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 &lt;, 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 &lt;, 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 &lt;, 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 &lt;, 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. $PEL(M!  + @@ @X+S@`  H.text  `.rsrc@@@.reloc `@B+H d  *( * * * * *0 +* *( * * * * *0 +* *( * *( *( * *( * *( * *( * *( *BSJB v4.0.30319l#~P#Stringsd #USl #GUID| #BlobG %3$' $  4>DO Yey!#=P =S =AJQZdn [ A ^ Ja Qd Zh d{ n~ = +w + + + + + =" =" ="" =## K$ =% _% =& s& =' ' =(    A J Q Z d nAJQZdn$,4<= =..   $"&(*,0 : >BF! $+4'      )##%')+-I<Module>CSharpExplicitInterfaceImplementation.dllInterfaceClassIGeneric`1Generic`1ConstructedIGenericInterface`1IndirectImplementationIGeneric2`1Outer`1IInner`1Inner1`1Inner2`1Inner3`1Inner4`1mscorlibSystemObjectTSUABCDMethodInterface.Method.ctorZIGeneric<S>.MethodVIGeneric<System.Int32>.MethodWIGeneric2<A>.MethodIGeneric2<T>.MethodOuter<T>.IInner<C>.MethodOuter<T>.IInner<T>.Methodtut1t2ss1s2vii1i2wabSystem.Runtime.CompilerServicesCompilationRelaxationsAttributeRuntimeCompatibilityAttributeCSharpExplicitInterfaceImplementation ʘSBB/%}̈z\V4$$,, 000 0 00000000   TWrapNonExceptionThrows++ +_CorDllMainmscoree.dll% @0HX@4VS_VERSION_INFO?DVarFileInfo$TranslationStringFileInfo000004b0,FileDescription 0FileVersion0.0.0.0t*InternalNameCSharpExplicitInterfaceImplementation.dll(LegalCopyright |*OriginalFilenameCSharpExplicitInterfaceImplementation.dll4ProductVersion0.0.0.08Assembly Version0.0.0.0 ;
MZ@ !L!This program cannot be run in DOS mode. $PEL(M!  + @@ @X+S@`  H.text  `.rsrc@@@.reloc `@B+H d  *( * * * * *0 +* *( * * * * *0 +* *( * *( *( * *( * *( * *( * *( *BSJB v4.0.30319l#~P#Stringsd #USl #GUID| #BlobG %3$' $  4>DO Yey!#=P =S =AJQZdn [ A ^ Ja Qd Zh d{ n~ = +w + + + + + =" =" ="" =## K$ =% _% =& s& =' ' =(    A J Q Z d nAJQZdn$,4<= =..   $"&(*,0 : >BF! $+4'      )##%')+-I<Module>CSharpExplicitInterfaceImplementation.dllInterfaceClassIGeneric`1Generic`1ConstructedIGenericInterface`1IndirectImplementationIGeneric2`1Outer`1IInner`1Inner1`1Inner2`1Inner3`1Inner4`1mscorlibSystemObjectTSUABCDMethodInterface.Method.ctorZIGeneric<S>.MethodVIGeneric<System.Int32>.MethodWIGeneric2<A>.MethodIGeneric2<T>.MethodOuter<T>.IInner<C>.MethodOuter<T>.IInner<T>.Methodtut1t2ss1s2vii1i2wabSystem.Runtime.CompilerServicesCompilationRelaxationsAttributeRuntimeCompatibilityAttributeCSharpExplicitInterfaceImplementation ʘSBB/%}̈z\V4$$,, 000 0 00000000   TWrapNonExceptionThrows++ +_CorDllMainmscoree.dll% @0HX@4VS_VERSION_INFO?DVarFileInfo$TranslationStringFileInfo000004b0,FileDescription 0FileVersion0.0.0.0t*InternalNameCSharpExplicitInterfaceImplementation.dll(LegalCopyright |*OriginalFilenameCSharpExplicitInterfaceImplementation.dll4ProductVersion0.0.0.08Assembly Version0.0.0.0 ;
-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
./docs/features/incremental-generators.md
# Incremental Generators ## Summary Incremental generators are intended to be a new API that exists alongside [source generators](generators.md) to allow users to specify generation strategies that can be applied in a high performance way by the hosting layer. ### High Level Design Goals - Allow for a finer grained approach to defining a generator - Scale source generators to support 'Roslyn/CoreCLR' scale projects in Visual Studio - Exploit caching between fine grained steps to reduce duplicate work - Support generating more items that just source texts - Exist alongside `ISourceGenerator` based implementations ## Implementation An incremental generator is an implementation of `Microsoft.CodeAnalysis.IIncrementalGenerator`. ```csharp namespace Microsoft.CodeAnalysis { public interface IIncrementalGenerator { void Initialize(IncrementalGeneratorInitializationContext initContext); } } ``` As with source generators, incremental generators are defined in external assemblies and passed to the compiler via the `-analyzer:` option. Implementations are required to be annotated with the `Microsoft.CodeAnalysis.GeneratorAttribute` with an optional parameter indicating the languages the generator supports: ```csharp [Generator(LanguageNames.CSharp)] public class MyGenerator : IIncrementalGenerator { ... } ``` An assembly can contain a mix of diagnostic analyzers, source generators and incremental generators. ### Initialization `IIncrementalGenerator` has an `Initialize` method that is called by the host (either the IDE or the command-line compiler) exactly once, regardless of the number of further compilations that may occur. `Initialize` passes an instance of `IncrementalGeneratorInitializationContext` which can be used by the generator to register a set of callbacks that affect how future generation passes will occur. Currently `IncrementalGeneratorInitializationContext` supports two callbacks: - `RegisterForPostInitialization(GeneratorPostInitializationContext)`: the same callback in shape and function as supported by Source Generators today - `RegisterExecutionPipeline(IncrementalGeneratorPipelineContext)`: replaces Execute, described below ### Pipeline based execution Rather than a dedicated `Execute` method, an Incremental Generator instead creates an execution 'pipeline' as part of the initialization process via the `RegisterExecutionPipeline` method: ```csharp public void Initialize(IncrementalGeneratorInitializationContext initContext) { initContext.RegisterExecutionPipeline(context => { // build the pipeline... }); } ``` This pipeline is not directly executed, but instead consists of a set of steps that are executed on demand as the input data to the pipeline changes. Between each step the data produced is cached, allowing previously calculated values to be reused in later computations when applicable, reducing the overall computation required between compilations. ### IncrementalValueSource&lt;T&gt; Input data is available to the pipeline in the form of an opaque data source, modelled as an `IncrementalValueSource<T>` where _T_ is the type of data that can be accessed in the pipeline. These sources are defined up front by the compiler, and can be accessed from the `Values` property of the `context` passed as part of the `RegisterExecutionPipeline` callback. Example values sources include - Compilation - AdditionalTexts - AnalyzerConfigOptions - MetadataReferences - ParseOptions Value sources have 'zero-or-more' potential values that can be produced. For example, the `Compilation` will always produce a single value, whereas the `AdditionalTexts` will produce a variable number of values, depending on how many additional texts where passed to the compiler. An execution pipeline cannot access these values directly. Instead it supplies a set of transforms that will be applied to the data as it changes. Transforms are applied through a set of extension methods: ```csharp public static partial class IncrementalValueSourceExtensions { // 1 => 1 transform public static IncrementalValueSource<U> Transform<T, U>(this IncrementalValueSource<T> source, Func<T, U> func) => ... } ``` These extension methods allow the user to perform a series of transforms, conceptually somewhat similar to LINQ, over the values coming from the data source: ```csharp initContext.RegisterExecutionPipeline(context => { // get the additional text source IncrementalValueSource<AdditionalText> additionalTexts = context.Sources.AdditionalTexts; // apply a 1-to-1 transform on each text, which represents extracting the path IncrementalValueSource<string> transformed = additionalTexts.Transform(static text => text.Path); }); ``` Note that `transformed` is similarly opaque. It represents the outcome of the transformation being applied to the data, but cannot be accessed directly. The transformed steps can be further transformed, and it is also valid to perform multiple transformations on the same input node, essentially 'splitting' the pipeline into multiple streams of processing. ```csharp // apply a 1-to-1 transform on each text, extracting the path IncrementalValueSource<string> transformed = additionalTexts.Transform(static text => text.Path); // split the processing into two streams of derived data IncrementalValueSource<string> prefixTransform = transformed.Transform(static path => "prefix_" + path); IncrementalValueSource<string> postfixTransform = transformed.Transform(static path => path + "_postfixed"); ``` ### Batching In addition to the 1-to-1 transform shown above, there are also extension methods for producing and consuming batches of data. For instance a given transform may want to produce more than one value for each input, or want to view all the data in a single collected view in order to make cross data decisions. ``` csharp public static partial class IncrementalValueSourceExtensions { // 1 => many (or none) public static IncrementalValueSource<U> TransformMany<T, U>(this IncrementalValueSource<T> source, Func<T, IEnumerable<U>> func) => ... // many => 1 public static IncrementalValueSource<U> BatchTransform<T, U>(this IncrementalValueSource<T> source, Func<IEnumerable<T>, U> func) => ... // many => many (or none) public static IncrementalValueSource<U> BatchTransformMany<T, U>(this IncrementalValueSource<T> source, Func<IEnumerable<T>, IEnumerable<U>> func) => ... } ``` In our above example we could use `BatchTransform` to collect the individual file paths collected, and convert them into a single collection: ``` csharp // apply a 1-to-1 transform on each text, which represents extracting the path IncrementalValueSource<string> transformed = additionalTexts.Transform(static text => text.Path); // batch the collected file paths into a single collection IncrementalValueSource<IEnumerable<string>> batched = transformed.BatchTransform(static paths => paths); ``` The author could have equally combined these two steps into a single operation that utilizes LINQ: ``` csharp // using System.Linq; IncrementalValueSource<IEnumerable<string>> singleOp = additionalTexts.BatchTransform(static texts => texts.Select(text => text.Path)); ``` **OPEN QUESTION** Should there be versions of `BatchTransform`/`BatchTransformMany` that take no transformation, and just perform the identity function as specified above? ### Outputting values At some point in the pipeline the author will want to actually use the transformed data to produce an output, such as a `SourceText`. For this purpose there are 'terminating' extension methods that allow the author to provide the resulting data the generator produces. The set of terminating extensions include: - GenerateSource - GenerateEmbeddedFile - GenerateArtifact GenerateSource for example looks like: ``` csharp static partial class IncrementalValueSourceExtensions { public internal static IncrementalGeneratorOutput GenerateSource<T>(this IncrementalValueSource<T> source, Action<SourceProductionContext, T> action) => ... } ``` That can be used by the author to supply `SourceText` to be appended to the compilation via the passed in `SourceProductionContext`: ``` csharp // take the file paths from the above batch and make some user visible syntax batched.GenerateSource(static (sourceProductionContext, filePaths) => { sourceProductionContext.AddSource("additionalFiles.cs", @" namespace Generated { public class AdditionalTextList { public static void PrintTexts() { System.Console.WriteLine(""Additional Texts were: " + string.Join(", ", filePaths) + @" ""); } } }"); }); ``` A generator may create and register multiple output nodes as part of the pipeline, but an output cannot be further transformed once it is created. Splitting the outputs by type produced allows the host (such as the IDE) to not run outputs that are not required. For instance artifacts are only produced as part of a command line build, so the IDE has no need to run the artifact based outputs or steps that feed into it. **OPEN QUESTION** Should we have `GenerateBatch...` versions of the output methods? This can already be achieved by the author calling `BatchTransform` before calling `Generate...` so would just be a helper, but seems common enough that it could be useful. ### Simple example Putting together the various steps outlined above, an example incremental generator might look like the following: ``` csharp [Generator(LanguageNames.CSharp)] public class MyGenerator : IIncrementalGenerator { public void Initialize(IncrementalGeneratorInitializationContext initContext) { initContext.RegisterExecutionPipeline(context => { // get the additional text source IncrementalValueSource<AdditionalText> additionalTexts = context.Sources.AdditionalTexts; // apply a 1-to-1 transform on each text, extracting the path IncrementalValueSource<string> transformed = additionalTexts.Transform(static text => text.Path); // batch the collected file paths into a single collection IncrementalValueSource<IEnumerable<string>> batched = transformed.BatchTransform(static paths => paths); // take the file paths from the above batch and make some user visible syntax batched.GenerateSource(static (sourceContext, filePaths) => { sourceContext.AddSource("additionalFiles.cs", @" namespace Generated { public class AdditionalTextList { public static void PrintTexts() { System.Console.WriteLine(""Additional Texts were: " + string.Join(", ", filePaths) + @" ""); } } }"); }); }); } } ``` ## Advanced Implementation ### Combining and filtering While the transformation steps outlined above allow a user to create simple generators from a single source of data, in reality it is expected that an author will need a way to take multiple sources of data and combine them. There exists an extension method `Combine` that allows the author to take one data source and merge it with another, for example, extracting a set of types from the compilation and using them to generate something on a per additional file basis. ```csharp public static partial class IncrementalValueSourceExtensions { // join 1 => many ((source1[0], source2), (source1[1], source2), (source1[2], source2), ...) public static IncrementalValueSource<(T source1Item, IEnumerable<U> source2Batch)> Combine<T, U>(this IncrementalValueSource<T> source1, IncrementalValueSource<U> source2) => ... } ``` The second data source is batched, and the resulting step has a value type of `(T, IEnumerable<U>)`. That is, a tuple where each element consists of a single item of data from `source1` combined with the entire batch of data from `source2`. While this is somewhat low-level, when combined with subsequent transforms, it gives the author the ability to combine an arbitrary number of data sources into any shape they require. In the following example the author combines the additional text source with the compilation: ```csharp IncrementalValueSource<(AdditionalText source1Item, IEnumerable<Compilation> source2Batch)> combined = context.Sources.AdditionalTexts.Combine(context.Sources.Compilation); ``` The type of combined is an `IncrementalValueSource<(AdditionalText, IEnumerable<Compilation>)>`. For each additional text, there is a tuple with the text, and the batched data of the compilation source. As the author knows that there is only ever a single compilation, they are free to transform the data to select the single compilation object: ```csharp IncrementalValueSource<(AdditionalText, Compilation)> transformed = combined.Transform(static pair => (pair.source1Item, pair.source2Batch.Single())); ``` Similarly a cross join can be achieved by first combining two value sources, then batch transforming the resulting value source. ```csharp IncrementalValueSource<(AdditionalText, MetadataReference)> combined = context.Sources.AdditionalTexts .Combine(context.Sources.MetadataReference) .TransformMany(static pair => pair.source2Batch.Select(static metadataRef => (pair.source1Item, metadataRef)); ``` **OPEN QUESTION**: Combine is pretty low level, but does allow you to do everything needed when used in conjunction with transform. Should we provide some higher level extension methods that chain together combine and transform out of the box for common operations? While filtering can be easily enough implement by the user as a transform step, it seems common and useful enough that we provide an implementation directly for the user to consume ```csharp static partial class IncrementalValueSourceExtensions { // helper for filtering values public static IncrementalValueSource<T> Filter<T>(this IncrementalValueSource<T> source, Func<T, bool> filter) => ... } ``` ### Caching While the finer grained steps allow for some coarse control of output types via the generator host, the performance benefits are only really seen when the driver can cache the outputs from one pipeline step to the next. While we have generally said that the execute method in an `ISourceGenerator` should be deterministic, incremental generators actively _require_ this property to be true. When calculating the required transformations to be applied as part of a step, the generator driver is free to look at inputs it has seen before and used previous computed and cached values of the transformation for these inputs. When using non batch transforms it can do this on an element by element basis. Consider the following transform: ```csharp IValueSource<string> transform = context.Sources.AdditionalTexts .Transform(static t => t.Path) .Transform(static p => "prefix_" + p); ``` During the first execution of the pipeline each of the two lambdas will be executed for each additional file: AdditionalText | Transform1 | Transform2 ------------------------|------------|----------------- Text{ Path: "abc.txt" } | "abc.txt" | "prefix_abc.txt" Text{ Path: "def.txt" } | "def.txt" | "prefix_def.txt" Text{ Path: "ghi.txt" } | "ghi.txt" | "prefix_ghi.txt" Now consider the case where in some future iteration, the first additional file has changed and has a different path, and the second file has changed, but kept its path the same. AdditionalText | Transform1 | Transform2 -----------------------------|------------|----------- **Text{ Path: "diff.txt" }** | | **Text{ Path: "def.txt" }** | | Text{ Path: "ghi.txt" } | | The generator would run transform1 on the first and second files, producing "diff.txt" and "def.txt" respectively. However, it would not need to re-run the transform for the third file, as the input has not changed. It can just use the previously cached value. AdditionalText | Transform1 | Transform2 -----------------------------|----------------|----------- **Text{ Path: "diff.txt" }** | **"diff.txt"** | **Text{ Path: "def.txt" }** | **"def.txt"** | Text{ Path: "ghi.txt" } | "ghi.txt" | Next the driver would look to run Transform2. It would operate on `"diff.txt"` producing `"prefix_diff.txt"`, but when it comes to `"def.txt"` it can observe that the item produced was the same as the last iteration. Even though the original input (`Text{ Path: "def.txt" }`) was changed, the result of Transform1 on it was the same. Thus there is no need to re-run Transform2 on `"def.txt"` as it can just use the cached value from before. Similarly the cached state of "ghi.txt" can be used. AdditionalText | Transform1 | Transform2 -----------------------------|----------------|---------------------- **Text{ Path: "diff.txt" }** | **"diff.txt"** | **"prefix_diff.txt"** **Text{ Path: "def.txt" }** | **"def.txt"** | "prefix_diff.txt" Text{ Path: "ghi.txt" } | "ghi.txt" | "prefix_ghi.txt" In this way, only changes that are consequential flow through the pipeline, and duplicate work is avoided. If a generator only relies on `AdditionalTexts` then the driver knows there can be no work to be done when a `SyntaxTree` changes. ### WithComparer For a user provided result to be comparable across iterations, there needs to be some concept of equivalence. Rather than requiring types returned from transformations implement `IEquatable<T>`, there exists an extension method that allows the author to supply a comparer that should be used when comparing values for the given transformation: ```csharp public static partial class IncrementalValueSourceExtensions { public static IncrementalValueSource<T> WithComparer(IEqualityComparer<T> comparer) => ... } ``` Allowing the user to specify a given comparer. ```csharp var withComparer = context.Sources.AdditionalTexts .Transform(t => t.Path) .WithComparer(myComparer); ``` Note that the comparer is on a per-transformation basis, meaning an author can specify different comparers for different parts of the pipeline. ```csharp var transform = context.Sources.AdditionalTexts.Transform(t => t.Path); var noCompareTransform = transform.Transform(...); var compareTransform = transform.WithComparer(myComparer).Transform(...); ``` The same transform node can have no comparer when acting as input to one step, and still provide one when acting as input to a different step. **OPEN QUESTION**: This again gives maximal flexibility, but might be annoying if you have lots of custom data structures that you use in multiple places. Should we consider allowing the author to specify a set of 'default' comparers that apply to all transforms unless overridden? **OPEN QUESTION**: `IValueComparer<T>` seems like the correct type to use, but can be less ergonomic as it requires the author to define a type not inline and reference it here. Should we provided a 'functional' overload that creates the equality comparer for the author under the hood given a lambda? ### Syntax Trees ## Internal Implementation TK: compiler specific implementation. StateTables etc. ### Hosting ISourceGenerator on the new APIs
# Incremental Generators ## Summary Incremental generators are intended to be a new API that exists alongside [source generators](generators.md) to allow users to specify generation strategies that can be applied in a high performance way by the hosting layer. ### High Level Design Goals - Allow for a finer grained approach to defining a generator - Scale source generators to support 'Roslyn/CoreCLR' scale projects in Visual Studio - Exploit caching between fine grained steps to reduce duplicate work - Support generating more items that just source texts - Exist alongside `ISourceGenerator` based implementations ## Implementation An incremental generator is an implementation of `Microsoft.CodeAnalysis.IIncrementalGenerator`. ```csharp namespace Microsoft.CodeAnalysis { public interface IIncrementalGenerator { void Initialize(IncrementalGeneratorInitializationContext initContext); } } ``` As with source generators, incremental generators are defined in external assemblies and passed to the compiler via the `-analyzer:` option. Implementations are required to be annotated with the `Microsoft.CodeAnalysis.GeneratorAttribute` with an optional parameter indicating the languages the generator supports: ```csharp [Generator(LanguageNames.CSharp)] public class MyGenerator : IIncrementalGenerator { ... } ``` An assembly can contain a mix of diagnostic analyzers, source generators and incremental generators. ### Initialization `IIncrementalGenerator` has an `Initialize` method that is called by the host (either the IDE or the command-line compiler) exactly once, regardless of the number of further compilations that may occur. `Initialize` passes an instance of `IncrementalGeneratorInitializationContext` which can be used by the generator to register a set of callbacks that affect how future generation passes will occur. Currently `IncrementalGeneratorInitializationContext` supports two callbacks: - `RegisterForPostInitialization(GeneratorPostInitializationContext)`: the same callback in shape and function as supported by Source Generators today - `RegisterExecutionPipeline(IncrementalGeneratorPipelineContext)`: replaces Execute, described below ### Pipeline based execution Rather than a dedicated `Execute` method, an Incremental Generator instead creates an execution 'pipeline' as part of the initialization process via the `RegisterExecutionPipeline` method: ```csharp public void Initialize(IncrementalGeneratorInitializationContext initContext) { initContext.RegisterExecutionPipeline(context => { // build the pipeline... }); } ``` This pipeline is not directly executed, but instead consists of a set of steps that are executed on demand as the input data to the pipeline changes. Between each step the data produced is cached, allowing previously calculated values to be reused in later computations when applicable, reducing the overall computation required between compilations. ### IncrementalValueSource&lt;T&gt; Input data is available to the pipeline in the form of an opaque data source, modelled as an `IncrementalValueSource<T>` where _T_ is the type of data that can be accessed in the pipeline. These sources are defined up front by the compiler, and can be accessed from the `Values` property of the `context` passed as part of the `RegisterExecutionPipeline` callback. Example values sources include - Compilation - AdditionalTexts - AnalyzerConfigOptions - MetadataReferences - ParseOptions Value sources have 'zero-or-more' potential values that can be produced. For example, the `Compilation` will always produce a single value, whereas the `AdditionalTexts` will produce a variable number of values, depending on how many additional texts where passed to the compiler. An execution pipeline cannot access these values directly. Instead it supplies a set of transforms that will be applied to the data as it changes. Transforms are applied through a set of extension methods: ```csharp public static partial class IncrementalValueSourceExtensions { // 1 => 1 transform public static IncrementalValueSource<U> Transform<T, U>(this IncrementalValueSource<T> source, Func<T, U> func) => ... } ``` These extension methods allow the user to perform a series of transforms, conceptually somewhat similar to LINQ, over the values coming from the data source: ```csharp initContext.RegisterExecutionPipeline(context => { // get the additional text source IncrementalValueSource<AdditionalText> additionalTexts = context.Sources.AdditionalTexts; // apply a 1-to-1 transform on each text, which represents extracting the path IncrementalValueSource<string> transformed = additionalTexts.Transform(static text => text.Path); }); ``` Note that `transformed` is similarly opaque. It represents the outcome of the transformation being applied to the data, but cannot be accessed directly. The transformed steps can be further transformed, and it is also valid to perform multiple transformations on the same input node, essentially 'splitting' the pipeline into multiple streams of processing. ```csharp // apply a 1-to-1 transform on each text, extracting the path IncrementalValueSource<string> transformed = additionalTexts.Transform(static text => text.Path); // split the processing into two streams of derived data IncrementalValueSource<string> prefixTransform = transformed.Transform(static path => "prefix_" + path); IncrementalValueSource<string> postfixTransform = transformed.Transform(static path => path + "_postfixed"); ``` ### Batching In addition to the 1-to-1 transform shown above, there are also extension methods for producing and consuming batches of data. For instance a given transform may want to produce more than one value for each input, or want to view all the data in a single collected view in order to make cross data decisions. ``` csharp public static partial class IncrementalValueSourceExtensions { // 1 => many (or none) public static IncrementalValueSource<U> TransformMany<T, U>(this IncrementalValueSource<T> source, Func<T, IEnumerable<U>> func) => ... // many => 1 public static IncrementalValueSource<U> BatchTransform<T, U>(this IncrementalValueSource<T> source, Func<IEnumerable<T>, U> func) => ... // many => many (or none) public static IncrementalValueSource<U> BatchTransformMany<T, U>(this IncrementalValueSource<T> source, Func<IEnumerable<T>, IEnumerable<U>> func) => ... } ``` In our above example we could use `BatchTransform` to collect the individual file paths collected, and convert them into a single collection: ``` csharp // apply a 1-to-1 transform on each text, which represents extracting the path IncrementalValueSource<string> transformed = additionalTexts.Transform(static text => text.Path); // batch the collected file paths into a single collection IncrementalValueSource<IEnumerable<string>> batched = transformed.BatchTransform(static paths => paths); ``` The author could have equally combined these two steps into a single operation that utilizes LINQ: ``` csharp // using System.Linq; IncrementalValueSource<IEnumerable<string>> singleOp = additionalTexts.BatchTransform(static texts => texts.Select(text => text.Path)); ``` **OPEN QUESTION** Should there be versions of `BatchTransform`/`BatchTransformMany` that take no transformation, and just perform the identity function as specified above? ### Outputting values At some point in the pipeline the author will want to actually use the transformed data to produce an output, such as a `SourceText`. For this purpose there are 'terminating' extension methods that allow the author to provide the resulting data the generator produces. The set of terminating extensions include: - GenerateSource - GenerateEmbeddedFile - GenerateArtifact GenerateSource for example looks like: ``` csharp static partial class IncrementalValueSourceExtensions { public internal static IncrementalGeneratorOutput GenerateSource<T>(this IncrementalValueSource<T> source, Action<SourceProductionContext, T> action) => ... } ``` That can be used by the author to supply `SourceText` to be appended to the compilation via the passed in `SourceProductionContext`: ``` csharp // take the file paths from the above batch and make some user visible syntax batched.GenerateSource(static (sourceProductionContext, filePaths) => { sourceProductionContext.AddSource("additionalFiles.cs", @" namespace Generated { public class AdditionalTextList { public static void PrintTexts() { System.Console.WriteLine(""Additional Texts were: " + string.Join(", ", filePaths) + @" ""); } } }"); }); ``` A generator may create and register multiple output nodes as part of the pipeline, but an output cannot be further transformed once it is created. Splitting the outputs by type produced allows the host (such as the IDE) to not run outputs that are not required. For instance artifacts are only produced as part of a command line build, so the IDE has no need to run the artifact based outputs or steps that feed into it. **OPEN QUESTION** Should we have `GenerateBatch...` versions of the output methods? This can already be achieved by the author calling `BatchTransform` before calling `Generate...` so would just be a helper, but seems common enough that it could be useful. ### Simple example Putting together the various steps outlined above, an example incremental generator might look like the following: ``` csharp [Generator(LanguageNames.CSharp)] public class MyGenerator : IIncrementalGenerator { public void Initialize(IncrementalGeneratorInitializationContext initContext) { initContext.RegisterExecutionPipeline(context => { // get the additional text source IncrementalValueSource<AdditionalText> additionalTexts = context.Sources.AdditionalTexts; // apply a 1-to-1 transform on each text, extracting the path IncrementalValueSource<string> transformed = additionalTexts.Transform(static text => text.Path); // batch the collected file paths into a single collection IncrementalValueSource<IEnumerable<string>> batched = transformed.BatchTransform(static paths => paths); // take the file paths from the above batch and make some user visible syntax batched.GenerateSource(static (sourceContext, filePaths) => { sourceContext.AddSource("additionalFiles.cs", @" namespace Generated { public class AdditionalTextList { public static void PrintTexts() { System.Console.WriteLine(""Additional Texts were: " + string.Join(", ", filePaths) + @" ""); } } }"); }); }); } } ``` ## Advanced Implementation ### Combining and filtering While the transformation steps outlined above allow a user to create simple generators from a single source of data, in reality it is expected that an author will need a way to take multiple sources of data and combine them. There exists an extension method `Combine` that allows the author to take one data source and merge it with another, for example, extracting a set of types from the compilation and using them to generate something on a per additional file basis. ```csharp public static partial class IncrementalValueSourceExtensions { // join 1 => many ((source1[0], source2), (source1[1], source2), (source1[2], source2), ...) public static IncrementalValueSource<(T source1Item, IEnumerable<U> source2Batch)> Combine<T, U>(this IncrementalValueSource<T> source1, IncrementalValueSource<U> source2) => ... } ``` The second data source is batched, and the resulting step has a value type of `(T, IEnumerable<U>)`. That is, a tuple where each element consists of a single item of data from `source1` combined with the entire batch of data from `source2`. While this is somewhat low-level, when combined with subsequent transforms, it gives the author the ability to combine an arbitrary number of data sources into any shape they require. In the following example the author combines the additional text source with the compilation: ```csharp IncrementalValueSource<(AdditionalText source1Item, IEnumerable<Compilation> source2Batch)> combined = context.Sources.AdditionalTexts.Combine(context.Sources.Compilation); ``` The type of combined is an `IncrementalValueSource<(AdditionalText, IEnumerable<Compilation>)>`. For each additional text, there is a tuple with the text, and the batched data of the compilation source. As the author knows that there is only ever a single compilation, they are free to transform the data to select the single compilation object: ```csharp IncrementalValueSource<(AdditionalText, Compilation)> transformed = combined.Transform(static pair => (pair.source1Item, pair.source2Batch.Single())); ``` Similarly a cross join can be achieved by first combining two value sources, then batch transforming the resulting value source. ```csharp IncrementalValueSource<(AdditionalText, MetadataReference)> combined = context.Sources.AdditionalTexts .Combine(context.Sources.MetadataReference) .TransformMany(static pair => pair.source2Batch.Select(static metadataRef => (pair.source1Item, metadataRef)); ``` **OPEN QUESTION**: Combine is pretty low level, but does allow you to do everything needed when used in conjunction with transform. Should we provide some higher level extension methods that chain together combine and transform out of the box for common operations? While filtering can be easily enough implement by the user as a transform step, it seems common and useful enough that we provide an implementation directly for the user to consume ```csharp static partial class IncrementalValueSourceExtensions { // helper for filtering values public static IncrementalValueSource<T> Filter<T>(this IncrementalValueSource<T> source, Func<T, bool> filter) => ... } ``` ### Caching While the finer grained steps allow for some coarse control of output types via the generator host, the performance benefits are only really seen when the driver can cache the outputs from one pipeline step to the next. While we have generally said that the execute method in an `ISourceGenerator` should be deterministic, incremental generators actively _require_ this property to be true. When calculating the required transformations to be applied as part of a step, the generator driver is free to look at inputs it has seen before and used previous computed and cached values of the transformation for these inputs. When using non batch transforms it can do this on an element by element basis. Consider the following transform: ```csharp IValueSource<string> transform = context.Sources.AdditionalTexts .Transform(static t => t.Path) .Transform(static p => "prefix_" + p); ``` During the first execution of the pipeline each of the two lambdas will be executed for each additional file: AdditionalText | Transform1 | Transform2 ------------------------|------------|----------------- Text{ Path: "abc.txt" } | "abc.txt" | "prefix_abc.txt" Text{ Path: "def.txt" } | "def.txt" | "prefix_def.txt" Text{ Path: "ghi.txt" } | "ghi.txt" | "prefix_ghi.txt" Now consider the case where in some future iteration, the first additional file has changed and has a different path, and the second file has changed, but kept its path the same. AdditionalText | Transform1 | Transform2 -----------------------------|------------|----------- **Text{ Path: "diff.txt" }** | | **Text{ Path: "def.txt" }** | | Text{ Path: "ghi.txt" } | | The generator would run transform1 on the first and second files, producing "diff.txt" and "def.txt" respectively. However, it would not need to re-run the transform for the third file, as the input has not changed. It can just use the previously cached value. AdditionalText | Transform1 | Transform2 -----------------------------|----------------|----------- **Text{ Path: "diff.txt" }** | **"diff.txt"** | **Text{ Path: "def.txt" }** | **"def.txt"** | Text{ Path: "ghi.txt" } | "ghi.txt" | Next the driver would look to run Transform2. It would operate on `"diff.txt"` producing `"prefix_diff.txt"`, but when it comes to `"def.txt"` it can observe that the item produced was the same as the last iteration. Even though the original input (`Text{ Path: "def.txt" }`) was changed, the result of Transform1 on it was the same. Thus there is no need to re-run Transform2 on `"def.txt"` as it can just use the cached value from before. Similarly the cached state of "ghi.txt" can be used. AdditionalText | Transform1 | Transform2 -----------------------------|----------------|---------------------- **Text{ Path: "diff.txt" }** | **"diff.txt"** | **"prefix_diff.txt"** **Text{ Path: "def.txt" }** | **"def.txt"** | "prefix_diff.txt" Text{ Path: "ghi.txt" } | "ghi.txt" | "prefix_ghi.txt" In this way, only changes that are consequential flow through the pipeline, and duplicate work is avoided. If a generator only relies on `AdditionalTexts` then the driver knows there can be no work to be done when a `SyntaxTree` changes. ### WithComparer For a user provided result to be comparable across iterations, there needs to be some concept of equivalence. Rather than requiring types returned from transformations implement `IEquatable<T>`, there exists an extension method that allows the author to supply a comparer that should be used when comparing values for the given transformation: ```csharp public static partial class IncrementalValueSourceExtensions { public static IncrementalValueSource<T> WithComparer(IEqualityComparer<T> comparer) => ... } ``` Allowing the user to specify a given comparer. ```csharp var withComparer = context.Sources.AdditionalTexts .Transform(t => t.Path) .WithComparer(myComparer); ``` Note that the comparer is on a per-transformation basis, meaning an author can specify different comparers for different parts of the pipeline. ```csharp var transform = context.Sources.AdditionalTexts.Transform(t => t.Path); var noCompareTransform = transform.Transform(...); var compareTransform = transform.WithComparer(myComparer).Transform(...); ``` The same transform node can have no comparer when acting as input to one step, and still provide one when acting as input to a different step. **OPEN QUESTION**: This again gives maximal flexibility, but might be annoying if you have lots of custom data structures that you use in multiple places. Should we consider allowing the author to specify a set of 'default' comparers that apply to all transforms unless overridden? **OPEN QUESTION**: `IValueComparer<T>` seems like the correct type to use, but can be less ergonomic as it requires the author to define a type not inline and reference it here. Should we provided a 'functional' overload that creates the equality comparer for the author under the hood given a lambda? ### Syntax Trees ## Internal Implementation TK: compiler specific implementation. StateTables etc. ### Hosting ISourceGenerator on the new APIs
-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/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/xlf/Resources.ko.xlf
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="ko" original="../Resources.resx"> <body> <trans-unit id="InvalidDebuggerStatement"> <source>Statements of type '{0}' are not allowed in the Immediate window.</source> <target state="translated">'{0}' 형식의 문은 직접 실행 창에서 허용되지 않습니다.</target> <note /> </trans-unit> </body> </file> </xliff>
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="ko" original="../Resources.resx"> <body> <trans-unit id="InvalidDebuggerStatement"> <source>Statements of type '{0}' are not allowed in the Immediate window.</source> <target state="translated">'{0}' 형식의 문은 직접 실행 창에서 허용되지 않습니다.</target> <note /> </trans-unit> </body> </file> </xliff>
-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/CSharp/Portable/Completion/CompletionProviders/Scripting/LoadDirectiveCompletionProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using System.Threading; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.CSharp.Completion.Providers { [ExportCompletionProvider(nameof(LoadDirectiveCompletionProvider), LanguageNames.CSharp)] [ExtensionOrder(After = nameof(FunctionPointerUnmanagedCallingConventionCompletionProvider))] [Shared] internal sealed class LoadDirectiveCompletionProvider : AbstractLoadDirectiveCompletionProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public LoadDirectiveCompletionProvider() { } protected override string DirectiveName => "load"; protected override bool TryGetStringLiteralToken(SyntaxTree tree, int position, out SyntaxToken stringLiteral, CancellationToken cancellationToken) => DirectiveCompletionProviderUtilities.TryGetStringLiteralToken(tree, position, SyntaxKind.LoadDirectiveTrivia, out stringLiteral, cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using System.Threading; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.CSharp.Completion.Providers { [ExportCompletionProvider(nameof(LoadDirectiveCompletionProvider), LanguageNames.CSharp)] [ExtensionOrder(After = nameof(FunctionPointerUnmanagedCallingConventionCompletionProvider))] [Shared] internal sealed class LoadDirectiveCompletionProvider : AbstractLoadDirectiveCompletionProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public LoadDirectiveCompletionProvider() { } protected override string DirectiveName => "load"; protected override bool TryGetStringLiteralToken(SyntaxTree tree, int position, out SyntaxToken stringLiteral, CancellationToken cancellationToken) => DirectiveCompletionProviderUtilities.TryGetStringLiteralToken(tree, position, SyntaxKind.LoadDirectiveTrivia, out stringLiteral, cancellationToken); } }
-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/EditorConfigSettings/Whitespace/View/ColumnDefnitions/WhitespaceCategoryColumnDefinition.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.ComponentModel.Composition; using System.Windows; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Shell.TableControl; using Microsoft.VisualStudio.Shell.TableManager; using Microsoft.VisualStudio.Utilities; using static Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Common.ColumnDefinitions.Whitespace; namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Whitespace.View.ColumnDefnitions { [Export(typeof(IDefaultColumnGroup))] [Name(nameof(WhitespaceCategoryGroupingSet))] // Required, name of the default group [GroupColumns(Category)] // Required, the names of the columns in the grouping internal class WhitespaceCategoryGroupingSet : IDefaultColumnGroup { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public WhitespaceCategoryGroupingSet() { } } [Export(typeof(ITableColumnDefinition))] [Name(Category)] internal class WhitespaceCategoryColumnDefinition : TableColumnDefinitionBase { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public WhitespaceCategoryColumnDefinition() { } public override string Name => Category; public override string DisplayName => ServicesVSResources.Category; public override double MinWidth => 80; public override bool DefaultVisible => false; public override bool IsFilterable => true; public override bool IsSortable => true; public override TextWrapping TextWrapping => TextWrapping.NoWrap; private static string? GetCategoryName(ITableEntryHandle entry) => entry.TryGetValue(Category, out string? categoryName) ? categoryName : null; public override IEntryBucket? CreateBucketForEntry(ITableEntryHandle entry) { var categoryName = GetCategoryName(entry); return categoryName is not null ? new StringEntryBucket(GetCategoryName(entry)) : null; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.ComponentModel.Composition; using System.Windows; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Shell.TableControl; using Microsoft.VisualStudio.Shell.TableManager; using Microsoft.VisualStudio.Utilities; using static Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Common.ColumnDefinitions.Whitespace; namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Whitespace.View.ColumnDefnitions { [Export(typeof(IDefaultColumnGroup))] [Name(nameof(WhitespaceCategoryGroupingSet))] // Required, name of the default group [GroupColumns(Category)] // Required, the names of the columns in the grouping internal class WhitespaceCategoryGroupingSet : IDefaultColumnGroup { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public WhitespaceCategoryGroupingSet() { } } [Export(typeof(ITableColumnDefinition))] [Name(Category)] internal class WhitespaceCategoryColumnDefinition : TableColumnDefinitionBase { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public WhitespaceCategoryColumnDefinition() { } public override string Name => Category; public override string DisplayName => ServicesVSResources.Category; public override double MinWidth => 80; public override bool DefaultVisible => false; public override bool IsFilterable => true; public override bool IsSortable => true; public override TextWrapping TextWrapping => TextWrapping.NoWrap; private static string? GetCategoryName(ITableEntryHandle entry) => entry.TryGetValue(Category, out string? categoryName) ? categoryName : null; public override IEntryBucket? CreateBucketForEntry(ITableEntryHandle entry) { var categoryName = GetCategoryName(entry); return categoryName is not null ? new StringEntryBucket(GetCategoryName(entry)) : null; } } }
-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/UseSiteDiagnosticsCheckEnforcer/Run.bat
REM Licensed to the .NET Foundation under one or more agreements. REM The .NET Foundation licenses this file to you under the MIT license. REM See the LICENSE file in the project root for more information. @REM %1 - OutDir @REM %2 - TargetFileName @REM %3 - TargetPath @REM %4 - ProjectDir @REM %5 - ILDASMPath @REM @echo %1 @REM @echo %2 @REM @echo %3 @REM @echo %4 @REM @echo %5 @echo Begin "%4UseSiteDiagnosticsCheckEnforcer\Run.bat" %1 %2 %3 %4 %5 @set WorkFolder="%1%CSUseSiteChecks" @set ILFileName="%2%.il" @set TargetPath="%3%" @set BaseLine="%4%UseSiteDiagnosticsCheckEnforcer\BaseLine.txt" @set ILDASMPath=%5% @IF NOT EXIST %WorkFolder% ( @goto label_md ) @rd /S /Q %WorkFolder% @IF ERRORLEVEL 1 ( @goto label_rdFailed ) :label_md @md %WorkFolder% @IF ERRORLEVEL 1 ( @goto label_mdFailed ) @pushd %WorkFolder% @%ILDASMPath% /NOBAR /OUT=%ILFileName% %TargetPath% @IF ERRORLEVEL 1 ( @goto label_ildasmFailed ) @findstr /C:Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol::get_BaseType() %ILFileName% > Found.txt @findstr /C:Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol::get_Interfaces() %ILFileName% >> Found.txt @findstr /C:Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol::get_AllInterfaces() %ILFileName% >> Found.txt @findstr /C:Microsoft.CodeAnalysis.CSharp.Symbols.NamedTypeSymbol::get_TypeArguments() %ILFileName% >> Found.txt @findstr /C:Microsoft.CodeAnalysis.CSharp.Symbols.TypeParameterSymbol::get_ConstraintTypes() %ILFileName% >> Found.txt @REM notepad Found.txt @fc %BaseLine% Found.txt > ComparisonResult.txt @IF ERRORLEVEL 1 ( @goto label_baselineMismatch ) @popd @rd /S /Q %WorkFolder% @echo End "%4%UseSiteDiagnosticsCheckEnforcer\Run.bat" @EXIT /B 0 :label_baselineMismatch @ECHO ********** Unexpected IL content in %TargetPath% @TYPE ComparisonResult.txt @ECHO ********** @popd @rd /S /Q %WorkFolder% @EXIT /B 1 :label_ildasmFailed @ECHO ILDASM failed for: %TargetPath% @echo %ILDASMPath% /NOBAR /OUT=%ILFileName% %TargetPath% @popd @rd /S /Q %WorkFolder% @EXIT /B 1 :label_rdFailed @ECHO Failed to delete temporary working folder: "%WorkFolder%" @EXIT /B 1 :label_mdFailed @ECHO Failed to create temporary working folder: "%WorkFolder%" @EXIT /B 1
REM Licensed to the .NET Foundation under one or more agreements. REM The .NET Foundation licenses this file to you under the MIT license. REM See the LICENSE file in the project root for more information. @REM %1 - OutDir @REM %2 - TargetFileName @REM %3 - TargetPath @REM %4 - ProjectDir @REM %5 - ILDASMPath @REM @echo %1 @REM @echo %2 @REM @echo %3 @REM @echo %4 @REM @echo %5 @echo Begin "%4UseSiteDiagnosticsCheckEnforcer\Run.bat" %1 %2 %3 %4 %5 @set WorkFolder="%1%CSUseSiteChecks" @set ILFileName="%2%.il" @set TargetPath="%3%" @set BaseLine="%4%UseSiteDiagnosticsCheckEnforcer\BaseLine.txt" @set ILDASMPath=%5% @IF NOT EXIST %WorkFolder% ( @goto label_md ) @rd /S /Q %WorkFolder% @IF ERRORLEVEL 1 ( @goto label_rdFailed ) :label_md @md %WorkFolder% @IF ERRORLEVEL 1 ( @goto label_mdFailed ) @pushd %WorkFolder% @%ILDASMPath% /NOBAR /OUT=%ILFileName% %TargetPath% @IF ERRORLEVEL 1 ( @goto label_ildasmFailed ) @findstr /C:Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol::get_BaseType() %ILFileName% > Found.txt @findstr /C:Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol::get_Interfaces() %ILFileName% >> Found.txt @findstr /C:Microsoft.CodeAnalysis.CSharp.Symbols.TypeSymbol::get_AllInterfaces() %ILFileName% >> Found.txt @findstr /C:Microsoft.CodeAnalysis.CSharp.Symbols.NamedTypeSymbol::get_TypeArguments() %ILFileName% >> Found.txt @findstr /C:Microsoft.CodeAnalysis.CSharp.Symbols.TypeParameterSymbol::get_ConstraintTypes() %ILFileName% >> Found.txt @REM notepad Found.txt @fc %BaseLine% Found.txt > ComparisonResult.txt @IF ERRORLEVEL 1 ( @goto label_baselineMismatch ) @popd @rd /S /Q %WorkFolder% @echo End "%4%UseSiteDiagnosticsCheckEnforcer\Run.bat" @EXIT /B 0 :label_baselineMismatch @ECHO ********** Unexpected IL content in %TargetPath% @TYPE ComparisonResult.txt @ECHO ********** @popd @rd /S /Q %WorkFolder% @EXIT /B 1 :label_ildasmFailed @ECHO ILDASM failed for: %TargetPath% @echo %ILDASMPath% /NOBAR /OUT=%ILFileName% %TargetPath% @popd @rd /S /Q %WorkFolder% @EXIT /B 1 :label_rdFailed @ECHO Failed to delete temporary working folder: "%WorkFolder%" @EXIT /B 1 :label_mdFailed @ECHO Failed to create temporary working folder: "%WorkFolder%" @EXIT /B 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/Compilers/CSharp/Portable/Emitter/Model/SpecializedGenericNestedTypeInstanceReference.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.PooledObjects; using System.Diagnostics; using System.Linq; namespace Microsoft.CodeAnalysis.CSharp.Emit { /// <summary> /// Represents a reference to an instantiation of a generic type nested in an instantiation of another generic type. /// e.g. /// A{int}.B{string} /// A.B{int}.C.D{string} /// </summary> internal sealed class SpecializedGenericNestedTypeInstanceReference : SpecializedNestedTypeReference, Cci.IGenericTypeInstanceReference { public SpecializedGenericNestedTypeInstanceReference(NamedTypeSymbol underlyingNamedType) : base(underlyingNamedType) { Debug.Assert(underlyingNamedType.IsDefinition); // Definition doesn't have custom modifiers on type arguments Debug.Assert(!underlyingNamedType.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.Any(a => a.CustomModifiers.Any())); } public sealed override void Dispatch(Cci.MetadataVisitor visitor) { visitor.Visit((Cci.IGenericTypeInstanceReference)this); } ImmutableArray<Cci.ITypeReference> Cci.IGenericTypeInstanceReference.GetGenericArguments(EmitContext context) { PEModuleBuilder moduleBeingBuilt = (PEModuleBuilder)context.Module; var builder = ArrayBuilder<Cci.ITypeReference>.GetInstance(); foreach (TypeWithAnnotations type in UnderlyingNamedType.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics) { builder.Add(moduleBeingBuilt.Translate(type.Type, syntaxNodeOpt: (CSharpSyntaxNode)context.SyntaxNode, diagnostics: context.Diagnostics)); } return builder.ToImmutableAndFree(); } Cci.INamedTypeReference Cci.IGenericTypeInstanceReference.GetGenericType(EmitContext context) { System.Diagnostics.Debug.Assert(UnderlyingNamedType.OriginalDefinition.IsDefinition); PEModuleBuilder moduleBeingBuilt = (PEModuleBuilder)context.Module; return moduleBeingBuilt.Translate(this.UnderlyingNamedType.OriginalDefinition, syntaxNodeOpt: (CSharpSyntaxNode)context.SyntaxNode, diagnostics: context.Diagnostics, needDeclaration: true); } public override Cci.IGenericTypeInstanceReference AsGenericTypeInstanceReference { get { return this; } } public override Cci.INamespaceTypeReference AsNamespaceTypeReference { get { return null; } } public override Cci.INestedTypeReference AsNestedTypeReference { get { return this; } } public override Cci.ISpecializedNestedTypeReference AsSpecializedNestedTypeReference { get { return null; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.PooledObjects; using System.Diagnostics; using System.Linq; namespace Microsoft.CodeAnalysis.CSharp.Emit { /// <summary> /// Represents a reference to an instantiation of a generic type nested in an instantiation of another generic type. /// e.g. /// A{int}.B{string} /// A.B{int}.C.D{string} /// </summary> internal sealed class SpecializedGenericNestedTypeInstanceReference : SpecializedNestedTypeReference, Cci.IGenericTypeInstanceReference { public SpecializedGenericNestedTypeInstanceReference(NamedTypeSymbol underlyingNamedType) : base(underlyingNamedType) { Debug.Assert(underlyingNamedType.IsDefinition); // Definition doesn't have custom modifiers on type arguments Debug.Assert(!underlyingNamedType.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.Any(a => a.CustomModifiers.Any())); } public sealed override void Dispatch(Cci.MetadataVisitor visitor) { visitor.Visit((Cci.IGenericTypeInstanceReference)this); } ImmutableArray<Cci.ITypeReference> Cci.IGenericTypeInstanceReference.GetGenericArguments(EmitContext context) { PEModuleBuilder moduleBeingBuilt = (PEModuleBuilder)context.Module; var builder = ArrayBuilder<Cci.ITypeReference>.GetInstance(); foreach (TypeWithAnnotations type in UnderlyingNamedType.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics) { builder.Add(moduleBeingBuilt.Translate(type.Type, syntaxNodeOpt: (CSharpSyntaxNode)context.SyntaxNode, diagnostics: context.Diagnostics)); } return builder.ToImmutableAndFree(); } Cci.INamedTypeReference Cci.IGenericTypeInstanceReference.GetGenericType(EmitContext context) { System.Diagnostics.Debug.Assert(UnderlyingNamedType.OriginalDefinition.IsDefinition); PEModuleBuilder moduleBeingBuilt = (PEModuleBuilder)context.Module; return moduleBeingBuilt.Translate(this.UnderlyingNamedType.OriginalDefinition, syntaxNodeOpt: (CSharpSyntaxNode)context.SyntaxNode, diagnostics: context.Diagnostics, needDeclaration: true); } public override Cci.IGenericTypeInstanceReference AsGenericTypeInstanceReference { get { return this; } } public override Cci.INamespaceTypeReference AsNamespaceTypeReference { get { return null; } } public override Cci.INestedTypeReference AsNestedTypeReference { get { return this; } } public override Cci.ISpecializedNestedTypeReference AsSpecializedNestedTypeReference { get { return null; } } } }
-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/Workspace/GlobalUndoServiceFactory.WorkspaceGlobalUndoTransaction.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Diagnostics; using System.Runtime.InteropServices; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Editor.Undo; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.Text.Operations; using Microsoft.VisualStudio.TextManager.Interop; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation { using Workspace = Microsoft.CodeAnalysis.Workspace; internal partial class GlobalUndoServiceFactory { private class WorkspaceUndoTransaction : ForegroundThreadAffinitizedObject, IWorkspaceGlobalUndoTransaction { private readonly ITextUndoHistoryRegistry _undoHistoryRegistry; private readonly IVsLinkedUndoTransactionManager _undoManager; private readonly Workspace _workspace; private readonly string _description; private readonly GlobalUndoService _service; // indicate whether undo transaction is currently active private bool _transactionAlive; public WorkspaceUndoTransaction( IThreadingContext threadingContext, ITextUndoHistoryRegistry undoHistoryRegistry, IVsLinkedUndoTransactionManager undoManager, Workspace workspace, string description, GlobalUndoService service) : base(threadingContext, assertIsForeground: true) { _undoHistoryRegistry = undoHistoryRegistry; _undoManager = undoManager; _workspace = workspace; _description = description; _service = service; Marshal.ThrowExceptionForHR(_undoManager.OpenLinkedUndo((uint)LinkedTransactionFlags2.mdtGlobal, _description)); _transactionAlive = true; } public void AddDocument(DocumentId id) { var visualStudioWorkspace = (VisualStudioWorkspace)_workspace; Contract.ThrowIfNull(visualStudioWorkspace); var solution = visualStudioWorkspace.CurrentSolution; var document = solution.GetDocument(id); if (document == null) { // document is not part of the workspace (newly created document that is not applied to the workspace yet?) return; } if (visualStudioWorkspace.IsDocumentOpen(id)) { var container = document.GetTextAsync().WaitAndGetResult(CancellationToken.None).Container; var textBuffer = container.TryGetTextBuffer(); var undoHistory = _undoHistoryRegistry.RegisterHistory(textBuffer); using var undoTransaction = undoHistory.CreateTransaction(_description); undoTransaction.AddUndo(new NoOpUndoPrimitive()); undoTransaction.Complete(); } else { // open and close the document so that it is included in the global undo transaction using (visualStudioWorkspace.OpenInvisibleEditor(id)) { // empty } } } public void Commit() { AssertIsForeground(); // once either commit or disposed is called, don't do finalizer check GC.SuppressFinalize(this); if (_transactionAlive) { _service.ActiveTransactions--; var result = _undoManager.CloseLinkedUndo(); if (result == VSConstants.UNDO_E_CLIENTABORT) { Dispose(); } else { Marshal.ThrowExceptionForHR(result); _transactionAlive = false; } } } public void Dispose() { AssertIsForeground(); // once either commit or disposed is called, don't do finalizer check GC.SuppressFinalize(this); if (_transactionAlive) { _service.ActiveTransactions--; Marshal.ThrowExceptionForHR(_undoManager.AbortLinkedUndo()); _transactionAlive = false; } } #if DEBUG ~WorkspaceUndoTransaction() { // make sure we closed it correctly Debug.Assert(!_transactionAlive); } #endif } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Diagnostics; using System.Runtime.InteropServices; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Editor.Undo; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.Text.Operations; using Microsoft.VisualStudio.TextManager.Interop; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation { using Workspace = Microsoft.CodeAnalysis.Workspace; internal partial class GlobalUndoServiceFactory { private class WorkspaceUndoTransaction : ForegroundThreadAffinitizedObject, IWorkspaceGlobalUndoTransaction { private readonly ITextUndoHistoryRegistry _undoHistoryRegistry; private readonly IVsLinkedUndoTransactionManager _undoManager; private readonly Workspace _workspace; private readonly string _description; private readonly GlobalUndoService _service; // indicate whether undo transaction is currently active private bool _transactionAlive; public WorkspaceUndoTransaction( IThreadingContext threadingContext, ITextUndoHistoryRegistry undoHistoryRegistry, IVsLinkedUndoTransactionManager undoManager, Workspace workspace, string description, GlobalUndoService service) : base(threadingContext, assertIsForeground: true) { _undoHistoryRegistry = undoHistoryRegistry; _undoManager = undoManager; _workspace = workspace; _description = description; _service = service; Marshal.ThrowExceptionForHR(_undoManager.OpenLinkedUndo((uint)LinkedTransactionFlags2.mdtGlobal, _description)); _transactionAlive = true; } public void AddDocument(DocumentId id) { var visualStudioWorkspace = (VisualStudioWorkspace)_workspace; Contract.ThrowIfNull(visualStudioWorkspace); var solution = visualStudioWorkspace.CurrentSolution; var document = solution.GetDocument(id); if (document == null) { // document is not part of the workspace (newly created document that is not applied to the workspace yet?) return; } if (visualStudioWorkspace.IsDocumentOpen(id)) { var container = document.GetTextAsync().WaitAndGetResult(CancellationToken.None).Container; var textBuffer = container.TryGetTextBuffer(); var undoHistory = _undoHistoryRegistry.RegisterHistory(textBuffer); using var undoTransaction = undoHistory.CreateTransaction(_description); undoTransaction.AddUndo(new NoOpUndoPrimitive()); undoTransaction.Complete(); } else { // open and close the document so that it is included in the global undo transaction using (visualStudioWorkspace.OpenInvisibleEditor(id)) { // empty } } } public void Commit() { AssertIsForeground(); // once either commit or disposed is called, don't do finalizer check GC.SuppressFinalize(this); if (_transactionAlive) { _service.ActiveTransactions--; var result = _undoManager.CloseLinkedUndo(); if (result == VSConstants.UNDO_E_CLIENTABORT) { Dispose(); } else { Marshal.ThrowExceptionForHR(result); _transactionAlive = false; } } } public void Dispose() { AssertIsForeground(); // once either commit or disposed is called, don't do finalizer check GC.SuppressFinalize(this); if (_transactionAlive) { _service.ActiveTransactions--; Marshal.ThrowExceptionForHR(_undoManager.AbortLinkedUndo()); _transactionAlive = false; } } #if DEBUG ~WorkspaceUndoTransaction() { // make sure we closed it correctly Debug.Assert(!_transactionAlive); } #endif } } }
-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/Metadata/PE/LoadingFields.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 CompilationCreationTestHelpers 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 Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols.Metadata.PE Public Class LoadingFields : Inherits BasicTestBase <Fact> Public Sub Test1() Dim assemblies = MetadataTestHelpers.GetSymbolsForReferences( { TestResources.SymbolsTests.Fields.CSFields, TestResources.SymbolsTests.Fields.VBFields, TestMetadata.ResourcesNet40.mscorlib }, importInternals:=True) Dim module1 = assemblies(0).Modules(0) Dim module2 = assemblies(1).Modules(0) Dim module3 = assemblies(2).Modules(0) Dim vbFields = module2.GlobalNamespace.GetTypeMembers("VBFields").Single() Dim csFields = module1.GlobalNamespace.GetTypeMembers("CSFields").Single() Dim f1 = DirectCast(vbFields.GetMembers("F1").Single(), FieldSymbol) Dim f2 = DirectCast(vbFields.GetMembers("F2").Single(), FieldSymbol) Dim f3 = DirectCast(vbFields.GetMembers("F3").Single(), FieldSymbol) Dim f4 = DirectCast(vbFields.GetMembers("F4").Single(), FieldSymbol) Dim f5 = DirectCast(vbFields.GetMembers("F5").Single(), FieldSymbol) Dim f6 = DirectCast(csFields.GetMembers("F6").Single(), FieldSymbol) Assert.Equal("F1", f1.Name) Assert.Same(vbFields.TypeParameters(0), f1.Type) Assert.False(f1.IsMustOverride) Assert.False(f1.IsConst) Assert.True(f1.IsDefinition) Assert.False(f1.IsOverrides) Assert.False(f1.IsReadOnly) Assert.False(f1.IsNotOverridable) Assert.True(f1.IsShared) Assert.False(f1.IsOverridable) Assert.Equal(SymbolKind.Field, f1.Kind) Assert.Equal(module2.Locations, f1.Locations) Assert.Same(f1, f1.OriginalDefinition) Assert.Equal(Accessibility.Public, f1.DeclaredAccessibility) Assert.Same(vbFields, f1.ContainingSymbol) Assert.Equal(0, f1.CustomModifiers.Length) Assert.Equal("F2", f2.Name) Assert.Same(DirectCast(module2, PEModuleSymbol).GetCorLibType(SpecialType.System_Int32), f2.Type) Assert.False(f2.IsConst) Assert.True(f2.IsReadOnly) Assert.False(f2.IsShared) Assert.Equal(Accessibility.Protected, f2.DeclaredAccessibility) Assert.Equal(0, f2.CustomModifiers.Length) Assert.Equal("F3", f3.Name) Assert.False(f3.IsConst) Assert.False(f3.IsReadOnly) Assert.False(f3.IsShared) Assert.Equal(Accessibility.Friend, f3.DeclaredAccessibility) Assert.Equal(0, f3.CustomModifiers.Length) Assert.Equal("F4", f4.Name) Assert.False(f4.IsConst) Assert.False(f4.IsReadOnly) Assert.False(f4.IsShared) Assert.Equal(Accessibility.ProtectedOrFriend, f4.DeclaredAccessibility) Assert.Equal(0, f4.CustomModifiers.Length) Assert.Equal("F5", f5.Name) Assert.True(f5.IsConst) Assert.False(f5.IsReadOnly) Assert.True(f5.IsShared) Assert.Equal(Accessibility.Protected, f5.DeclaredAccessibility) Assert.Equal(0, f5.CustomModifiers.Length) Assert.Equal("F6", f6.Name) Assert.False(f6.IsConst) Assert.False(f6.IsReadOnly) Assert.False(f6.IsShared) Assert.False(f6.CustomModifiers.Single().IsOptional) Assert.Equal("System.Runtime.CompilerServices.IsVolatile", f6.CustomModifiers.Single().Modifier.ToTestDisplayString()) Assert.True(f6.HasUnsupportedMetadata) Assert.Equal(3, csFields.GetMembers("FFF").Length()) Assert.Equal(3, csFields.GetMembers("Fff").Length()) Assert.Equal(3, csFields.GetMembers("FfF").Length()) End Sub <Fact> Public Sub ConstantFields() Dim assemblies = MetadataTestHelpers.GetSymbolsForReferences( { TestResources.SymbolsTests.Fields.ConstantFields, TestMetadata.ResourcesNet40.mscorlib }) Dim module1 = assemblies(0).Modules(0) Dim ConstFields = module1.GlobalNamespace.GetTypeMembers("ConstFields").Single() Dim ByteEnum = module1.GlobalNamespace.GetTypeMembers("ByteEnum").Single() Dim SByteEnum = module1.GlobalNamespace.GetTypeMembers("SByteEnum").Single() Dim UInt16Enum = module1.GlobalNamespace.GetTypeMembers("UInt16Enum").Single() Dim Int16Enum = module1.GlobalNamespace.GetTypeMembers("Int16Enum").Single() Dim UInt32Enum = module1.GlobalNamespace.GetTypeMembers("UInt32Enum").Single() Dim Int32Enum = module1.GlobalNamespace.GetTypeMembers("Int32Enum").Single() Dim UInt64Enum = module1.GlobalNamespace.GetTypeMembers("UInt64Enum").Single() Dim Int64Enum = module1.GlobalNamespace.GetTypeMembers("Int64Enum").Single() 'Public Const Int64Field As Long = 634315546432909307 'Public DateTimeField As DateTime 'Public Const SingleField As Single = 9 'Public Const DoubleField As Double = -10 'Public Const StringField As String = "11" 'Public Const StringNullField As String = Nothing 'Public Const ObjectNullField As Object = Nothing Dim Int64Field = DirectCast(ConstFields.GetMembers("Int64Field").Single(), FieldSymbol) Dim DateTimeField = DirectCast(ConstFields.GetMembers("DateTimeField").Single(), FieldSymbol) Dim SingleField = DirectCast(ConstFields.GetMembers("SingleField").Single(), FieldSymbol) Dim DoubleField = DirectCast(ConstFields.GetMembers("DoubleField").Single(), FieldSymbol) Dim StringField = DirectCast(ConstFields.GetMembers("StringField").Single(), FieldSymbol) Dim StringNullField = DirectCast(ConstFields.GetMembers("StringNullField").Single(), FieldSymbol) Dim ObjectNullField = DirectCast(ConstFields.GetMembers("ObjectNullField").Single(), FieldSymbol) Assert.True(Int64Field.IsConst) Assert.True(Int64Field.HasConstantValue) Assert.Equal(Int64Field.ConstantValue, 634315546432909307) Assert.Equal(ConstantValueTypeDiscriminator.Int64, Int64Field.GetConstantValue(ConstantFieldsInProgress.Empty).Discriminator) Assert.Equal(634315546432909307, Int64Field.GetConstantValue(ConstantFieldsInProgress.Empty).Int64Value) Assert.True(DateTimeField.IsConst) Assert.True(DateTimeField.HasConstantValue) Assert.Equal(DateTimeField.ConstantValue, New DateTime(634315546432909307)) Assert.Equal(ConstantValueTypeDiscriminator.DateTime, DateTimeField.GetConstantValue(ConstantFieldsInProgress.Empty).Discriminator) Assert.Equal(New DateTime(634315546432909307), DateTimeField.GetConstantValue(ConstantFieldsInProgress.Empty).DateTimeValue) Assert.True(SingleField.IsConst) Assert.True(SingleField.HasConstantValue) Assert.Equal(SingleField.ConstantValue, 9.0F) Assert.Equal(ConstantValueTypeDiscriminator.Single, SingleField.GetConstantValue(ConstantFieldsInProgress.Empty).Discriminator) Assert.Equal(9.0F, SingleField.GetConstantValue(ConstantFieldsInProgress.Empty).SingleValue) Assert.True(DoubleField.IsConst) Assert.True(DoubleField.HasConstantValue) Assert.Equal(DoubleField.ConstantValue, -10.0) Assert.Equal(ConstantValueTypeDiscriminator.Double, DoubleField.GetConstantValue(ConstantFieldsInProgress.Empty).Discriminator) Assert.Equal(-10.0, DoubleField.GetConstantValue(ConstantFieldsInProgress.Empty).DoubleValue) Assert.True(StringField.IsConst) Assert.True(StringField.HasConstantValue) Assert.Equal(StringField.ConstantValue, "11") Assert.Equal(ConstantValueTypeDiscriminator.String, StringField.GetConstantValue(ConstantFieldsInProgress.Empty).Discriminator) Assert.Equal("11", StringField.GetConstantValue(ConstantFieldsInProgress.Empty).StringValue) Assert.True(StringNullField.IsConst) Assert.True(StringNullField.HasConstantValue) Assert.Null(StringNullField.ConstantValue) Assert.Equal(ConstantValueTypeDiscriminator.Nothing, StringNullField.GetConstantValue(ConstantFieldsInProgress.Empty).Discriminator) Assert.True(ObjectNullField.IsConst) Assert.True(ObjectNullField.HasConstantValue) Assert.Null(ObjectNullField.ConstantValue) Assert.Equal(ConstantValueTypeDiscriminator.Nothing, ObjectNullField.GetConstantValue(ConstantFieldsInProgress.Empty).Discriminator) 'ByteValue = 1 'SByteValue = -2 'UInt16Value = 3 'Int16Value = -4 'UInt32Value = 5 'Int32Value = -6 'UInt64Value = 7 'Int64Value = -8 Dim ByteValue = DirectCast(ByteEnum.GetMembers("ByteValue").Single(), FieldSymbol) Dim SByteValue = DirectCast(SByteEnum.GetMembers("SByteValue").Single(), FieldSymbol) Dim UInt16Value = DirectCast(UInt16Enum.GetMembers("UInt16Value").Single(), FieldSymbol) Dim Int16Value = DirectCast(Int16Enum.GetMembers("Int16Value").Single(), FieldSymbol) Dim UInt32Value = DirectCast(UInt32Enum.GetMembers("UInt32Value").Single(), FieldSymbol) Dim Int32Value = DirectCast(Int32Enum.GetMembers("Int32Value").Single(), FieldSymbol) Dim UInt64Value = DirectCast(UInt64Enum.GetMembers("UInt64Value").Single(), FieldSymbol) Dim Int64Value = DirectCast(Int64Enum.GetMembers("Int64Value").Single(), FieldSymbol) Assert.True(ByteValue.IsConst) Assert.True(ByteValue.HasConstantValue) Assert.Equal(ByteValue.ConstantValue, CByte(1)) Assert.Equal(ConstantValueTypeDiscriminator.Byte, ByteValue.GetConstantValue(ConstantFieldsInProgress.Empty).Discriminator) Assert.Equal(CByte(1), ByteValue.GetConstantValue(ConstantFieldsInProgress.Empty).ByteValue) Assert.True(SByteValue.IsConst) Assert.True(SByteValue.HasConstantValue) Assert.Equal(SByteValue.ConstantValue, CSByte(-2)) Assert.Equal(ConstantValueTypeDiscriminator.SByte, SByteValue.GetConstantValue(ConstantFieldsInProgress.Empty).Discriminator) Assert.Equal(CSByte(-2), SByteValue.GetConstantValue(ConstantFieldsInProgress.Empty).SByteValue) Assert.True(UInt16Value.IsConst) Assert.True(UInt16Value.HasConstantValue) Assert.Equal(UInt16Value.ConstantValue, 3US) Assert.Equal(ConstantValueTypeDiscriminator.UInt16, UInt16Value.GetConstantValue(ConstantFieldsInProgress.Empty).Discriminator) Assert.Equal(3US, UInt16Value.GetConstantValue(ConstantFieldsInProgress.Empty).UInt16Value) Assert.True(Int16Value.IsConst) Assert.True(Int16Value.HasConstantValue) Assert.Equal(Int16Value.ConstantValue, -4S) Assert.Equal(ConstantValueTypeDiscriminator.Int16, Int16Value.GetConstantValue(ConstantFieldsInProgress.Empty).Discriminator) Assert.Equal(-4S, Int16Value.GetConstantValue(ConstantFieldsInProgress.Empty).Int16Value) Assert.True(UInt32Value.IsConst) Assert.True(UInt32Value.HasConstantValue) Assert.Equal(UInt32Value.ConstantValue, 5UI) Assert.Equal(ConstantValueTypeDiscriminator.UInt32, UInt32Value.GetConstantValue(ConstantFieldsInProgress.Empty).Discriminator) Assert.Equal(5UI, UInt32Value.GetConstantValue(ConstantFieldsInProgress.Empty).UInt32Value) Assert.True(Int32Value.IsConst) Assert.True(Int32Value.HasConstantValue) Assert.Equal(Int32Value.ConstantValue, -6) Assert.Equal(ConstantValueTypeDiscriminator.Int32, Int32Value.GetConstantValue(ConstantFieldsInProgress.Empty).Discriminator) Assert.Equal(-6, Int32Value.GetConstantValue(ConstantFieldsInProgress.Empty).Int32Value) Assert.True(UInt64Value.IsConst) Assert.True(UInt64Value.HasConstantValue) Assert.Equal(UInt64Value.ConstantValue, 7UL) Assert.Equal(ConstantValueTypeDiscriminator.UInt64, UInt64Value.GetConstantValue(ConstantFieldsInProgress.Empty).Discriminator) Assert.Equal(7UL, UInt64Value.GetConstantValue(ConstantFieldsInProgress.Empty).UInt64Value) Assert.True(Int64Value.IsConst) Assert.True(Int64Value.HasConstantValue) Assert.Equal(Int64Value.ConstantValue, -8L) Assert.Equal(ConstantValueTypeDiscriminator.Int64, Int64Value.GetConstantValue(ConstantFieldsInProgress.Empty).Discriminator) Assert.Equal(-8L, Int64Value.GetConstantValue(ConstantFieldsInProgress.Empty).Int64Value) End Sub <Fact> <WorkItem(193333, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?_a=edit&id=193333")> Public Sub EnumWithPrivateValueField() Dim ilSource = " .class public auto ansi sealed TestEnum extends [mscorlib]System.Enum { .field private specialname rtspecialname int32 value__ .field public static literal valuetype TestEnum Value1 = int32(0x00000000) .field public static literal valuetype TestEnum Value2 = int32(0x00000001) } // end of class TestEnum " Dim vbSource = <compilation> <file> Module Module1 Sub Main() Dim val as TestEnum = TestEnum.Value1 System.Console.WriteLine(val.ToString()) val = TestEnum.Value2 System.Console.WriteLine(val.ToString()) End Sub End Module </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(vbSource, ilSource, includeVbRuntime:=True, options:=TestOptions.DebugExe) CompileAndVerify(compilation, expectedOutput:="Value1 Value2") End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Runtime.CompilerServices Imports CompilationCreationTestHelpers 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 Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols.Metadata.PE Public Class LoadingFields : Inherits BasicTestBase <Fact> Public Sub Test1() Dim assemblies = MetadataTestHelpers.GetSymbolsForReferences( { TestResources.SymbolsTests.Fields.CSFields, TestResources.SymbolsTests.Fields.VBFields, TestMetadata.ResourcesNet40.mscorlib }, importInternals:=True) Dim module1 = assemblies(0).Modules(0) Dim module2 = assemblies(1).Modules(0) Dim module3 = assemblies(2).Modules(0) Dim vbFields = module2.GlobalNamespace.GetTypeMembers("VBFields").Single() Dim csFields = module1.GlobalNamespace.GetTypeMembers("CSFields").Single() Dim f1 = DirectCast(vbFields.GetMembers("F1").Single(), FieldSymbol) Dim f2 = DirectCast(vbFields.GetMembers("F2").Single(), FieldSymbol) Dim f3 = DirectCast(vbFields.GetMembers("F3").Single(), FieldSymbol) Dim f4 = DirectCast(vbFields.GetMembers("F4").Single(), FieldSymbol) Dim f5 = DirectCast(vbFields.GetMembers("F5").Single(), FieldSymbol) Dim f6 = DirectCast(csFields.GetMembers("F6").Single(), FieldSymbol) Assert.Equal("F1", f1.Name) Assert.Same(vbFields.TypeParameters(0), f1.Type) Assert.False(f1.IsMustOverride) Assert.False(f1.IsConst) Assert.True(f1.IsDefinition) Assert.False(f1.IsOverrides) Assert.False(f1.IsReadOnly) Assert.False(f1.IsNotOverridable) Assert.True(f1.IsShared) Assert.False(f1.IsOverridable) Assert.Equal(SymbolKind.Field, f1.Kind) Assert.Equal(module2.Locations, f1.Locations) Assert.Same(f1, f1.OriginalDefinition) Assert.Equal(Accessibility.Public, f1.DeclaredAccessibility) Assert.Same(vbFields, f1.ContainingSymbol) Assert.Equal(0, f1.CustomModifiers.Length) Assert.Equal("F2", f2.Name) Assert.Same(DirectCast(module2, PEModuleSymbol).GetCorLibType(SpecialType.System_Int32), f2.Type) Assert.False(f2.IsConst) Assert.True(f2.IsReadOnly) Assert.False(f2.IsShared) Assert.Equal(Accessibility.Protected, f2.DeclaredAccessibility) Assert.Equal(0, f2.CustomModifiers.Length) Assert.Equal("F3", f3.Name) Assert.False(f3.IsConst) Assert.False(f3.IsReadOnly) Assert.False(f3.IsShared) Assert.Equal(Accessibility.Friend, f3.DeclaredAccessibility) Assert.Equal(0, f3.CustomModifiers.Length) Assert.Equal("F4", f4.Name) Assert.False(f4.IsConst) Assert.False(f4.IsReadOnly) Assert.False(f4.IsShared) Assert.Equal(Accessibility.ProtectedOrFriend, f4.DeclaredAccessibility) Assert.Equal(0, f4.CustomModifiers.Length) Assert.Equal("F5", f5.Name) Assert.True(f5.IsConst) Assert.False(f5.IsReadOnly) Assert.True(f5.IsShared) Assert.Equal(Accessibility.Protected, f5.DeclaredAccessibility) Assert.Equal(0, f5.CustomModifiers.Length) Assert.Equal("F6", f6.Name) Assert.False(f6.IsConst) Assert.False(f6.IsReadOnly) Assert.False(f6.IsShared) Assert.False(f6.CustomModifiers.Single().IsOptional) Assert.Equal("System.Runtime.CompilerServices.IsVolatile", f6.CustomModifiers.Single().Modifier.ToTestDisplayString()) Assert.True(f6.HasUnsupportedMetadata) Assert.Equal(3, csFields.GetMembers("FFF").Length()) Assert.Equal(3, csFields.GetMembers("Fff").Length()) Assert.Equal(3, csFields.GetMembers("FfF").Length()) End Sub <Fact> Public Sub ConstantFields() Dim assemblies = MetadataTestHelpers.GetSymbolsForReferences( { TestResources.SymbolsTests.Fields.ConstantFields, TestMetadata.ResourcesNet40.mscorlib }) Dim module1 = assemblies(0).Modules(0) Dim ConstFields = module1.GlobalNamespace.GetTypeMembers("ConstFields").Single() Dim ByteEnum = module1.GlobalNamespace.GetTypeMembers("ByteEnum").Single() Dim SByteEnum = module1.GlobalNamespace.GetTypeMembers("SByteEnum").Single() Dim UInt16Enum = module1.GlobalNamespace.GetTypeMembers("UInt16Enum").Single() Dim Int16Enum = module1.GlobalNamespace.GetTypeMembers("Int16Enum").Single() Dim UInt32Enum = module1.GlobalNamespace.GetTypeMembers("UInt32Enum").Single() Dim Int32Enum = module1.GlobalNamespace.GetTypeMembers("Int32Enum").Single() Dim UInt64Enum = module1.GlobalNamespace.GetTypeMembers("UInt64Enum").Single() Dim Int64Enum = module1.GlobalNamespace.GetTypeMembers("Int64Enum").Single() 'Public Const Int64Field As Long = 634315546432909307 'Public DateTimeField As DateTime 'Public Const SingleField As Single = 9 'Public Const DoubleField As Double = -10 'Public Const StringField As String = "11" 'Public Const StringNullField As String = Nothing 'Public Const ObjectNullField As Object = Nothing Dim Int64Field = DirectCast(ConstFields.GetMembers("Int64Field").Single(), FieldSymbol) Dim DateTimeField = DirectCast(ConstFields.GetMembers("DateTimeField").Single(), FieldSymbol) Dim SingleField = DirectCast(ConstFields.GetMembers("SingleField").Single(), FieldSymbol) Dim DoubleField = DirectCast(ConstFields.GetMembers("DoubleField").Single(), FieldSymbol) Dim StringField = DirectCast(ConstFields.GetMembers("StringField").Single(), FieldSymbol) Dim StringNullField = DirectCast(ConstFields.GetMembers("StringNullField").Single(), FieldSymbol) Dim ObjectNullField = DirectCast(ConstFields.GetMembers("ObjectNullField").Single(), FieldSymbol) Assert.True(Int64Field.IsConst) Assert.True(Int64Field.HasConstantValue) Assert.Equal(Int64Field.ConstantValue, 634315546432909307) Assert.Equal(ConstantValueTypeDiscriminator.Int64, Int64Field.GetConstantValue(ConstantFieldsInProgress.Empty).Discriminator) Assert.Equal(634315546432909307, Int64Field.GetConstantValue(ConstantFieldsInProgress.Empty).Int64Value) Assert.True(DateTimeField.IsConst) Assert.True(DateTimeField.HasConstantValue) Assert.Equal(DateTimeField.ConstantValue, New DateTime(634315546432909307)) Assert.Equal(ConstantValueTypeDiscriminator.DateTime, DateTimeField.GetConstantValue(ConstantFieldsInProgress.Empty).Discriminator) Assert.Equal(New DateTime(634315546432909307), DateTimeField.GetConstantValue(ConstantFieldsInProgress.Empty).DateTimeValue) Assert.True(SingleField.IsConst) Assert.True(SingleField.HasConstantValue) Assert.Equal(SingleField.ConstantValue, 9.0F) Assert.Equal(ConstantValueTypeDiscriminator.Single, SingleField.GetConstantValue(ConstantFieldsInProgress.Empty).Discriminator) Assert.Equal(9.0F, SingleField.GetConstantValue(ConstantFieldsInProgress.Empty).SingleValue) Assert.True(DoubleField.IsConst) Assert.True(DoubleField.HasConstantValue) Assert.Equal(DoubleField.ConstantValue, -10.0) Assert.Equal(ConstantValueTypeDiscriminator.Double, DoubleField.GetConstantValue(ConstantFieldsInProgress.Empty).Discriminator) Assert.Equal(-10.0, DoubleField.GetConstantValue(ConstantFieldsInProgress.Empty).DoubleValue) Assert.True(StringField.IsConst) Assert.True(StringField.HasConstantValue) Assert.Equal(StringField.ConstantValue, "11") Assert.Equal(ConstantValueTypeDiscriminator.String, StringField.GetConstantValue(ConstantFieldsInProgress.Empty).Discriminator) Assert.Equal("11", StringField.GetConstantValue(ConstantFieldsInProgress.Empty).StringValue) Assert.True(StringNullField.IsConst) Assert.True(StringNullField.HasConstantValue) Assert.Null(StringNullField.ConstantValue) Assert.Equal(ConstantValueTypeDiscriminator.Nothing, StringNullField.GetConstantValue(ConstantFieldsInProgress.Empty).Discriminator) Assert.True(ObjectNullField.IsConst) Assert.True(ObjectNullField.HasConstantValue) Assert.Null(ObjectNullField.ConstantValue) Assert.Equal(ConstantValueTypeDiscriminator.Nothing, ObjectNullField.GetConstantValue(ConstantFieldsInProgress.Empty).Discriminator) 'ByteValue = 1 'SByteValue = -2 'UInt16Value = 3 'Int16Value = -4 'UInt32Value = 5 'Int32Value = -6 'UInt64Value = 7 'Int64Value = -8 Dim ByteValue = DirectCast(ByteEnum.GetMembers("ByteValue").Single(), FieldSymbol) Dim SByteValue = DirectCast(SByteEnum.GetMembers("SByteValue").Single(), FieldSymbol) Dim UInt16Value = DirectCast(UInt16Enum.GetMembers("UInt16Value").Single(), FieldSymbol) Dim Int16Value = DirectCast(Int16Enum.GetMembers("Int16Value").Single(), FieldSymbol) Dim UInt32Value = DirectCast(UInt32Enum.GetMembers("UInt32Value").Single(), FieldSymbol) Dim Int32Value = DirectCast(Int32Enum.GetMembers("Int32Value").Single(), FieldSymbol) Dim UInt64Value = DirectCast(UInt64Enum.GetMembers("UInt64Value").Single(), FieldSymbol) Dim Int64Value = DirectCast(Int64Enum.GetMembers("Int64Value").Single(), FieldSymbol) Assert.True(ByteValue.IsConst) Assert.True(ByteValue.HasConstantValue) Assert.Equal(ByteValue.ConstantValue, CByte(1)) Assert.Equal(ConstantValueTypeDiscriminator.Byte, ByteValue.GetConstantValue(ConstantFieldsInProgress.Empty).Discriminator) Assert.Equal(CByte(1), ByteValue.GetConstantValue(ConstantFieldsInProgress.Empty).ByteValue) Assert.True(SByteValue.IsConst) Assert.True(SByteValue.HasConstantValue) Assert.Equal(SByteValue.ConstantValue, CSByte(-2)) Assert.Equal(ConstantValueTypeDiscriminator.SByte, SByteValue.GetConstantValue(ConstantFieldsInProgress.Empty).Discriminator) Assert.Equal(CSByte(-2), SByteValue.GetConstantValue(ConstantFieldsInProgress.Empty).SByteValue) Assert.True(UInt16Value.IsConst) Assert.True(UInt16Value.HasConstantValue) Assert.Equal(UInt16Value.ConstantValue, 3US) Assert.Equal(ConstantValueTypeDiscriminator.UInt16, UInt16Value.GetConstantValue(ConstantFieldsInProgress.Empty).Discriminator) Assert.Equal(3US, UInt16Value.GetConstantValue(ConstantFieldsInProgress.Empty).UInt16Value) Assert.True(Int16Value.IsConst) Assert.True(Int16Value.HasConstantValue) Assert.Equal(Int16Value.ConstantValue, -4S) Assert.Equal(ConstantValueTypeDiscriminator.Int16, Int16Value.GetConstantValue(ConstantFieldsInProgress.Empty).Discriminator) Assert.Equal(-4S, Int16Value.GetConstantValue(ConstantFieldsInProgress.Empty).Int16Value) Assert.True(UInt32Value.IsConst) Assert.True(UInt32Value.HasConstantValue) Assert.Equal(UInt32Value.ConstantValue, 5UI) Assert.Equal(ConstantValueTypeDiscriminator.UInt32, UInt32Value.GetConstantValue(ConstantFieldsInProgress.Empty).Discriminator) Assert.Equal(5UI, UInt32Value.GetConstantValue(ConstantFieldsInProgress.Empty).UInt32Value) Assert.True(Int32Value.IsConst) Assert.True(Int32Value.HasConstantValue) Assert.Equal(Int32Value.ConstantValue, -6) Assert.Equal(ConstantValueTypeDiscriminator.Int32, Int32Value.GetConstantValue(ConstantFieldsInProgress.Empty).Discriminator) Assert.Equal(-6, Int32Value.GetConstantValue(ConstantFieldsInProgress.Empty).Int32Value) Assert.True(UInt64Value.IsConst) Assert.True(UInt64Value.HasConstantValue) Assert.Equal(UInt64Value.ConstantValue, 7UL) Assert.Equal(ConstantValueTypeDiscriminator.UInt64, UInt64Value.GetConstantValue(ConstantFieldsInProgress.Empty).Discriminator) Assert.Equal(7UL, UInt64Value.GetConstantValue(ConstantFieldsInProgress.Empty).UInt64Value) Assert.True(Int64Value.IsConst) Assert.True(Int64Value.HasConstantValue) Assert.Equal(Int64Value.ConstantValue, -8L) Assert.Equal(ConstantValueTypeDiscriminator.Int64, Int64Value.GetConstantValue(ConstantFieldsInProgress.Empty).Discriminator) Assert.Equal(-8L, Int64Value.GetConstantValue(ConstantFieldsInProgress.Empty).Int64Value) End Sub <Fact> <WorkItem(193333, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?_a=edit&id=193333")> Public Sub EnumWithPrivateValueField() Dim ilSource = " .class public auto ansi sealed TestEnum extends [mscorlib]System.Enum { .field private specialname rtspecialname int32 value__ .field public static literal valuetype TestEnum Value1 = int32(0x00000000) .field public static literal valuetype TestEnum Value2 = int32(0x00000001) } // end of class TestEnum " Dim vbSource = <compilation> <file> Module Module1 Sub Main() Dim val as TestEnum = TestEnum.Value1 System.Console.WriteLine(val.ToString()) val = TestEnum.Value2 System.Console.WriteLine(val.ToString()) End Sub End Module </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(vbSource, ilSource, includeVbRuntime:=True, options:=TestOptions.DebugExe) CompileAndVerify(compilation, expectedOutput:="Value1 Value2") End Sub 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/Portable/Errors/LazyUnmanagedCallersOnlyMethodCalledDiagnosticInfo.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; namespace Microsoft.CodeAnalysis.CSharp { internal sealed class LazyUnmanagedCallersOnlyMethodCalledDiagnosticInfo : DiagnosticInfo { private DiagnosticInfo? _lazyActualUnmanagedCallersOnlyDiagnostic; private readonly MethodSymbol _method; private readonly bool _isDelegateConversion; internal LazyUnmanagedCallersOnlyMethodCalledDiagnosticInfo(MethodSymbol method, bool isDelegateConversion) : base(CSharp.MessageProvider.Instance, (int)ErrorCode.Unknown) { _method = method; _lazyActualUnmanagedCallersOnlyDiagnostic = null; _isDelegateConversion = isDelegateConversion; } internal override DiagnosticInfo GetResolvedInfo() { if (_lazyActualUnmanagedCallersOnlyDiagnostic is null) { UnmanagedCallersOnlyAttributeData? unmanagedCallersOnlyAttributeData = _method.GetUnmanagedCallersOnlyAttributeData(forceComplete: true); Debug.Assert(!ReferenceEquals(unmanagedCallersOnlyAttributeData, UnmanagedCallersOnlyAttributeData.Uninitialized)); Debug.Assert(!ReferenceEquals(unmanagedCallersOnlyAttributeData, UnmanagedCallersOnlyAttributeData.AttributePresentDataNotBound)); var info = unmanagedCallersOnlyAttributeData is null ? CSDiagnosticInfo.VoidDiagnosticInfo : new CSDiagnosticInfo(_isDelegateConversion ? ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeConvertedToDelegate : ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeCalledDirectly, _method); Interlocked.CompareExchange(ref _lazyActualUnmanagedCallersOnlyDiagnostic, info, null); } return _lazyActualUnmanagedCallersOnlyDiagnostic; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; namespace Microsoft.CodeAnalysis.CSharp { internal sealed class LazyUnmanagedCallersOnlyMethodCalledDiagnosticInfo : DiagnosticInfo { private DiagnosticInfo? _lazyActualUnmanagedCallersOnlyDiagnostic; private readonly MethodSymbol _method; private readonly bool _isDelegateConversion; internal LazyUnmanagedCallersOnlyMethodCalledDiagnosticInfo(MethodSymbol method, bool isDelegateConversion) : base(CSharp.MessageProvider.Instance, (int)ErrorCode.Unknown) { _method = method; _lazyActualUnmanagedCallersOnlyDiagnostic = null; _isDelegateConversion = isDelegateConversion; } internal override DiagnosticInfo GetResolvedInfo() { if (_lazyActualUnmanagedCallersOnlyDiagnostic is null) { UnmanagedCallersOnlyAttributeData? unmanagedCallersOnlyAttributeData = _method.GetUnmanagedCallersOnlyAttributeData(forceComplete: true); Debug.Assert(!ReferenceEquals(unmanagedCallersOnlyAttributeData, UnmanagedCallersOnlyAttributeData.Uninitialized)); Debug.Assert(!ReferenceEquals(unmanagedCallersOnlyAttributeData, UnmanagedCallersOnlyAttributeData.AttributePresentDataNotBound)); var info = unmanagedCallersOnlyAttributeData is null ? CSDiagnosticInfo.VoidDiagnosticInfo : new CSDiagnosticInfo(_isDelegateConversion ? ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeConvertedToDelegate : ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeCalledDirectly, _method); Interlocked.CompareExchange(ref _lazyActualUnmanagedCallersOnlyDiagnostic, info, null); } return _lazyActualUnmanagedCallersOnlyDiagnostic; } } }
-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/Diagnostics/AddExplicitCast/AddExplicitCastTests_FixAllTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics.AddExplicitCast Partial Public Class AddExplicitCastTests <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddExplicitCast)> Public Async Function TestFixAllInDocumentBC30512() As Task Dim input = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document><![CDATA[ Option Strict On Public Class Program1 Class Base End Class Class Derived Inherits Base End Class Class Test Public Property D As Derived Public Property B As Base Public Sub New() End Sub Public Sub New(ByRef d As Derived) Me.D = d End Sub Public Sub testing(ByVal d As Derived) End Sub Private Sub testing(ByVal b As Base) End Sub End Class Class Test2 Inherits Test Public Sub New(ByVal b As Base) MyBase.New(b) End Sub End Class Class Test3 Public Sub New(ByVal b As Derived) End Sub Public Sub New(ByVal i As Integer, ByVal b As Base) Me.New(b) End Sub End Class Private Function ReturnBase() As Base Dim b As Base = New Base() Return b End Function Private Function ReturnBase(ByVal d As Derived) As Base Dim b As Base = New Base() Return b End Function Private Function ReturnDerived(ByVal b As Base) As Derived Return b End Function Private Function ReturnDerived2(ByVal b As Base) As Derived Return ReturnBase() End Function Public Sub New() Dim b As Base = New Derived Dim d As Derived = {|FixAllInDocument:b|} d = New Base() Dim d2 As Derived = ReturnBase() d2 = ReturnBase(b) Dim t As Test = New Test() t.D = b t.D = b d = t.B End Sub Private Sub PassDerived(ByVal d As Derived) End Sub Private Sub PassDerived(ByVal i As Integer, ByVal d As Derived) End Sub Public Sub M() Dim b As Base = New Derived Dim d As Derived = b PassDerived(b) PassDerived(ReturnBase()) PassDerived(1, b) PassDerived(1, ReturnBase()) Dim list As List(Of Derived) = New List(Of Derived)() list.Add(b) Dim t As Test = New Test() t.testing(b) Dim foo2 As Func(Of Derived, Base) = Function(p_d) p_d Dim d2 As Derived = foo2(b) d2 = foo2(d) End Sub End Class]]> </Document> <Document><![CDATA[ Option Strict On Public Class Program2 Interface Base1 End Interface Interface Base2 Inherits Base1 End Interface Interface Base3 End Interface Class Derived1 Implements Base2, Base3 End Class Class Derived2 Inherits Derived1 End Class Class Test Public Shared Narrowing Operator CType(t As Test) As Derived2 Return New Derived2 End Operator End Class Private Function returnDerived2_1() As Derived2 Return New Derived1() End Function Private Function returnDerived2_2() As Derived2 Return New Test() End Function Private Sub Foo1(ByVal b As Derived2) End Sub Private Sub Foo2(ByVal b As Base2) End Sub Private Sub Foo3(ByVal b1 As Derived2) End Sub Private Sub Foo3(ByVal i As Integer) End Sub Private Sub M2(ByVal b1 As Base1, ByVal b2 As Base2, ByVal b3 As Base3, ByVal d1 As Derived1, ByVal d2 As Derived2) Dim derived2 As Derived2 = b1 derived2 = b3 Dim base2 As Base2 = b1 derived2 = d1 d2 = New Test() Foo1(b1) Foo1(d1) Foo2(b1) Foo3(b1) End Sub End Class]]> </Document> </Project> <Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true"> <ProjectReference>Assembly1</ProjectReference> <Document><![CDATA[ Option Strict On Public Class Program3 Class Base End Class Class Derived Inherits Base End Class Private Sub returnD2(ByVal b As Base) Dim d As Derived = b End Sub End Class]]> </Document> </Project> </Workspace>.ToString() Dim expected = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document><![CDATA[ Option Strict On Public Class Program1 Class Base End Class Class Derived Inherits Base End Class Class Test Public Property D As Derived Public Property B As Base Public Sub New() End Sub Public Sub New(ByRef d As Derived) Me.D = d End Sub Public Sub testing(ByVal d As Derived) End Sub Private Sub testing(ByVal b As Base) End Sub End Class Class Test2 Inherits Test Public Sub New(ByVal b As Base) MyBase.New(CType(b, Derived)) End Sub End Class Class Test3 Public Sub New(ByVal b As Derived) End Sub Public Sub New(ByVal i As Integer, ByVal b As Base) Me.New(CType(b, Derived)) End Sub End Class Private Function ReturnBase() As Base Dim b As Base = New Base() Return b End Function Private Function ReturnBase(ByVal d As Derived) As Base Dim b As Base = New Base() Return b End Function Private Function ReturnDerived(ByVal b As Base) As Derived Return CType(b, Derived) End Function Private Function ReturnDerived2(ByVal b As Base) As Derived Return CType(ReturnBase(), Derived) End Function Public Sub New() Dim b As Base = New Derived Dim d As Derived = CType(b, Derived) d = New Base() Dim d2 As Derived = CType(ReturnBase(), Derived) d2 = ReturnBase(CType(b, Derived)) Dim t As Test = New Test() t.D = CType(b, Derived) t.D = CType(b, Derived) d = CType(t.B, Derived) End Sub Private Sub PassDerived(ByVal d As Derived) End Sub Private Sub PassDerived(ByVal i As Integer, ByVal d As Derived) End Sub Public Sub M() Dim b As Base = New Derived Dim d As Derived = CType(b, Derived) PassDerived(CType(b, Derived)) PassDerived(CType(ReturnBase(), Derived)) PassDerived(1, CType(b, Derived)) PassDerived(1, CType(ReturnBase(), Derived)) Dim list As List(Of Derived) = New List(Of Derived)() list.Add(CType(b, Derived)) Dim t As Test = New Test() t.testing(CType(b, Derived)) Dim foo2 As Func(Of Derived, Base) = Function(p_d) p_d Dim d2 As Derived = foo2(CType(b, Derived)) d2 = CType(foo2(d), Derived) End Sub End Class]]> </Document> <Document><![CDATA[ Option Strict On Public Class Program2 Interface Base1 End Interface Interface Base2 Inherits Base1 End Interface Interface Base3 End Interface Class Derived1 Implements Base2, Base3 End Class Class Derived2 Inherits Derived1 End Class Class Test Public Shared Narrowing Operator CType(t As Test) As Derived2 Return New Derived2 End Operator End Class Private Function returnDerived2_1() As Derived2 Return New Derived1() End Function Private Function returnDerived2_2() As Derived2 Return New Test() End Function Private Sub Foo1(ByVal b As Derived2) End Sub Private Sub Foo2(ByVal b As Base2) End Sub Private Sub Foo3(ByVal b1 As Derived2) End Sub Private Sub Foo3(ByVal i As Integer) End Sub Private Sub M2(ByVal b1 As Base1, ByVal b2 As Base2, ByVal b3 As Base3, ByVal d1 As Derived1, ByVal d2 As Derived2) Dim derived2 As Derived2 = b1 derived2 = b3 Dim base2 As Base2 = b1 derived2 = d1 d2 = New Test() Foo1(b1) Foo1(d1) Foo2(b1) Foo3(b1) End Sub End Class]]> </Document> </Project> <Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true"> <ProjectReference>Assembly1</ProjectReference> <Document><![CDATA[ Option Strict On Public Class Program3 Class Base End Class Class Derived Inherits Base End Class Private Sub returnD2(ByVal b As Base) Dim d As Derived = b End Sub End Class]]> </Document> </Project> </Workspace>.ToString() Await TestInRegularAndScriptAsync(input, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddExplicitCast)> Public Async Function TestFixAllInProjectBC30512() As Task Dim input = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document><![CDATA[ Option Strict On Public Class Program1 Class Base End Class Class Derived Inherits Base End Class Class Test Public Property D As Derived Public Property B As Base Public Sub New() End Sub Public Sub New(ByRef d As Derived) Me.D = d End Sub Public Sub testing(ByVal d As Derived) End Sub Private Sub testing(ByVal b As Base) End Sub End Class Class Test2 Inherits Test Public Sub New(ByVal b As Base) MyBase.New(b) End Sub End Class Class Test3 Public Sub New(ByVal b As Derived) End Sub Public Sub New(ByVal i As Integer, ByVal b As Base) Me.New(b) End Sub End Class Private Function ReturnBase() As Base Dim b As Base = New Base() Return b End Function Private Function ReturnBase(ByVal d As Derived) As Base Dim b As Base = New Base() Return b End Function Private Function ReturnDerived(ByVal b As Base) As Derived Return b End Function Private Function ReturnDerived2(ByVal b As Base) As Derived Return ReturnBase() End Function Public Sub New() Dim b As Base = New Derived Dim d As Derived = {|FixAllInProject:b|} d = New Base() Dim d2 As Derived = ReturnBase() d2 = ReturnBase(b) Dim t As Test = New Test() t.D = b t.D = b d = t.B End Sub Private Sub PassDerived(ByVal d As Derived) End Sub Private Sub PassDerived(ByVal i As Integer, ByVal d As Derived) End Sub Public Sub M() Dim b As Base = New Derived Dim d As Derived = b PassDerived(b) PassDerived(ReturnBase()) PassDerived(1, b) PassDerived(1, ReturnBase()) Dim list As List(Of Derived) = New List(Of Derived)() list.Add(b) Dim t As Test = New Test() t.testing(b) Dim foo2 As Func(Of Derived, Base) = Function(p_d) p_d Dim d2 As Derived = foo2(b) d2 = foo2(d) End Sub End Class]]> </Document> <Document><![CDATA[ Option Strict On Public Class Program2 Interface Base1 End Interface Interface Base2 Inherits Base1 End Interface Interface Base3 End Interface Class Derived1 Implements Base2, Base3 End Class Class Derived2 Inherits Derived1 End Class Class Test Public Shared Narrowing Operator CType(t As Test) As Derived2 Return New Derived2 End Operator End Class Private Function returnDerived2_1() As Derived2 Return New Derived1() End Function Private Function returnDerived2_2() As Derived2 Return New Test() End Function Private Sub Foo1(ByVal b As Derived2) End Sub Private Sub Foo2(ByVal b As Base2) End Sub Private Sub Foo3(ByVal b1 As Derived2) End Sub Private Sub Foo3(ByVal i As Integer) End Sub Private Sub M2(ByVal b1 As Base1, ByVal b2 As Base2, ByVal b3 As Base3, ByVal d1 As Derived1, ByVal d2 As Derived2) Dim derived2 As Derived2 = b1 derived2 = b3 Dim base2 As Base2 = b1 derived2 = d1 d2 = New Test() Foo1(b1) Foo1(d1) Foo2(b1) Foo3(b1) End Sub End Class]]> </Document> </Project> <Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true"> <ProjectReference>Assembly1</ProjectReference> <Document><![CDATA[ Option Strict On Public Class Program3 Class Base End Class Class Derived Inherits Base End Class Private Sub returnD2(ByVal b As Base) Dim d As Derived = b End Sub End Class]]> </Document> </Project> </Workspace>.ToString() Dim expected = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document><![CDATA[ Option Strict On Public Class Program1 Class Base End Class Class Derived Inherits Base End Class Class Test Public Property D As Derived Public Property B As Base Public Sub New() End Sub Public Sub New(ByRef d As Derived) Me.D = d End Sub Public Sub testing(ByVal d As Derived) End Sub Private Sub testing(ByVal b As Base) End Sub End Class Class Test2 Inherits Test Public Sub New(ByVal b As Base) MyBase.New(CType(b, Derived)) End Sub End Class Class Test3 Public Sub New(ByVal b As Derived) End Sub Public Sub New(ByVal i As Integer, ByVal b As Base) Me.New(CType(b, Derived)) End Sub End Class Private Function ReturnBase() As Base Dim b As Base = New Base() Return b End Function Private Function ReturnBase(ByVal d As Derived) As Base Dim b As Base = New Base() Return b End Function Private Function ReturnDerived(ByVal b As Base) As Derived Return CType(b, Derived) End Function Private Function ReturnDerived2(ByVal b As Base) As Derived Return CType(ReturnBase(), Derived) End Function Public Sub New() Dim b As Base = New Derived Dim d As Derived = CType(b, Derived) d = New Base() Dim d2 As Derived = CType(ReturnBase(), Derived) d2 = ReturnBase(CType(b, Derived)) Dim t As Test = New Test() t.D = CType(b, Derived) t.D = CType(b, Derived) d = CType(t.B, Derived) End Sub Private Sub PassDerived(ByVal d As Derived) End Sub Private Sub PassDerived(ByVal i As Integer, ByVal d As Derived) End Sub Public Sub M() Dim b As Base = New Derived Dim d As Derived = CType(b, Derived) PassDerived(CType(b, Derived)) PassDerived(CType(ReturnBase(), Derived)) PassDerived(1, CType(b, Derived)) PassDerived(1, CType(ReturnBase(), Derived)) Dim list As List(Of Derived) = New List(Of Derived)() list.Add(CType(b, Derived)) Dim t As Test = New Test() t.testing(CType(b, Derived)) Dim foo2 As Func(Of Derived, Base) = Function(p_d) p_d Dim d2 As Derived = foo2(CType(b, Derived)) d2 = CType(foo2(d), Derived) End Sub End Class]]> </Document> <Document><![CDATA[ Option Strict On Public Class Program2 Interface Base1 End Interface Interface Base2 Inherits Base1 End Interface Interface Base3 End Interface Class Derived1 Implements Base2, Base3 End Class Class Derived2 Inherits Derived1 End Class Class Test Public Shared Narrowing Operator CType(t As Test) As Derived2 Return New Derived2 End Operator End Class Private Function returnDerived2_1() As Derived2 Return New Derived1() End Function Private Function returnDerived2_2() As Derived2 Return CType(New Test(), Derived2) End Function Private Sub Foo1(ByVal b As Derived2) End Sub Private Sub Foo2(ByVal b As Base2) End Sub Private Sub Foo3(ByVal b1 As Derived2) End Sub Private Sub Foo3(ByVal i As Integer) End Sub Private Sub M2(ByVal b1 As Base1, ByVal b2 As Base2, ByVal b3 As Base3, ByVal d1 As Derived1, ByVal d2 As Derived2) Dim derived2 As Derived2 = CType(b1, Derived2) derived2 = CType(b3, Derived2) Dim base2 As Base2 = CType(b1, Base2) derived2 = CType(d1, Derived2) d2 = CType(New Test(), Derived2) Foo1(CType(b1, Derived2)) Foo1(CType(d1, Derived2)) Foo2(CType(b1, Base2)) Foo3(b1) End Sub End Class]]> </Document> </Project> <Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true"> <ProjectReference>Assembly1</ProjectReference> <Document><![CDATA[ Option Strict On Public Class Program3 Class Base End Class Class Derived Inherits Base End Class Private Sub returnD2(ByVal b As Base) Dim d As Derived = b End Sub End Class]]> </Document> </Project> </Workspace>.ToString() Await TestInRegularAndScriptAsync(input, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddExplicitCast)> Public Async Function TestFixAllInSolutionBC30512() As Task Dim input = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document><![CDATA[ Option Strict On Public Class Program1 Class Base End Class Class Derived Inherits Base End Class Class Test Public Property D As Derived Public Property B As Base Public Sub New() End Sub Public Sub New(ByRef d As Derived) Me.D = d End Sub Public Sub testing(ByVal d As Derived) End Sub Private Sub testing(ByVal b As Base) End Sub End Class Class Test2 Inherits Test Public Sub New(ByVal b As Base) MyBase.New(b) End Sub End Class Class Test3 Public Sub New(ByVal b As Derived) End Sub Public Sub New(ByVal i As Integer, ByVal b As Base) Me.New(b) End Sub End Class Private Function ReturnBase() As Base Dim b As Base = New Base() Return b End Function Private Function ReturnBase(ByVal d As Derived) As Base Dim b As Base = New Base() Return b End Function Private Function ReturnDerived(ByVal b As Base) As Derived Return b End Function Private Function ReturnDerived2(ByVal b As Base) As Derived Return ReturnBase() End Function Public Sub New() Dim b As Base = New Derived Dim d As Derived = {|FixAllInSolution:b|} d = New Base() Dim d2 As Derived = ReturnBase() d2 = ReturnBase(b) Dim t As Test = New Test() t.D = b t.D = b d = t.B End Sub Private Sub PassDerived(ByVal d As Derived) End Sub Private Sub PassDerived(ByVal i As Integer, ByVal d As Derived) End Sub Public Sub M() Dim b As Base = New Derived Dim d As Derived = b PassDerived(b) PassDerived(ReturnBase()) PassDerived(1, b) PassDerived(1, ReturnBase()) Dim list As List(Of Derived) = New List(Of Derived)() list.Add(b) Dim t As Test = New Test() t.testing(b) Dim foo2 As Func(Of Derived, Base) = Function(p_d) p_d Dim d2 As Derived = foo2(b) d2 = foo2(d) End Sub End Class]]> </Document> <Document><![CDATA[ Option Strict On Public Class Program2 Interface Base1 End Interface Interface Base2 Inherits Base1 End Interface Interface Base3 End Interface Class Derived1 Implements Base2, Base3 End Class Class Derived2 Inherits Derived1 End Class Class Test Public Shared Narrowing Operator CType(t As Test) As Derived2 Return New Derived2 End Operator End Class Private Function returnDerived2_1() As Derived2 Return New Derived1() End Function Private Function returnDerived2_2() As Derived2 Return New Test() End Function Private Sub Foo1(ByVal b As Derived2) End Sub Private Sub Foo2(ByVal b As Base2) End Sub Private Sub Foo3(ByVal b1 As Derived2) End Sub Private Sub Foo3(ByVal i As Integer) End Sub Private Sub M2(ByVal b1 As Base1, ByVal b2 As Base2, ByVal b3 As Base3, ByVal d1 As Derived1, ByVal d2 As Derived2) Dim derived2 As Derived2 = b1 derived2 = b3 Dim base2 As Base2 = b1 derived2 = d1 d2 = New Test() Foo1(b1) Foo1(d1) Foo2(b1) Foo3(b1) End Sub End Class]]> </Document> </Project> <Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true"> <ProjectReference>Assembly1</ProjectReference> <Document><![CDATA[ Option Strict On Public Class Program3 Class Base End Class Class Derived Inherits Base End Class Private Sub returnD2(ByVal b As Base) Dim d As Derived = b End Sub End Class]]> </Document> </Project> </Workspace>.ToString() Dim expected = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document><![CDATA[ Option Strict On Public Class Program1 Class Base End Class Class Derived Inherits Base End Class Class Test Public Property D As Derived Public Property B As Base Public Sub New() End Sub Public Sub New(ByRef d As Derived) Me.D = d End Sub Public Sub testing(ByVal d As Derived) End Sub Private Sub testing(ByVal b As Base) End Sub End Class Class Test2 Inherits Test Public Sub New(ByVal b As Base) MyBase.New(CType(b, Derived)) End Sub End Class Class Test3 Public Sub New(ByVal b As Derived) End Sub Public Sub New(ByVal i As Integer, ByVal b As Base) Me.New(CType(b, Derived)) End Sub End Class Private Function ReturnBase() As Base Dim b As Base = New Base() Return b End Function Private Function ReturnBase(ByVal d As Derived) As Base Dim b As Base = New Base() Return b End Function Private Function ReturnDerived(ByVal b As Base) As Derived Return CType(b, Derived) End Function Private Function ReturnDerived2(ByVal b As Base) As Derived Return CType(ReturnBase(), Derived) End Function Public Sub New() Dim b As Base = New Derived Dim d As Derived = CType(b, Derived) d = New Base() Dim d2 As Derived = CType(ReturnBase(), Derived) d2 = ReturnBase(CType(b, Derived)) Dim t As Test = New Test() t.D = CType(b, Derived) t.D = CType(b, Derived) d = CType(t.B, Derived) End Sub Private Sub PassDerived(ByVal d As Derived) End Sub Private Sub PassDerived(ByVal i As Integer, ByVal d As Derived) End Sub Public Sub M() Dim b As Base = New Derived Dim d As Derived = CType(b, Derived) PassDerived(CType(b, Derived)) PassDerived(CType(ReturnBase(), Derived)) PassDerived(1, CType(b, Derived)) PassDerived(1, CType(ReturnBase(), Derived)) Dim list As List(Of Derived) = New List(Of Derived)() list.Add(CType(b, Derived)) Dim t As Test = New Test() t.testing(CType(b, Derived)) Dim foo2 As Func(Of Derived, Base) = Function(p_d) p_d Dim d2 As Derived = foo2(CType(b, Derived)) d2 = CType(foo2(d), Derived) End Sub End Class]]> </Document> <Document><![CDATA[ Option Strict On Public Class Program2 Interface Base1 End Interface Interface Base2 Inherits Base1 End Interface Interface Base3 End Interface Class Derived1 Implements Base2, Base3 End Class Class Derived2 Inherits Derived1 End Class Class Test Public Shared Narrowing Operator CType(t As Test) As Derived2 Return New Derived2 End Operator End Class Private Function returnDerived2_1() As Derived2 Return New Derived1() End Function Private Function returnDerived2_2() As Derived2 Return CType(New Test(), Derived2) End Function Private Sub Foo1(ByVal b As Derived2) End Sub Private Sub Foo2(ByVal b As Base2) End Sub Private Sub Foo3(ByVal b1 As Derived2) End Sub Private Sub Foo3(ByVal i As Integer) End Sub Private Sub M2(ByVal b1 As Base1, ByVal b2 As Base2, ByVal b3 As Base3, ByVal d1 As Derived1, ByVal d2 As Derived2) Dim derived2 As Derived2 = CType(b1, Derived2) derived2 = CType(b3, Derived2) Dim base2 As Base2 = CType(b1, Base2) derived2 = CType(d1, Derived2) d2 = CType(New Test(), Derived2) Foo1(CType(b1, Derived2)) Foo1(CType(d1, Derived2)) Foo2(CType(b1, Base2)) Foo3(b1) End Sub End Class]]> </Document> </Project> <Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true"> <ProjectReference>Assembly1</ProjectReference> <Document><![CDATA[ Option Strict On Public Class Program3 Class Base End Class Class Derived Inherits Base End Class Private Sub returnD2(ByVal b As Base) Dim d As Derived = CType(b, Derived) End Sub End Class]]> </Document> </Project> </Workspace>.ToString() Await TestInRegularAndScriptAsync(input, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddExplicitCast)> Public Async Function TestFixAllInDocumentBC30519() As Task Dim input = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document><![CDATA[ Option Strict On Public Class Program1 Interface Base1 End Interface Interface Base2 Inherits Base1 End Interface Interface Base3 End Interface Class Derived1 Implements Base2, Base3 End Class Class Derived2 Inherits Derived1 End Class Private Sub Foo4(ByVal i As Integer, ByVal j As String, ByVal d As Derived1) End Sub Private Sub Foo4(ByVal j As String, ByVal i As Integer, ByVal d As Derived1) End Sub Private Sub Foo5(ByVal j As String, ByVal i As Integer, ByVal d As Derived2, ByVal Optional x As Integer = 1) End Sub Private Sub Foo5(ByVal j As String, ByVal i As Integer, ByVal d As Derived1, ParamArray d2list As Derived2()) End Sub Private Sub M2(ByVal b1 As Base1, ByVal b2 As Base2, ByVal b3 As Base3, ByVal d1 As Derived1, ByVal d2 As Derived2) Foo4(1, "", b1) {|FixAllInDocument:Foo4(i:=1, j:="", b1)|} Foo5("", 1, b1) Foo5(d:=b1, i:=1, j:="", x:=1) Foo5(1, "", x:=1, d:=b1) Foo5(1, "", d:=b1, b2, b3, d1) Foo5("", 1, d:=b1, b2, b3, d1) Dim d2list = New Derived2() {} Foo5(j:="", i:=1, d:=b2, d2list) Dim d1list = New Derived1() {} Foo5(j:="", i:=1, d:=b2, d1list) End Sub End Class]]> </Document> <Document><![CDATA[ Option Strict On Public Class Program2 Class Base End Class Class Derived Inherits Base End Class Public Sub Foo(ByRef d As Derived, i As Integer) End Sub Public Sub Foo(ByRef d As Derived, d2 As Derived) End Sub Public Sub M() Dim b As Base = New Derived Foo(b, 1) End Sub End Class]]> </Document> </Project> <Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true"> <ProjectReference>Assembly1</ProjectReference> <Document><![CDATA[ Option Strict On Public Class Program3 Class Base End Class Class Derived Inherits Base End Class Public Sub Foo(ByRef d As Derived, i As Integer) End Sub Public Sub Foo(ByRef d As Derived, d2 As Derived) End Sub Public Sub M() Dim b As Base = New Derived Foo(b, 1) End Sub End Class]]> </Document> </Project> </Workspace>.ToString() Dim expected = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document><![CDATA[ Option Strict On Public Class Program1 Interface Base1 End Interface Interface Base2 Inherits Base1 End Interface Interface Base3 End Interface Class Derived1 Implements Base2, Base3 End Class Class Derived2 Inherits Derived1 End Class Private Sub Foo4(ByVal i As Integer, ByVal j As String, ByVal d As Derived1) End Sub Private Sub Foo4(ByVal j As String, ByVal i As Integer, ByVal d As Derived1) End Sub Private Sub Foo5(ByVal j As String, ByVal i As Integer, ByVal d As Derived2, ByVal Optional x As Integer = 1) End Sub Private Sub Foo5(ByVal j As String, ByVal i As Integer, ByVal d As Derived1, ParamArray d2list As Derived2()) End Sub Private Sub M2(ByVal b1 As Base1, ByVal b2 As Base2, ByVal b3 As Base3, ByVal d1 As Derived1, ByVal d2 As Derived2) Foo4(1, "", b1) Foo4(i:=1, j:="", CType(b1, Derived1)) Foo5("", 1, b1) Foo5(d:=CType(b1, Derived2), i:=1, j:="", x:=1) Foo5(CStr(1), "", x:=1, d:=b1) Foo5(1, "", d:=b1, b2, b3, d1) Foo5("", 1, d:=b1, b2, b3, d1) Dim d2list = New Derived2() {} Foo5(j:="", i:=1, d:=CType(b2, Derived1), d2list) Dim d1list = New Derived1() {} Foo5(j:="", i:=1, d:=CType(b2, Derived1), d1list) End Sub End Class]]> </Document> <Document><![CDATA[ Option Strict On Public Class Program2 Class Base End Class Class Derived Inherits Base End Class Public Sub Foo(ByRef d As Derived, i As Integer) End Sub Public Sub Foo(ByRef d As Derived, d2 As Derived) End Sub Public Sub M() Dim b As Base = New Derived Foo(b, 1) End Sub End Class]]> </Document> </Project> <Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true"> <ProjectReference>Assembly1</ProjectReference> <Document><![CDATA[ Option Strict On Public Class Program3 Class Base End Class Class Derived Inherits Base End Class Public Sub Foo(ByRef d As Derived, i As Integer) End Sub Public Sub Foo(ByRef d As Derived, d2 As Derived) End Sub Public Sub M() Dim b As Base = New Derived Foo(b, 1) End Sub End Class]]> </Document> </Project> </Workspace>.ToString() Await TestInRegularAndScriptAsync(input, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddExplicitCast)> Public Async Function TestFixAllInProjectBC30519() As Task Dim input = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document><![CDATA[ Option Strict On Public Class Program1 Interface Base1 End Interface Interface Base2 Inherits Base1 End Interface Interface Base3 End Interface Class Derived1 Implements Base2, Base3 End Class Class Derived2 Inherits Derived1 End Class Private Sub Foo4(ByVal i As Integer, ByVal j As String, ByVal d As Derived1) End Sub Private Sub Foo4(ByVal j As String, ByVal i As Integer, ByVal d As Derived1) End Sub Private Sub Foo5(ByVal j As String, ByVal i As Integer, ByVal d As Derived2, ByVal Optional x As Integer = 1) End Sub Private Sub Foo5(ByVal j As String, ByVal i As Integer, ByVal d As Derived1, ParamArray d2list As Derived2()) End Sub Private Sub M2(ByVal b1 As Base1, ByVal b2 As Base2, ByVal b3 As Base3, ByVal d1 As Derived1, ByVal d2 As Derived2) Foo4(1, "", b1) {|FixAllInProject:Foo4(i:=1, j:="", b1)|} Foo5("", 1, b1) Foo5(d:=b1, i:=1, j:="", x:=1) Foo5(1, "", x:=1, d:=b1) Foo5(1, "", d:=b1, b2, b3, d1) Foo5("", 1, d:=b1, b2, b3, d1) Dim d2list = New Derived2() {} Foo5(j:="", i:=1, d:=b2, d2list) Dim d1list = New Derived1() {} Foo5(j:="", i:=1, d:=b2, d1list) End Sub End Class]]> </Document> <Document><![CDATA[ Option Strict On Public Class Program2 Class Base End Class Class Derived Inherits Base End Class Public Sub Foo(ByRef d As Derived, i As Integer) End Sub Public Sub Foo(ByRef d As Derived, d2 As Derived) End Sub Public Sub M() Dim b As Base = New Derived Foo(b, 1) End Sub End Class]]> </Document> </Project> <Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true"> <ProjectReference>Assembly1</ProjectReference> <Document><![CDATA[ Option Strict On Public Class Program3 Class Base End Class Class Derived Inherits Base End Class Public Sub Foo(ByRef d As Derived, i As Integer) End Sub Public Sub Foo(ByRef d As Derived, d2 As Derived) End Sub Public Sub M() Dim b As Base = New Derived Foo(b, 1) End Sub End Class]]> </Document> </Project> </Workspace>.ToString() Dim expected = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document><![CDATA[ Option Strict On Public Class Program1 Interface Base1 End Interface Interface Base2 Inherits Base1 End Interface Interface Base3 End Interface Class Derived1 Implements Base2, Base3 End Class Class Derived2 Inherits Derived1 End Class Private Sub Foo4(ByVal i As Integer, ByVal j As String, ByVal d As Derived1) End Sub Private Sub Foo4(ByVal j As String, ByVal i As Integer, ByVal d As Derived1) End Sub Private Sub Foo5(ByVal j As String, ByVal i As Integer, ByVal d As Derived2, ByVal Optional x As Integer = 1) End Sub Private Sub Foo5(ByVal j As String, ByVal i As Integer, ByVal d As Derived1, ParamArray d2list As Derived2()) End Sub Private Sub M2(ByVal b1 As Base1, ByVal b2 As Base2, ByVal b3 As Base3, ByVal d1 As Derived1, ByVal d2 As Derived2) Foo4(1, "", b1) Foo4(i:=1, j:="", CType(b1, Derived1)) Foo5("", 1, b1) Foo5(d:=CType(b1, Derived2), i:=1, j:="", x:=1) Foo5(CStr(1), "", x:=1, d:=b1) Foo5(1, "", d:=b1, b2, b3, d1) Foo5("", 1, d:=b1, b2, b3, d1) Dim d2list = New Derived2() {} Foo5(j:="", i:=1, d:=CType(b2, Derived1), d2list) Dim d1list = New Derived1() {} Foo5(j:="", i:=1, d:=CType(b2, Derived1), d1list) End Sub End Class]]> </Document> <Document><![CDATA[ Option Strict On Public Class Program2 Class Base End Class Class Derived Inherits Base End Class Public Sub Foo(ByRef d As Derived, i As Integer) End Sub Public Sub Foo(ByRef d As Derived, d2 As Derived) End Sub Public Sub M() Dim b As Base = New Derived Foo(CType(b, Derived), 1) End Sub End Class]]> </Document> </Project> <Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true"> <ProjectReference>Assembly1</ProjectReference> <Document><![CDATA[ Option Strict On Public Class Program3 Class Base End Class Class Derived Inherits Base End Class Public Sub Foo(ByRef d As Derived, i As Integer) End Sub Public Sub Foo(ByRef d As Derived, d2 As Derived) End Sub Public Sub M() Dim b As Base = New Derived Foo(b, 1) End Sub End Class]]> </Document> </Project> </Workspace>.ToString() Await TestInRegularAndScriptAsync(input, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddExplicitCast)> Public Async Function TestFixAllInSolutionBC30519() As Task Dim input = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document><![CDATA[ Option Strict On Public Class Program1 Interface Base1 End Interface Interface Base2 Inherits Base1 End Interface Interface Base3 End Interface Class Derived1 Implements Base2, Base3 End Class Class Derived2 Inherits Derived1 End Class Private Sub Foo4(ByVal i As Integer, ByVal j As String, ByVal d As Derived1) End Sub Private Sub Foo4(ByVal j As String, ByVal i As Integer, ByVal d As Derived1) End Sub Private Sub Foo5(ByVal j As String, ByVal i As Integer, ByVal d As Derived2, ByVal Optional x As Integer = 1) End Sub Private Sub Foo5(ByVal j As String, ByVal i As Integer, ByVal d As Derived1, ParamArray d2list As Derived2()) End Sub Private Sub M2(ByVal b1 As Base1, ByVal b2 As Base2, ByVal b3 As Base3, ByVal d1 As Derived1, ByVal d2 As Derived2) Foo4(1, "", b1) {|FixAllInSolution:Foo4(i:=1, j:="", b1)|} Foo5("", 1, b1) Foo5(d:=b1, i:=1, j:="", x:=1) Foo5(1, "", x:=1, d:=b1) Foo5(1, "", d:=b1, b2, b3, d1) Foo5("", 1, d:=b1, b2, b3, d1) Dim d2list = New Derived2() {} Foo5(j:="", i:=1, d:=b2, d2list) Dim d1list = New Derived1() {} Foo5(j:="", i:=1, d:=b2, d1list) End Sub End Class]]> </Document> <Document><![CDATA[ Option Strict On Public Class Program2 Class Base End Class Class Derived Inherits Base End Class Public Sub Foo(ByRef d As Derived, i As Integer) End Sub Public Sub Foo(ByRef d As Derived, d2 As Derived) End Sub Public Sub M() Dim b As Base = New Derived Foo(b, 1) End Sub End Class]]> </Document> </Project> <Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true"> <ProjectReference>Assembly1</ProjectReference> <Document><![CDATA[ Option Strict On Public Class Program3 Class Base End Class Class Derived Inherits Base End Class Public Sub Foo(ByRef d As Derived, i As Integer) End Sub Public Sub Foo(ByRef d As Derived, d2 As Derived) End Sub Public Sub M() Dim b As Base = New Derived Foo(b, 1) End Sub End Class]]> </Document> </Project> </Workspace>.ToString() Dim expected = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document><![CDATA[ Option Strict On Public Class Program1 Interface Base1 End Interface Interface Base2 Inherits Base1 End Interface Interface Base3 End Interface Class Derived1 Implements Base2, Base3 End Class Class Derived2 Inherits Derived1 End Class Private Sub Foo4(ByVal i As Integer, ByVal j As String, ByVal d As Derived1) End Sub Private Sub Foo4(ByVal j As String, ByVal i As Integer, ByVal d As Derived1) End Sub Private Sub Foo5(ByVal j As String, ByVal i As Integer, ByVal d As Derived2, ByVal Optional x As Integer = 1) End Sub Private Sub Foo5(ByVal j As String, ByVal i As Integer, ByVal d As Derived1, ParamArray d2list As Derived2()) End Sub Private Sub M2(ByVal b1 As Base1, ByVal b2 As Base2, ByVal b3 As Base3, ByVal d1 As Derived1, ByVal d2 As Derived2) Foo4(1, "", b1) Foo4(i:=1, j:="", CType(b1, Derived1)) Foo5("", 1, b1) Foo5(d:=CType(b1, Derived2), i:=1, j:="", x:=1) Foo5(CStr(1), "", x:=1, d:=b1) Foo5(1, "", d:=b1, b2, b3, d1) Foo5("", 1, d:=b1, b2, b3, d1) Dim d2list = New Derived2() {} Foo5(j:="", i:=1, d:=CType(b2, Derived1), d2list) Dim d1list = New Derived1() {} Foo5(j:="", i:=1, d:=CType(b2, Derived1), d1list) End Sub End Class]]> </Document> <Document><![CDATA[ Option Strict On Public Class Program2 Class Base End Class Class Derived Inherits Base End Class Public Sub Foo(ByRef d As Derived, i As Integer) End Sub Public Sub Foo(ByRef d As Derived, d2 As Derived) End Sub Public Sub M() Dim b As Base = New Derived Foo(CType(b, Derived), 1) End Sub End Class]]> </Document> </Project> <Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true"> <ProjectReference>Assembly1</ProjectReference> <Document><![CDATA[ Option Strict On Public Class Program3 Class Base End Class Class Derived Inherits Base End Class Public Sub Foo(ByRef d As Derived, i As Integer) End Sub Public Sub Foo(ByRef d As Derived, d2 As Derived) End Sub Public Sub M() Dim b As Base = New Derived Foo(CType(b, Derived), 1) End Sub End Class]]> </Document> </Project> </Workspace>.ToString() Await TestInRegularAndScriptAsync(input, expected) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics.AddExplicitCast Partial Public Class AddExplicitCastTests <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddExplicitCast)> Public Async Function TestFixAllInDocumentBC30512() As Task Dim input = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document><![CDATA[ Option Strict On Public Class Program1 Class Base End Class Class Derived Inherits Base End Class Class Test Public Property D As Derived Public Property B As Base Public Sub New() End Sub Public Sub New(ByRef d As Derived) Me.D = d End Sub Public Sub testing(ByVal d As Derived) End Sub Private Sub testing(ByVal b As Base) End Sub End Class Class Test2 Inherits Test Public Sub New(ByVal b As Base) MyBase.New(b) End Sub End Class Class Test3 Public Sub New(ByVal b As Derived) End Sub Public Sub New(ByVal i As Integer, ByVal b As Base) Me.New(b) End Sub End Class Private Function ReturnBase() As Base Dim b As Base = New Base() Return b End Function Private Function ReturnBase(ByVal d As Derived) As Base Dim b As Base = New Base() Return b End Function Private Function ReturnDerived(ByVal b As Base) As Derived Return b End Function Private Function ReturnDerived2(ByVal b As Base) As Derived Return ReturnBase() End Function Public Sub New() Dim b As Base = New Derived Dim d As Derived = {|FixAllInDocument:b|} d = New Base() Dim d2 As Derived = ReturnBase() d2 = ReturnBase(b) Dim t As Test = New Test() t.D = b t.D = b d = t.B End Sub Private Sub PassDerived(ByVal d As Derived) End Sub Private Sub PassDerived(ByVal i As Integer, ByVal d As Derived) End Sub Public Sub M() Dim b As Base = New Derived Dim d As Derived = b PassDerived(b) PassDerived(ReturnBase()) PassDerived(1, b) PassDerived(1, ReturnBase()) Dim list As List(Of Derived) = New List(Of Derived)() list.Add(b) Dim t As Test = New Test() t.testing(b) Dim foo2 As Func(Of Derived, Base) = Function(p_d) p_d Dim d2 As Derived = foo2(b) d2 = foo2(d) End Sub End Class]]> </Document> <Document><![CDATA[ Option Strict On Public Class Program2 Interface Base1 End Interface Interface Base2 Inherits Base1 End Interface Interface Base3 End Interface Class Derived1 Implements Base2, Base3 End Class Class Derived2 Inherits Derived1 End Class Class Test Public Shared Narrowing Operator CType(t As Test) As Derived2 Return New Derived2 End Operator End Class Private Function returnDerived2_1() As Derived2 Return New Derived1() End Function Private Function returnDerived2_2() As Derived2 Return New Test() End Function Private Sub Foo1(ByVal b As Derived2) End Sub Private Sub Foo2(ByVal b As Base2) End Sub Private Sub Foo3(ByVal b1 As Derived2) End Sub Private Sub Foo3(ByVal i As Integer) End Sub Private Sub M2(ByVal b1 As Base1, ByVal b2 As Base2, ByVal b3 As Base3, ByVal d1 As Derived1, ByVal d2 As Derived2) Dim derived2 As Derived2 = b1 derived2 = b3 Dim base2 As Base2 = b1 derived2 = d1 d2 = New Test() Foo1(b1) Foo1(d1) Foo2(b1) Foo3(b1) End Sub End Class]]> </Document> </Project> <Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true"> <ProjectReference>Assembly1</ProjectReference> <Document><![CDATA[ Option Strict On Public Class Program3 Class Base End Class Class Derived Inherits Base End Class Private Sub returnD2(ByVal b As Base) Dim d As Derived = b End Sub End Class]]> </Document> </Project> </Workspace>.ToString() Dim expected = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document><![CDATA[ Option Strict On Public Class Program1 Class Base End Class Class Derived Inherits Base End Class Class Test Public Property D As Derived Public Property B As Base Public Sub New() End Sub Public Sub New(ByRef d As Derived) Me.D = d End Sub Public Sub testing(ByVal d As Derived) End Sub Private Sub testing(ByVal b As Base) End Sub End Class Class Test2 Inherits Test Public Sub New(ByVal b As Base) MyBase.New(CType(b, Derived)) End Sub End Class Class Test3 Public Sub New(ByVal b As Derived) End Sub Public Sub New(ByVal i As Integer, ByVal b As Base) Me.New(CType(b, Derived)) End Sub End Class Private Function ReturnBase() As Base Dim b As Base = New Base() Return b End Function Private Function ReturnBase(ByVal d As Derived) As Base Dim b As Base = New Base() Return b End Function Private Function ReturnDerived(ByVal b As Base) As Derived Return CType(b, Derived) End Function Private Function ReturnDerived2(ByVal b As Base) As Derived Return CType(ReturnBase(), Derived) End Function Public Sub New() Dim b As Base = New Derived Dim d As Derived = CType(b, Derived) d = New Base() Dim d2 As Derived = CType(ReturnBase(), Derived) d2 = ReturnBase(CType(b, Derived)) Dim t As Test = New Test() t.D = CType(b, Derived) t.D = CType(b, Derived) d = CType(t.B, Derived) End Sub Private Sub PassDerived(ByVal d As Derived) End Sub Private Sub PassDerived(ByVal i As Integer, ByVal d As Derived) End Sub Public Sub M() Dim b As Base = New Derived Dim d As Derived = CType(b, Derived) PassDerived(CType(b, Derived)) PassDerived(CType(ReturnBase(), Derived)) PassDerived(1, CType(b, Derived)) PassDerived(1, CType(ReturnBase(), Derived)) Dim list As List(Of Derived) = New List(Of Derived)() list.Add(CType(b, Derived)) Dim t As Test = New Test() t.testing(CType(b, Derived)) Dim foo2 As Func(Of Derived, Base) = Function(p_d) p_d Dim d2 As Derived = foo2(CType(b, Derived)) d2 = CType(foo2(d), Derived) End Sub End Class]]> </Document> <Document><![CDATA[ Option Strict On Public Class Program2 Interface Base1 End Interface Interface Base2 Inherits Base1 End Interface Interface Base3 End Interface Class Derived1 Implements Base2, Base3 End Class Class Derived2 Inherits Derived1 End Class Class Test Public Shared Narrowing Operator CType(t As Test) As Derived2 Return New Derived2 End Operator End Class Private Function returnDerived2_1() As Derived2 Return New Derived1() End Function Private Function returnDerived2_2() As Derived2 Return New Test() End Function Private Sub Foo1(ByVal b As Derived2) End Sub Private Sub Foo2(ByVal b As Base2) End Sub Private Sub Foo3(ByVal b1 As Derived2) End Sub Private Sub Foo3(ByVal i As Integer) End Sub Private Sub M2(ByVal b1 As Base1, ByVal b2 As Base2, ByVal b3 As Base3, ByVal d1 As Derived1, ByVal d2 As Derived2) Dim derived2 As Derived2 = b1 derived2 = b3 Dim base2 As Base2 = b1 derived2 = d1 d2 = New Test() Foo1(b1) Foo1(d1) Foo2(b1) Foo3(b1) End Sub End Class]]> </Document> </Project> <Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true"> <ProjectReference>Assembly1</ProjectReference> <Document><![CDATA[ Option Strict On Public Class Program3 Class Base End Class Class Derived Inherits Base End Class Private Sub returnD2(ByVal b As Base) Dim d As Derived = b End Sub End Class]]> </Document> </Project> </Workspace>.ToString() Await TestInRegularAndScriptAsync(input, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddExplicitCast)> Public Async Function TestFixAllInProjectBC30512() As Task Dim input = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document><![CDATA[ Option Strict On Public Class Program1 Class Base End Class Class Derived Inherits Base End Class Class Test Public Property D As Derived Public Property B As Base Public Sub New() End Sub Public Sub New(ByRef d As Derived) Me.D = d End Sub Public Sub testing(ByVal d As Derived) End Sub Private Sub testing(ByVal b As Base) End Sub End Class Class Test2 Inherits Test Public Sub New(ByVal b As Base) MyBase.New(b) End Sub End Class Class Test3 Public Sub New(ByVal b As Derived) End Sub Public Sub New(ByVal i As Integer, ByVal b As Base) Me.New(b) End Sub End Class Private Function ReturnBase() As Base Dim b As Base = New Base() Return b End Function Private Function ReturnBase(ByVal d As Derived) As Base Dim b As Base = New Base() Return b End Function Private Function ReturnDerived(ByVal b As Base) As Derived Return b End Function Private Function ReturnDerived2(ByVal b As Base) As Derived Return ReturnBase() End Function Public Sub New() Dim b As Base = New Derived Dim d As Derived = {|FixAllInProject:b|} d = New Base() Dim d2 As Derived = ReturnBase() d2 = ReturnBase(b) Dim t As Test = New Test() t.D = b t.D = b d = t.B End Sub Private Sub PassDerived(ByVal d As Derived) End Sub Private Sub PassDerived(ByVal i As Integer, ByVal d As Derived) End Sub Public Sub M() Dim b As Base = New Derived Dim d As Derived = b PassDerived(b) PassDerived(ReturnBase()) PassDerived(1, b) PassDerived(1, ReturnBase()) Dim list As List(Of Derived) = New List(Of Derived)() list.Add(b) Dim t As Test = New Test() t.testing(b) Dim foo2 As Func(Of Derived, Base) = Function(p_d) p_d Dim d2 As Derived = foo2(b) d2 = foo2(d) End Sub End Class]]> </Document> <Document><![CDATA[ Option Strict On Public Class Program2 Interface Base1 End Interface Interface Base2 Inherits Base1 End Interface Interface Base3 End Interface Class Derived1 Implements Base2, Base3 End Class Class Derived2 Inherits Derived1 End Class Class Test Public Shared Narrowing Operator CType(t As Test) As Derived2 Return New Derived2 End Operator End Class Private Function returnDerived2_1() As Derived2 Return New Derived1() End Function Private Function returnDerived2_2() As Derived2 Return New Test() End Function Private Sub Foo1(ByVal b As Derived2) End Sub Private Sub Foo2(ByVal b As Base2) End Sub Private Sub Foo3(ByVal b1 As Derived2) End Sub Private Sub Foo3(ByVal i As Integer) End Sub Private Sub M2(ByVal b1 As Base1, ByVal b2 As Base2, ByVal b3 As Base3, ByVal d1 As Derived1, ByVal d2 As Derived2) Dim derived2 As Derived2 = b1 derived2 = b3 Dim base2 As Base2 = b1 derived2 = d1 d2 = New Test() Foo1(b1) Foo1(d1) Foo2(b1) Foo3(b1) End Sub End Class]]> </Document> </Project> <Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true"> <ProjectReference>Assembly1</ProjectReference> <Document><![CDATA[ Option Strict On Public Class Program3 Class Base End Class Class Derived Inherits Base End Class Private Sub returnD2(ByVal b As Base) Dim d As Derived = b End Sub End Class]]> </Document> </Project> </Workspace>.ToString() Dim expected = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document><![CDATA[ Option Strict On Public Class Program1 Class Base End Class Class Derived Inherits Base End Class Class Test Public Property D As Derived Public Property B As Base Public Sub New() End Sub Public Sub New(ByRef d As Derived) Me.D = d End Sub Public Sub testing(ByVal d As Derived) End Sub Private Sub testing(ByVal b As Base) End Sub End Class Class Test2 Inherits Test Public Sub New(ByVal b As Base) MyBase.New(CType(b, Derived)) End Sub End Class Class Test3 Public Sub New(ByVal b As Derived) End Sub Public Sub New(ByVal i As Integer, ByVal b As Base) Me.New(CType(b, Derived)) End Sub End Class Private Function ReturnBase() As Base Dim b As Base = New Base() Return b End Function Private Function ReturnBase(ByVal d As Derived) As Base Dim b As Base = New Base() Return b End Function Private Function ReturnDerived(ByVal b As Base) As Derived Return CType(b, Derived) End Function Private Function ReturnDerived2(ByVal b As Base) As Derived Return CType(ReturnBase(), Derived) End Function Public Sub New() Dim b As Base = New Derived Dim d As Derived = CType(b, Derived) d = New Base() Dim d2 As Derived = CType(ReturnBase(), Derived) d2 = ReturnBase(CType(b, Derived)) Dim t As Test = New Test() t.D = CType(b, Derived) t.D = CType(b, Derived) d = CType(t.B, Derived) End Sub Private Sub PassDerived(ByVal d As Derived) End Sub Private Sub PassDerived(ByVal i As Integer, ByVal d As Derived) End Sub Public Sub M() Dim b As Base = New Derived Dim d As Derived = CType(b, Derived) PassDerived(CType(b, Derived)) PassDerived(CType(ReturnBase(), Derived)) PassDerived(1, CType(b, Derived)) PassDerived(1, CType(ReturnBase(), Derived)) Dim list As List(Of Derived) = New List(Of Derived)() list.Add(CType(b, Derived)) Dim t As Test = New Test() t.testing(CType(b, Derived)) Dim foo2 As Func(Of Derived, Base) = Function(p_d) p_d Dim d2 As Derived = foo2(CType(b, Derived)) d2 = CType(foo2(d), Derived) End Sub End Class]]> </Document> <Document><![CDATA[ Option Strict On Public Class Program2 Interface Base1 End Interface Interface Base2 Inherits Base1 End Interface Interface Base3 End Interface Class Derived1 Implements Base2, Base3 End Class Class Derived2 Inherits Derived1 End Class Class Test Public Shared Narrowing Operator CType(t As Test) As Derived2 Return New Derived2 End Operator End Class Private Function returnDerived2_1() As Derived2 Return New Derived1() End Function Private Function returnDerived2_2() As Derived2 Return CType(New Test(), Derived2) End Function Private Sub Foo1(ByVal b As Derived2) End Sub Private Sub Foo2(ByVal b As Base2) End Sub Private Sub Foo3(ByVal b1 As Derived2) End Sub Private Sub Foo3(ByVal i As Integer) End Sub Private Sub M2(ByVal b1 As Base1, ByVal b2 As Base2, ByVal b3 As Base3, ByVal d1 As Derived1, ByVal d2 As Derived2) Dim derived2 As Derived2 = CType(b1, Derived2) derived2 = CType(b3, Derived2) Dim base2 As Base2 = CType(b1, Base2) derived2 = CType(d1, Derived2) d2 = CType(New Test(), Derived2) Foo1(CType(b1, Derived2)) Foo1(CType(d1, Derived2)) Foo2(CType(b1, Base2)) Foo3(b1) End Sub End Class]]> </Document> </Project> <Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true"> <ProjectReference>Assembly1</ProjectReference> <Document><![CDATA[ Option Strict On Public Class Program3 Class Base End Class Class Derived Inherits Base End Class Private Sub returnD2(ByVal b As Base) Dim d As Derived = b End Sub End Class]]> </Document> </Project> </Workspace>.ToString() Await TestInRegularAndScriptAsync(input, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddExplicitCast)> Public Async Function TestFixAllInSolutionBC30512() As Task Dim input = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document><![CDATA[ Option Strict On Public Class Program1 Class Base End Class Class Derived Inherits Base End Class Class Test Public Property D As Derived Public Property B As Base Public Sub New() End Sub Public Sub New(ByRef d As Derived) Me.D = d End Sub Public Sub testing(ByVal d As Derived) End Sub Private Sub testing(ByVal b As Base) End Sub End Class Class Test2 Inherits Test Public Sub New(ByVal b As Base) MyBase.New(b) End Sub End Class Class Test3 Public Sub New(ByVal b As Derived) End Sub Public Sub New(ByVal i As Integer, ByVal b As Base) Me.New(b) End Sub End Class Private Function ReturnBase() As Base Dim b As Base = New Base() Return b End Function Private Function ReturnBase(ByVal d As Derived) As Base Dim b As Base = New Base() Return b End Function Private Function ReturnDerived(ByVal b As Base) As Derived Return b End Function Private Function ReturnDerived2(ByVal b As Base) As Derived Return ReturnBase() End Function Public Sub New() Dim b As Base = New Derived Dim d As Derived = {|FixAllInSolution:b|} d = New Base() Dim d2 As Derived = ReturnBase() d2 = ReturnBase(b) Dim t As Test = New Test() t.D = b t.D = b d = t.B End Sub Private Sub PassDerived(ByVal d As Derived) End Sub Private Sub PassDerived(ByVal i As Integer, ByVal d As Derived) End Sub Public Sub M() Dim b As Base = New Derived Dim d As Derived = b PassDerived(b) PassDerived(ReturnBase()) PassDerived(1, b) PassDerived(1, ReturnBase()) Dim list As List(Of Derived) = New List(Of Derived)() list.Add(b) Dim t As Test = New Test() t.testing(b) Dim foo2 As Func(Of Derived, Base) = Function(p_d) p_d Dim d2 As Derived = foo2(b) d2 = foo2(d) End Sub End Class]]> </Document> <Document><![CDATA[ Option Strict On Public Class Program2 Interface Base1 End Interface Interface Base2 Inherits Base1 End Interface Interface Base3 End Interface Class Derived1 Implements Base2, Base3 End Class Class Derived2 Inherits Derived1 End Class Class Test Public Shared Narrowing Operator CType(t As Test) As Derived2 Return New Derived2 End Operator End Class Private Function returnDerived2_1() As Derived2 Return New Derived1() End Function Private Function returnDerived2_2() As Derived2 Return New Test() End Function Private Sub Foo1(ByVal b As Derived2) End Sub Private Sub Foo2(ByVal b As Base2) End Sub Private Sub Foo3(ByVal b1 As Derived2) End Sub Private Sub Foo3(ByVal i As Integer) End Sub Private Sub M2(ByVal b1 As Base1, ByVal b2 As Base2, ByVal b3 As Base3, ByVal d1 As Derived1, ByVal d2 As Derived2) Dim derived2 As Derived2 = b1 derived2 = b3 Dim base2 As Base2 = b1 derived2 = d1 d2 = New Test() Foo1(b1) Foo1(d1) Foo2(b1) Foo3(b1) End Sub End Class]]> </Document> </Project> <Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true"> <ProjectReference>Assembly1</ProjectReference> <Document><![CDATA[ Option Strict On Public Class Program3 Class Base End Class Class Derived Inherits Base End Class Private Sub returnD2(ByVal b As Base) Dim d As Derived = b End Sub End Class]]> </Document> </Project> </Workspace>.ToString() Dim expected = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document><![CDATA[ Option Strict On Public Class Program1 Class Base End Class Class Derived Inherits Base End Class Class Test Public Property D As Derived Public Property B As Base Public Sub New() End Sub Public Sub New(ByRef d As Derived) Me.D = d End Sub Public Sub testing(ByVal d As Derived) End Sub Private Sub testing(ByVal b As Base) End Sub End Class Class Test2 Inherits Test Public Sub New(ByVal b As Base) MyBase.New(CType(b, Derived)) End Sub End Class Class Test3 Public Sub New(ByVal b As Derived) End Sub Public Sub New(ByVal i As Integer, ByVal b As Base) Me.New(CType(b, Derived)) End Sub End Class Private Function ReturnBase() As Base Dim b As Base = New Base() Return b End Function Private Function ReturnBase(ByVal d As Derived) As Base Dim b As Base = New Base() Return b End Function Private Function ReturnDerived(ByVal b As Base) As Derived Return CType(b, Derived) End Function Private Function ReturnDerived2(ByVal b As Base) As Derived Return CType(ReturnBase(), Derived) End Function Public Sub New() Dim b As Base = New Derived Dim d As Derived = CType(b, Derived) d = New Base() Dim d2 As Derived = CType(ReturnBase(), Derived) d2 = ReturnBase(CType(b, Derived)) Dim t As Test = New Test() t.D = CType(b, Derived) t.D = CType(b, Derived) d = CType(t.B, Derived) End Sub Private Sub PassDerived(ByVal d As Derived) End Sub Private Sub PassDerived(ByVal i As Integer, ByVal d As Derived) End Sub Public Sub M() Dim b As Base = New Derived Dim d As Derived = CType(b, Derived) PassDerived(CType(b, Derived)) PassDerived(CType(ReturnBase(), Derived)) PassDerived(1, CType(b, Derived)) PassDerived(1, CType(ReturnBase(), Derived)) Dim list As List(Of Derived) = New List(Of Derived)() list.Add(CType(b, Derived)) Dim t As Test = New Test() t.testing(CType(b, Derived)) Dim foo2 As Func(Of Derived, Base) = Function(p_d) p_d Dim d2 As Derived = foo2(CType(b, Derived)) d2 = CType(foo2(d), Derived) End Sub End Class]]> </Document> <Document><![CDATA[ Option Strict On Public Class Program2 Interface Base1 End Interface Interface Base2 Inherits Base1 End Interface Interface Base3 End Interface Class Derived1 Implements Base2, Base3 End Class Class Derived2 Inherits Derived1 End Class Class Test Public Shared Narrowing Operator CType(t As Test) As Derived2 Return New Derived2 End Operator End Class Private Function returnDerived2_1() As Derived2 Return New Derived1() End Function Private Function returnDerived2_2() As Derived2 Return CType(New Test(), Derived2) End Function Private Sub Foo1(ByVal b As Derived2) End Sub Private Sub Foo2(ByVal b As Base2) End Sub Private Sub Foo3(ByVal b1 As Derived2) End Sub Private Sub Foo3(ByVal i As Integer) End Sub Private Sub M2(ByVal b1 As Base1, ByVal b2 As Base2, ByVal b3 As Base3, ByVal d1 As Derived1, ByVal d2 As Derived2) Dim derived2 As Derived2 = CType(b1, Derived2) derived2 = CType(b3, Derived2) Dim base2 As Base2 = CType(b1, Base2) derived2 = CType(d1, Derived2) d2 = CType(New Test(), Derived2) Foo1(CType(b1, Derived2)) Foo1(CType(d1, Derived2)) Foo2(CType(b1, Base2)) Foo3(b1) End Sub End Class]]> </Document> </Project> <Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true"> <ProjectReference>Assembly1</ProjectReference> <Document><![CDATA[ Option Strict On Public Class Program3 Class Base End Class Class Derived Inherits Base End Class Private Sub returnD2(ByVal b As Base) Dim d As Derived = CType(b, Derived) End Sub End Class]]> </Document> </Project> </Workspace>.ToString() Await TestInRegularAndScriptAsync(input, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddExplicitCast)> Public Async Function TestFixAllInDocumentBC30519() As Task Dim input = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document><![CDATA[ Option Strict On Public Class Program1 Interface Base1 End Interface Interface Base2 Inherits Base1 End Interface Interface Base3 End Interface Class Derived1 Implements Base2, Base3 End Class Class Derived2 Inherits Derived1 End Class Private Sub Foo4(ByVal i As Integer, ByVal j As String, ByVal d As Derived1) End Sub Private Sub Foo4(ByVal j As String, ByVal i As Integer, ByVal d As Derived1) End Sub Private Sub Foo5(ByVal j As String, ByVal i As Integer, ByVal d As Derived2, ByVal Optional x As Integer = 1) End Sub Private Sub Foo5(ByVal j As String, ByVal i As Integer, ByVal d As Derived1, ParamArray d2list As Derived2()) End Sub Private Sub M2(ByVal b1 As Base1, ByVal b2 As Base2, ByVal b3 As Base3, ByVal d1 As Derived1, ByVal d2 As Derived2) Foo4(1, "", b1) {|FixAllInDocument:Foo4(i:=1, j:="", b1)|} Foo5("", 1, b1) Foo5(d:=b1, i:=1, j:="", x:=1) Foo5(1, "", x:=1, d:=b1) Foo5(1, "", d:=b1, b2, b3, d1) Foo5("", 1, d:=b1, b2, b3, d1) Dim d2list = New Derived2() {} Foo5(j:="", i:=1, d:=b2, d2list) Dim d1list = New Derived1() {} Foo5(j:="", i:=1, d:=b2, d1list) End Sub End Class]]> </Document> <Document><![CDATA[ Option Strict On Public Class Program2 Class Base End Class Class Derived Inherits Base End Class Public Sub Foo(ByRef d As Derived, i As Integer) End Sub Public Sub Foo(ByRef d As Derived, d2 As Derived) End Sub Public Sub M() Dim b As Base = New Derived Foo(b, 1) End Sub End Class]]> </Document> </Project> <Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true"> <ProjectReference>Assembly1</ProjectReference> <Document><![CDATA[ Option Strict On Public Class Program3 Class Base End Class Class Derived Inherits Base End Class Public Sub Foo(ByRef d As Derived, i As Integer) End Sub Public Sub Foo(ByRef d As Derived, d2 As Derived) End Sub Public Sub M() Dim b As Base = New Derived Foo(b, 1) End Sub End Class]]> </Document> </Project> </Workspace>.ToString() Dim expected = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document><![CDATA[ Option Strict On Public Class Program1 Interface Base1 End Interface Interface Base2 Inherits Base1 End Interface Interface Base3 End Interface Class Derived1 Implements Base2, Base3 End Class Class Derived2 Inherits Derived1 End Class Private Sub Foo4(ByVal i As Integer, ByVal j As String, ByVal d As Derived1) End Sub Private Sub Foo4(ByVal j As String, ByVal i As Integer, ByVal d As Derived1) End Sub Private Sub Foo5(ByVal j As String, ByVal i As Integer, ByVal d As Derived2, ByVal Optional x As Integer = 1) End Sub Private Sub Foo5(ByVal j As String, ByVal i As Integer, ByVal d As Derived1, ParamArray d2list As Derived2()) End Sub Private Sub M2(ByVal b1 As Base1, ByVal b2 As Base2, ByVal b3 As Base3, ByVal d1 As Derived1, ByVal d2 As Derived2) Foo4(1, "", b1) Foo4(i:=1, j:="", CType(b1, Derived1)) Foo5("", 1, b1) Foo5(d:=CType(b1, Derived2), i:=1, j:="", x:=1) Foo5(CStr(1), "", x:=1, d:=b1) Foo5(1, "", d:=b1, b2, b3, d1) Foo5("", 1, d:=b1, b2, b3, d1) Dim d2list = New Derived2() {} Foo5(j:="", i:=1, d:=CType(b2, Derived1), d2list) Dim d1list = New Derived1() {} Foo5(j:="", i:=1, d:=CType(b2, Derived1), d1list) End Sub End Class]]> </Document> <Document><![CDATA[ Option Strict On Public Class Program2 Class Base End Class Class Derived Inherits Base End Class Public Sub Foo(ByRef d As Derived, i As Integer) End Sub Public Sub Foo(ByRef d As Derived, d2 As Derived) End Sub Public Sub M() Dim b As Base = New Derived Foo(b, 1) End Sub End Class]]> </Document> </Project> <Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true"> <ProjectReference>Assembly1</ProjectReference> <Document><![CDATA[ Option Strict On Public Class Program3 Class Base End Class Class Derived Inherits Base End Class Public Sub Foo(ByRef d As Derived, i As Integer) End Sub Public Sub Foo(ByRef d As Derived, d2 As Derived) End Sub Public Sub M() Dim b As Base = New Derived Foo(b, 1) End Sub End Class]]> </Document> </Project> </Workspace>.ToString() Await TestInRegularAndScriptAsync(input, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddExplicitCast)> Public Async Function TestFixAllInProjectBC30519() As Task Dim input = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document><![CDATA[ Option Strict On Public Class Program1 Interface Base1 End Interface Interface Base2 Inherits Base1 End Interface Interface Base3 End Interface Class Derived1 Implements Base2, Base3 End Class Class Derived2 Inherits Derived1 End Class Private Sub Foo4(ByVal i As Integer, ByVal j As String, ByVal d As Derived1) End Sub Private Sub Foo4(ByVal j As String, ByVal i As Integer, ByVal d As Derived1) End Sub Private Sub Foo5(ByVal j As String, ByVal i As Integer, ByVal d As Derived2, ByVal Optional x As Integer = 1) End Sub Private Sub Foo5(ByVal j As String, ByVal i As Integer, ByVal d As Derived1, ParamArray d2list As Derived2()) End Sub Private Sub M2(ByVal b1 As Base1, ByVal b2 As Base2, ByVal b3 As Base3, ByVal d1 As Derived1, ByVal d2 As Derived2) Foo4(1, "", b1) {|FixAllInProject:Foo4(i:=1, j:="", b1)|} Foo5("", 1, b1) Foo5(d:=b1, i:=1, j:="", x:=1) Foo5(1, "", x:=1, d:=b1) Foo5(1, "", d:=b1, b2, b3, d1) Foo5("", 1, d:=b1, b2, b3, d1) Dim d2list = New Derived2() {} Foo5(j:="", i:=1, d:=b2, d2list) Dim d1list = New Derived1() {} Foo5(j:="", i:=1, d:=b2, d1list) End Sub End Class]]> </Document> <Document><![CDATA[ Option Strict On Public Class Program2 Class Base End Class Class Derived Inherits Base End Class Public Sub Foo(ByRef d As Derived, i As Integer) End Sub Public Sub Foo(ByRef d As Derived, d2 As Derived) End Sub Public Sub M() Dim b As Base = New Derived Foo(b, 1) End Sub End Class]]> </Document> </Project> <Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true"> <ProjectReference>Assembly1</ProjectReference> <Document><![CDATA[ Option Strict On Public Class Program3 Class Base End Class Class Derived Inherits Base End Class Public Sub Foo(ByRef d As Derived, i As Integer) End Sub Public Sub Foo(ByRef d As Derived, d2 As Derived) End Sub Public Sub M() Dim b As Base = New Derived Foo(b, 1) End Sub End Class]]> </Document> </Project> </Workspace>.ToString() Dim expected = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document><![CDATA[ Option Strict On Public Class Program1 Interface Base1 End Interface Interface Base2 Inherits Base1 End Interface Interface Base3 End Interface Class Derived1 Implements Base2, Base3 End Class Class Derived2 Inherits Derived1 End Class Private Sub Foo4(ByVal i As Integer, ByVal j As String, ByVal d As Derived1) End Sub Private Sub Foo4(ByVal j As String, ByVal i As Integer, ByVal d As Derived1) End Sub Private Sub Foo5(ByVal j As String, ByVal i As Integer, ByVal d As Derived2, ByVal Optional x As Integer = 1) End Sub Private Sub Foo5(ByVal j As String, ByVal i As Integer, ByVal d As Derived1, ParamArray d2list As Derived2()) End Sub Private Sub M2(ByVal b1 As Base1, ByVal b2 As Base2, ByVal b3 As Base3, ByVal d1 As Derived1, ByVal d2 As Derived2) Foo4(1, "", b1) Foo4(i:=1, j:="", CType(b1, Derived1)) Foo5("", 1, b1) Foo5(d:=CType(b1, Derived2), i:=1, j:="", x:=1) Foo5(CStr(1), "", x:=1, d:=b1) Foo5(1, "", d:=b1, b2, b3, d1) Foo5("", 1, d:=b1, b2, b3, d1) Dim d2list = New Derived2() {} Foo5(j:="", i:=1, d:=CType(b2, Derived1), d2list) Dim d1list = New Derived1() {} Foo5(j:="", i:=1, d:=CType(b2, Derived1), d1list) End Sub End Class]]> </Document> <Document><![CDATA[ Option Strict On Public Class Program2 Class Base End Class Class Derived Inherits Base End Class Public Sub Foo(ByRef d As Derived, i As Integer) End Sub Public Sub Foo(ByRef d As Derived, d2 As Derived) End Sub Public Sub M() Dim b As Base = New Derived Foo(CType(b, Derived), 1) End Sub End Class]]> </Document> </Project> <Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true"> <ProjectReference>Assembly1</ProjectReference> <Document><![CDATA[ Option Strict On Public Class Program3 Class Base End Class Class Derived Inherits Base End Class Public Sub Foo(ByRef d As Derived, i As Integer) End Sub Public Sub Foo(ByRef d As Derived, d2 As Derived) End Sub Public Sub M() Dim b As Base = New Derived Foo(b, 1) End Sub End Class]]> </Document> </Project> </Workspace>.ToString() Await TestInRegularAndScriptAsync(input, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddExplicitCast)> Public Async Function TestFixAllInSolutionBC30519() As Task Dim input = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document><![CDATA[ Option Strict On Public Class Program1 Interface Base1 End Interface Interface Base2 Inherits Base1 End Interface Interface Base3 End Interface Class Derived1 Implements Base2, Base3 End Class Class Derived2 Inherits Derived1 End Class Private Sub Foo4(ByVal i As Integer, ByVal j As String, ByVal d As Derived1) End Sub Private Sub Foo4(ByVal j As String, ByVal i As Integer, ByVal d As Derived1) End Sub Private Sub Foo5(ByVal j As String, ByVal i As Integer, ByVal d As Derived2, ByVal Optional x As Integer = 1) End Sub Private Sub Foo5(ByVal j As String, ByVal i As Integer, ByVal d As Derived1, ParamArray d2list As Derived2()) End Sub Private Sub M2(ByVal b1 As Base1, ByVal b2 As Base2, ByVal b3 As Base3, ByVal d1 As Derived1, ByVal d2 As Derived2) Foo4(1, "", b1) {|FixAllInSolution:Foo4(i:=1, j:="", b1)|} Foo5("", 1, b1) Foo5(d:=b1, i:=1, j:="", x:=1) Foo5(1, "", x:=1, d:=b1) Foo5(1, "", d:=b1, b2, b3, d1) Foo5("", 1, d:=b1, b2, b3, d1) Dim d2list = New Derived2() {} Foo5(j:="", i:=1, d:=b2, d2list) Dim d1list = New Derived1() {} Foo5(j:="", i:=1, d:=b2, d1list) End Sub End Class]]> </Document> <Document><![CDATA[ Option Strict On Public Class Program2 Class Base End Class Class Derived Inherits Base End Class Public Sub Foo(ByRef d As Derived, i As Integer) End Sub Public Sub Foo(ByRef d As Derived, d2 As Derived) End Sub Public Sub M() Dim b As Base = New Derived Foo(b, 1) End Sub End Class]]> </Document> </Project> <Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true"> <ProjectReference>Assembly1</ProjectReference> <Document><![CDATA[ Option Strict On Public Class Program3 Class Base End Class Class Derived Inherits Base End Class Public Sub Foo(ByRef d As Derived, i As Integer) End Sub Public Sub Foo(ByRef d As Derived, d2 As Derived) End Sub Public Sub M() Dim b As Base = New Derived Foo(b, 1) End Sub End Class]]> </Document> </Project> </Workspace>.ToString() Dim expected = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document><![CDATA[ Option Strict On Public Class Program1 Interface Base1 End Interface Interface Base2 Inherits Base1 End Interface Interface Base3 End Interface Class Derived1 Implements Base2, Base3 End Class Class Derived2 Inherits Derived1 End Class Private Sub Foo4(ByVal i As Integer, ByVal j As String, ByVal d As Derived1) End Sub Private Sub Foo4(ByVal j As String, ByVal i As Integer, ByVal d As Derived1) End Sub Private Sub Foo5(ByVal j As String, ByVal i As Integer, ByVal d As Derived2, ByVal Optional x As Integer = 1) End Sub Private Sub Foo5(ByVal j As String, ByVal i As Integer, ByVal d As Derived1, ParamArray d2list As Derived2()) End Sub Private Sub M2(ByVal b1 As Base1, ByVal b2 As Base2, ByVal b3 As Base3, ByVal d1 As Derived1, ByVal d2 As Derived2) Foo4(1, "", b1) Foo4(i:=1, j:="", CType(b1, Derived1)) Foo5("", 1, b1) Foo5(d:=CType(b1, Derived2), i:=1, j:="", x:=1) Foo5(CStr(1), "", x:=1, d:=b1) Foo5(1, "", d:=b1, b2, b3, d1) Foo5("", 1, d:=b1, b2, b3, d1) Dim d2list = New Derived2() {} Foo5(j:="", i:=1, d:=CType(b2, Derived1), d2list) Dim d1list = New Derived1() {} Foo5(j:="", i:=1, d:=CType(b2, Derived1), d1list) End Sub End Class]]> </Document> <Document><![CDATA[ Option Strict On Public Class Program2 Class Base End Class Class Derived Inherits Base End Class Public Sub Foo(ByRef d As Derived, i As Integer) End Sub Public Sub Foo(ByRef d As Derived, d2 As Derived) End Sub Public Sub M() Dim b As Base = New Derived Foo(CType(b, Derived), 1) End Sub End Class]]> </Document> </Project> <Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true"> <ProjectReference>Assembly1</ProjectReference> <Document><![CDATA[ Option Strict On Public Class Program3 Class Base End Class Class Derived Inherits Base End Class Public Sub Foo(ByRef d As Derived, i As Integer) End Sub Public Sub Foo(ByRef d As Derived, d2 As Derived) End Sub Public Sub M() Dim b As Base = New Derived Foo(CType(b, Derived), 1) End Sub End Class]]> </Document> </Project> </Workspace>.ToString() Await TestInRegularAndScriptAsync(input, expected) 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/Compilers/VisualBasic/Portable/Compilation/QuerySymbolInfo.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic Public Structure CollectionRangeVariableSymbolInfo ''' <summary> ''' Optional AsQueryable/AsEnumerable/Cast(Of Object) method used ''' to "convert" <see cref="CollectionRangeVariableSyntax.Expression"/> to queryable ''' collection. ''' </summary> Public ReadOnly Property ToQueryableCollectionConversion As SymbolInfo ''' <summary> ''' Optional Select method to handle AsClause. ''' </summary> Public ReadOnly Property AsClauseConversion As SymbolInfo ''' <summary> ''' SelectMany method for <see cref="CollectionRangeVariableSyntax"/>, which is not the first ''' <see cref="CollectionRangeVariableSyntax"/> in a <see cref="QueryExpressionSyntax"/>, and is not the first ''' <see cref="CollectionRangeVariableSyntax"/> in <see cref="AggregateClauseSyntax"/>. ''' </summary> Public ReadOnly Property SelectMany As SymbolInfo Friend Shared ReadOnly None As New CollectionRangeVariableSymbolInfo(SymbolInfo.None, SymbolInfo.None, SymbolInfo.None) Friend Sub New( toQueryableCollectionConversion As SymbolInfo, asClauseConversion As SymbolInfo, selectMany As SymbolInfo ) Me.ToQueryableCollectionConversion = toQueryableCollectionConversion Me.AsClauseConversion = asClauseConversion Me.SelectMany = selectMany End Sub End Structure Public Structure AggregateClauseSymbolInfo ''' <summary> ''' The first of the two optional Select methods associated with <see cref="AggregateClauseSyntax"/>. ''' </summary> Public ReadOnly Property Select1 As SymbolInfo ''' <summary> ''' The second of the two optional Select methods associated with <see cref="AggregateClauseSyntax"/>. ''' </summary> Public ReadOnly Property Select2 As SymbolInfo Friend Sub New(select1 As SymbolInfo) Me.Select1 = select1 Me.Select2 = SymbolInfo.None End Sub Friend Sub New(select1 As SymbolInfo, select2 As SymbolInfo) Me.Select1 = select1 Me.Select2 = select2 End Sub End Structure Partial Friend Class VBSemanticModel ''' <summary> ''' Returns information about methods associated with CollectionRangeVariableSyntax. ''' </summary> Public Function GetCollectionRangeVariableSymbolInfo( variableSyntax As CollectionRangeVariableSyntax, Optional cancellationToken As CancellationToken = Nothing ) As CollectionRangeVariableSymbolInfo If variableSyntax Is Nothing Then Throw New ArgumentNullException(NameOf(variableSyntax)) End If If Not IsInTree(variableSyntax) Then Throw New ArgumentException(VBResources.VariableSyntaxNotWithinSyntaxTree) End If Return GetCollectionRangeVariableSymbolInfoWorker(variableSyntax, cancellationToken) End Function Friend MustOverride Function GetCollectionRangeVariableSymbolInfoWorker(node As CollectionRangeVariableSyntax, Optional cancellationToken As CancellationToken = Nothing) As CollectionRangeVariableSymbolInfo ''' <summary> ''' Returns information about methods associated with AggregateClauseSyntax. ''' </summary> Public Function GetAggregateClauseSymbolInfo( aggregateSyntax As AggregateClauseSyntax, Optional cancellationToken As CancellationToken = Nothing ) As AggregateClauseSymbolInfo If aggregateSyntax Is Nothing Then Throw New ArgumentNullException(NameOf(aggregateSyntax)) End If If Not IsInTree(aggregateSyntax) Then Throw New ArgumentException(VBResources.AggregateSyntaxNotWithinSyntaxTree) End If ' Stand-alone Aggregate does not use Select methods. If aggregateSyntax.Parent Is Nothing OrElse (aggregateSyntax.Parent.Kind = SyntaxKind.QueryExpression AndAlso DirectCast(aggregateSyntax.Parent, QueryExpressionSyntax).Clauses.FirstOrDefault Is aggregateSyntax) Then Return New AggregateClauseSymbolInfo(SymbolInfo.None) End If Return GetAggregateClauseSymbolInfoWorker(aggregateSyntax, cancellationToken) End Function Friend MustOverride Function GetAggregateClauseSymbolInfoWorker(node As AggregateClauseSyntax, Optional cancellationToken As CancellationToken = Nothing) As AggregateClauseSymbolInfo ''' <summary> ''' DistinctClauseSyntax - Returns Distinct method associated with DistinctClauseSyntax. ''' ''' WhereClauseSyntax - Returns Where method associated with WhereClauseSyntax. ''' ''' PartitionWhileClauseSyntax - Returns TakeWhile/SkipWhile method associated with PartitionWhileClauseSyntax. ''' ''' PartitionClauseSyntax - Returns Take/Skip method associated with PartitionClauseSyntax. ''' ''' GroupByClauseSyntax - Returns GroupBy method associated with GroupByClauseSyntax. ''' ''' JoinClauseSyntax - Returns Join/GroupJoin method associated with JoinClauseSyntax/GroupJoinClauseSyntax. ''' ''' SelectClauseSyntax - Returns Select method associated with SelectClauseSyntax, if needed. ''' ''' FromClauseSyntax - Returns Select method associated with FromClauseSyntax, which has only one ''' CollectionRangeVariableSyntax and is the only query clause within ''' QueryExpressionSyntax. NotNeeded SymbolInfo otherwise. ''' The method call is injected by the compiler to make sure that query is translated to at ''' least one method call. ''' ''' LetClauseSyntax - NotNeeded SymbolInfo. ''' ''' OrderByClauseSyntax - NotNeeded SymbolInfo. ''' ''' AggregateClauseSyntax - Empty SymbolInfo. GetAggregateClauseInfo should be used instead. ''' </summary> Public Shadows Function GetSymbolInfo( clauseSyntax As QueryClauseSyntax, Optional cancellationToken As CancellationToken = Nothing ) As SymbolInfo CheckSyntaxNode(clauseSyntax) If CanGetSemanticInfo(clauseSyntax) Then Select Case clauseSyntax.Kind Case SyntaxKind.LetClause, SyntaxKind.OrderByClause Return SymbolInfo.None Case SyntaxKind.AggregateClause Return SymbolInfo.None End Select Return GetQueryClauseSymbolInfo(clauseSyntax, cancellationToken) Else Return SymbolInfo.None End If End Function Friend MustOverride Function GetQueryClauseSymbolInfo(node As QueryClauseSyntax, Optional cancellationToken As CancellationToken = Nothing) As SymbolInfo ''' <summary> ''' Returns Select method associated with ExpressionRangeVariableSyntax within a LetClauseSyntax, if needed. ''' NotNeeded SymbolInfo otherwise. ''' </summary> Public Shadows Function GetSymbolInfo( variableSyntax As ExpressionRangeVariableSyntax, Optional cancellationToken As CancellationToken = Nothing ) As SymbolInfo CheckSyntaxNode(variableSyntax) If CanGetSemanticInfo(variableSyntax) Then If variableSyntax.Parent Is Nothing OrElse variableSyntax.Parent.Kind <> SyntaxKind.LetClause Then Return SymbolInfo.None End If Return GetLetClauseSymbolInfo(variableSyntax, cancellationToken) Else Return SymbolInfo.None End If End Function Friend MustOverride Function GetLetClauseSymbolInfo(node As ExpressionRangeVariableSyntax, Optional cancellationToken As CancellationToken = Nothing) As SymbolInfo ''' <summary> ''' Returns aggregate function associated with FunctionAggregationSyntax. ''' </summary> Public Shadows Function GetSymbolInfo( functionSyntax As FunctionAggregationSyntax, Optional cancellationToken As CancellationToken = Nothing ) As SymbolInfo CheckSyntaxNode(functionSyntax) If CanGetSemanticInfo(functionSyntax) Then If Not IsInTree(functionSyntax) Then Throw New ArgumentException(VBResources.FunctionSyntaxNotWithinSyntaxTree) End If Return GetSymbolInfo(DirectCast(functionSyntax, ExpressionSyntax), cancellationToken) Else Return SymbolInfo.None End If End Function ''' <summary> ''' Returns OrderBy/OrderByDescending/ThenBy/ThenByDescending method associated with OrderingSyntax. ''' </summary> Public Shadows Function GetSymbolInfo( orderingSyntax As OrderingSyntax, Optional cancellationToken As CancellationToken = Nothing ) As SymbolInfo CheckSyntaxNode(orderingSyntax) If CanGetSemanticInfo(orderingSyntax) Then Return GetOrderingSymbolInfo(orderingSyntax, cancellationToken) Else Return SymbolInfo.None End If End Function Friend MustOverride Function GetOrderingSymbolInfo(node As OrderingSyntax, Optional cancellationToken As CancellationToken = Nothing) As SymbolInfo End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic Public Structure CollectionRangeVariableSymbolInfo ''' <summary> ''' Optional AsQueryable/AsEnumerable/Cast(Of Object) method used ''' to "convert" <see cref="CollectionRangeVariableSyntax.Expression"/> to queryable ''' collection. ''' </summary> Public ReadOnly Property ToQueryableCollectionConversion As SymbolInfo ''' <summary> ''' Optional Select method to handle AsClause. ''' </summary> Public ReadOnly Property AsClauseConversion As SymbolInfo ''' <summary> ''' SelectMany method for <see cref="CollectionRangeVariableSyntax"/>, which is not the first ''' <see cref="CollectionRangeVariableSyntax"/> in a <see cref="QueryExpressionSyntax"/>, and is not the first ''' <see cref="CollectionRangeVariableSyntax"/> in <see cref="AggregateClauseSyntax"/>. ''' </summary> Public ReadOnly Property SelectMany As SymbolInfo Friend Shared ReadOnly None As New CollectionRangeVariableSymbolInfo(SymbolInfo.None, SymbolInfo.None, SymbolInfo.None) Friend Sub New( toQueryableCollectionConversion As SymbolInfo, asClauseConversion As SymbolInfo, selectMany As SymbolInfo ) Me.ToQueryableCollectionConversion = toQueryableCollectionConversion Me.AsClauseConversion = asClauseConversion Me.SelectMany = selectMany End Sub End Structure Public Structure AggregateClauseSymbolInfo ''' <summary> ''' The first of the two optional Select methods associated with <see cref="AggregateClauseSyntax"/>. ''' </summary> Public ReadOnly Property Select1 As SymbolInfo ''' <summary> ''' The second of the two optional Select methods associated with <see cref="AggregateClauseSyntax"/>. ''' </summary> Public ReadOnly Property Select2 As SymbolInfo Friend Sub New(select1 As SymbolInfo) Me.Select1 = select1 Me.Select2 = SymbolInfo.None End Sub Friend Sub New(select1 As SymbolInfo, select2 As SymbolInfo) Me.Select1 = select1 Me.Select2 = select2 End Sub End Structure Partial Friend Class VBSemanticModel ''' <summary> ''' Returns information about methods associated with CollectionRangeVariableSyntax. ''' </summary> Public Function GetCollectionRangeVariableSymbolInfo( variableSyntax As CollectionRangeVariableSyntax, Optional cancellationToken As CancellationToken = Nothing ) As CollectionRangeVariableSymbolInfo If variableSyntax Is Nothing Then Throw New ArgumentNullException(NameOf(variableSyntax)) End If If Not IsInTree(variableSyntax) Then Throw New ArgumentException(VBResources.VariableSyntaxNotWithinSyntaxTree) End If Return GetCollectionRangeVariableSymbolInfoWorker(variableSyntax, cancellationToken) End Function Friend MustOverride Function GetCollectionRangeVariableSymbolInfoWorker(node As CollectionRangeVariableSyntax, Optional cancellationToken As CancellationToken = Nothing) As CollectionRangeVariableSymbolInfo ''' <summary> ''' Returns information about methods associated with AggregateClauseSyntax. ''' </summary> Public Function GetAggregateClauseSymbolInfo( aggregateSyntax As AggregateClauseSyntax, Optional cancellationToken As CancellationToken = Nothing ) As AggregateClauseSymbolInfo If aggregateSyntax Is Nothing Then Throw New ArgumentNullException(NameOf(aggregateSyntax)) End If If Not IsInTree(aggregateSyntax) Then Throw New ArgumentException(VBResources.AggregateSyntaxNotWithinSyntaxTree) End If ' Stand-alone Aggregate does not use Select methods. If aggregateSyntax.Parent Is Nothing OrElse (aggregateSyntax.Parent.Kind = SyntaxKind.QueryExpression AndAlso DirectCast(aggregateSyntax.Parent, QueryExpressionSyntax).Clauses.FirstOrDefault Is aggregateSyntax) Then Return New AggregateClauseSymbolInfo(SymbolInfo.None) End If Return GetAggregateClauseSymbolInfoWorker(aggregateSyntax, cancellationToken) End Function Friend MustOverride Function GetAggregateClauseSymbolInfoWorker(node As AggregateClauseSyntax, Optional cancellationToken As CancellationToken = Nothing) As AggregateClauseSymbolInfo ''' <summary> ''' DistinctClauseSyntax - Returns Distinct method associated with DistinctClauseSyntax. ''' ''' WhereClauseSyntax - Returns Where method associated with WhereClauseSyntax. ''' ''' PartitionWhileClauseSyntax - Returns TakeWhile/SkipWhile method associated with PartitionWhileClauseSyntax. ''' ''' PartitionClauseSyntax - Returns Take/Skip method associated with PartitionClauseSyntax. ''' ''' GroupByClauseSyntax - Returns GroupBy method associated with GroupByClauseSyntax. ''' ''' JoinClauseSyntax - Returns Join/GroupJoin method associated with JoinClauseSyntax/GroupJoinClauseSyntax. ''' ''' SelectClauseSyntax - Returns Select method associated with SelectClauseSyntax, if needed. ''' ''' FromClauseSyntax - Returns Select method associated with FromClauseSyntax, which has only one ''' CollectionRangeVariableSyntax and is the only query clause within ''' QueryExpressionSyntax. NotNeeded SymbolInfo otherwise. ''' The method call is injected by the compiler to make sure that query is translated to at ''' least one method call. ''' ''' LetClauseSyntax - NotNeeded SymbolInfo. ''' ''' OrderByClauseSyntax - NotNeeded SymbolInfo. ''' ''' AggregateClauseSyntax - Empty SymbolInfo. GetAggregateClauseInfo should be used instead. ''' </summary> Public Shadows Function GetSymbolInfo( clauseSyntax As QueryClauseSyntax, Optional cancellationToken As CancellationToken = Nothing ) As SymbolInfo CheckSyntaxNode(clauseSyntax) If CanGetSemanticInfo(clauseSyntax) Then Select Case clauseSyntax.Kind Case SyntaxKind.LetClause, SyntaxKind.OrderByClause Return SymbolInfo.None Case SyntaxKind.AggregateClause Return SymbolInfo.None End Select Return GetQueryClauseSymbolInfo(clauseSyntax, cancellationToken) Else Return SymbolInfo.None End If End Function Friend MustOverride Function GetQueryClauseSymbolInfo(node As QueryClauseSyntax, Optional cancellationToken As CancellationToken = Nothing) As SymbolInfo ''' <summary> ''' Returns Select method associated with ExpressionRangeVariableSyntax within a LetClauseSyntax, if needed. ''' NotNeeded SymbolInfo otherwise. ''' </summary> Public Shadows Function GetSymbolInfo( variableSyntax As ExpressionRangeVariableSyntax, Optional cancellationToken As CancellationToken = Nothing ) As SymbolInfo CheckSyntaxNode(variableSyntax) If CanGetSemanticInfo(variableSyntax) Then If variableSyntax.Parent Is Nothing OrElse variableSyntax.Parent.Kind <> SyntaxKind.LetClause Then Return SymbolInfo.None End If Return GetLetClauseSymbolInfo(variableSyntax, cancellationToken) Else Return SymbolInfo.None End If End Function Friend MustOverride Function GetLetClauseSymbolInfo(node As ExpressionRangeVariableSyntax, Optional cancellationToken As CancellationToken = Nothing) As SymbolInfo ''' <summary> ''' Returns aggregate function associated with FunctionAggregationSyntax. ''' </summary> Public Shadows Function GetSymbolInfo( functionSyntax As FunctionAggregationSyntax, Optional cancellationToken As CancellationToken = Nothing ) As SymbolInfo CheckSyntaxNode(functionSyntax) If CanGetSemanticInfo(functionSyntax) Then If Not IsInTree(functionSyntax) Then Throw New ArgumentException(VBResources.FunctionSyntaxNotWithinSyntaxTree) End If Return GetSymbolInfo(DirectCast(functionSyntax, ExpressionSyntax), cancellationToken) Else Return SymbolInfo.None End If End Function ''' <summary> ''' Returns OrderBy/OrderByDescending/ThenBy/ThenByDescending method associated with OrderingSyntax. ''' </summary> Public Shadows Function GetSymbolInfo( orderingSyntax As OrderingSyntax, Optional cancellationToken As CancellationToken = Nothing ) As SymbolInfo CheckSyntaxNode(orderingSyntax) If CanGetSemanticInfo(orderingSyntax) Then Return GetOrderingSymbolInfo(orderingSyntax, cancellationToken) Else Return SymbolInfo.None End If End Function Friend MustOverride Function GetOrderingSymbolInfo(node As OrderingSyntax, Optional cancellationToken As CancellationToken = Nothing) As SymbolInfo End Class End Namespace
-1
dotnet/roslyn
56,419
Fix partial method doc comments
Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
RikkiGibson
"2021-09-15T20:47:39Z"
"2021-09-21T23:49:10Z"
0f60b3e9446f5d0fc14a570998c81a5d6c40cc23
8cda7462843d43d9b72039eede2f4cb43126cac2
Fix partial method doc comments. Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
./src/Compilers/CSharp/Portable/Compiler/DocumentationCommentCompiler.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Globalization; using System.IO; using System.Reflection; using System.Resources; using System.Text; using System.Threading; using System.Xml; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// Traverses the symbol table processing XML documentation comments and optionally writing them to /// a provided stream. /// </summary> internal partial class DocumentationCommentCompiler : CSharpSymbolVisitor { private readonly string _assemblyName; private readonly CSharpCompilation _compilation; private readonly TextWriter _writer; //never write directly - always use a helper private readonly SyntaxTree _filterTree; //if not null, limit analysis to types residing in this tree private readonly TextSpan? _filterSpanWithinTree; //if filterTree and filterSpanWithinTree is not null, limit analysis to types residing within this span in the filterTree. private readonly bool _processIncludes; private readonly bool _isForSingleSymbol; //minor differences in behavior between batch case and API case. private readonly BindingDiagnosticBag _diagnostics; private readonly CancellationToken _cancellationToken; private SyntaxNodeLocationComparer _lazyComparer; private DocumentationCommentIncludeCache _includedFileCache; private int _indentDepth; private Stack<TemporaryStringBuilder> _temporaryStringBuilders; private DocumentationCommentCompiler( string assemblyName, CSharpCompilation compilation, TextWriter writer, SyntaxTree filterTree, TextSpan? filterSpanWithinTree, bool processIncludes, bool isForSingleSymbol, BindingDiagnosticBag diagnostics, CancellationToken cancellationToken) { _assemblyName = assemblyName; _compilation = compilation; _writer = writer; _filterTree = filterTree; _filterSpanWithinTree = filterSpanWithinTree; _processIncludes = processIncludes; _isForSingleSymbol = isForSingleSymbol; _diagnostics = diagnostics; _cancellationToken = cancellationToken; } /// <summary> /// Traverses the symbol table processing XML documentation comments and optionally writing them to /// a provided stream. /// </summary> /// <param name="compilation">Compilation that owns the symbol table.</param> /// <param name="assemblyName">Assembly name override, if specified. Otherwise the <see cref="ISymbol.Name"/> of the source assembly is used.</param> /// <param name="xmlDocStream">Stream to which XML will be written, if specified.</param> /// <param name="diagnostics">Will be supplemented with documentation comment diagnostics.</param> /// <param name="cancellationToken">To stop traversing the symbol table early.</param> /// <param name="filterTree">Only report diagnostics from this syntax tree, if non-null.</param> /// <param name="filterSpanWithinTree">If <paramref name="filterTree"/> and filterSpanWithinTree is non-null, report diagnostics within this span in the <paramref name="filterTree"/>.</param> #nullable enable public static void WriteDocumentationCommentXml(CSharpCompilation compilation, string? assemblyName, Stream? xmlDocStream, BindingDiagnosticBag diagnostics, CancellationToken cancellationToken, SyntaxTree? filterTree = null, TextSpan? filterSpanWithinTree = null) #nullable disable { StreamWriter writer = null; if (xmlDocStream != null && xmlDocStream.CanWrite) { writer = new StreamWriter( stream: xmlDocStream, encoding: new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: false), bufferSize: 0x400, // Default. leaveOpen: true); // Don't close caller's stream. } try { using (writer) { var compiler = new DocumentationCommentCompiler(assemblyName ?? compilation.SourceAssembly.Name, compilation, writer, filterTree, filterSpanWithinTree, processIncludes: true, isForSingleSymbol: false, diagnostics: diagnostics, cancellationToken: cancellationToken); compiler.Visit(compilation.SourceAssembly.GlobalNamespace); Debug.Assert(compiler._indentDepth == 0); writer?.Flush(); } } catch (Exception e) { diagnostics.Add(ErrorCode.ERR_DocFileGen, Location.None, e.Message); } if (diagnostics.DiagnosticBag is DiagnosticBag diagnosticBag) { if (filterTree != null) { // Will respect the DocumentationMode. UnprocessedDocumentationCommentFinder.ReportUnprocessed(filterTree, filterSpanWithinTree, diagnosticBag, cancellationToken); } else { foreach (SyntaxTree tree in compilation.SyntaxTrees) { // Will respect the DocumentationMode. UnprocessedDocumentationCommentFinder.ReportUnprocessed(tree, null, diagnosticBag, cancellationToken); } } } } /// <summary> /// Gets the XML that would be written to the documentation comment file for this assembly. /// </summary> /// <param name="symbol">The symbol for which to retrieve documentation comments.</param> /// <param name="processIncludes">True to treat includes as semantically meaningful (pull in contents from other files and bind crefs, etc).</param> /// <param name="cancellationToken">To stop traversing the symbol table early.</param> internal static string GetDocumentationCommentXml(Symbol symbol, bool processIncludes, CancellationToken cancellationToken) { Debug.Assert( symbol.Kind == SymbolKind.Event || symbol.Kind == SymbolKind.Field || symbol.Kind == SymbolKind.Method || symbol.Kind == SymbolKind.NamedType || symbol.Kind == SymbolKind.Property); CSharpCompilation compilation = symbol.DeclaringCompilation; Debug.Assert(compilation != null); PooledStringBuilder pooled = PooledStringBuilder.GetInstance(); StringWriter writer = new StringWriter(pooled.Builder); var compiler = new DocumentationCommentCompiler( assemblyName: null, compilation: compilation, writer: writer, filterTree: null, filterSpanWithinTree: null, processIncludes: processIncludes, isForSingleSymbol: true, diagnostics: BindingDiagnosticBag.Discarded, cancellationToken: cancellationToken); compiler.Visit(symbol); Debug.Assert(compiler._indentDepth == 0); writer.Dispose(); return pooled.ToStringAndFree(); } /// <summary> /// Write header, descend into members, and write footer. /// </summary> public override void VisitNamespace(NamespaceSymbol symbol) { _cancellationToken.ThrowIfCancellationRequested(); if (symbol.IsGlobalNamespace) { Debug.Assert(_assemblyName != null); WriteLine("<?xml version=\"1.0\"?>"); WriteLine("<doc>"); Indent(); if (!_compilation.Options.OutputKind.IsNetModule()) { WriteLine("<assembly>"); Indent(); WriteLine("<name>{0}</name>", _assemblyName); Unindent(); WriteLine("</assembly>"); } WriteLine("<members>"); Indent(); } Debug.Assert(!_isForSingleSymbol); foreach (var s in symbol.GetMembers()) { _cancellationToken.ThrowIfCancellationRequested(); s.Accept(this); } if (symbol.IsGlobalNamespace) { Unindent(); WriteLine("</members>"); Unindent(); WriteLine("</doc>"); } } /// <summary> /// Write own documentation comments and then descend into members. /// </summary> public override void VisitNamedType(NamedTypeSymbol symbol) { _cancellationToken.ThrowIfCancellationRequested(); if (_filterTree != null && !symbol.IsDefinedInSourceTree(_filterTree, _filterSpanWithinTree)) { return; } DefaultVisit(symbol); if (!_isForSingleSymbol) { foreach (Symbol member in symbol.GetMembers()) { _cancellationToken.ThrowIfCancellationRequested(); member.Accept(this); } } } /// <summary> /// Compile documentation comments on the symbol and write them to the stream if one is provided. /// </summary> public override void DefaultVisit(Symbol symbol) { _cancellationToken.ThrowIfCancellationRequested(); if (ShouldSkip(symbol)) { return; } if (_filterTree != null && !symbol.IsDefinedInSourceTree(_filterTree, _filterSpanWithinTree)) { return; } bool isPartialMethodDefinitionPart = symbol.IsPartialDefinition(); // CONSIDER: ignore this if isForSingleSymbol? if (isPartialMethodDefinitionPart) { MethodSymbol implementationPart = ((MethodSymbol)symbol).PartialImplementationPart; if ((object)implementationPart != null) { Visit(implementationPart); } } DocumentationMode maxDocumentationMode; ImmutableArray<DocumentationCommentTriviaSyntax> docCommentNodes; if (!TryGetDocumentationCommentNodes(symbol, out maxDocumentationMode, out docCommentNodes)) { // If the XML in any of the doc comments is invalid, skip all further processing (for this symbol) and // just write a comment saying that info was lost for this symbol. string message = ErrorFacts.GetMessage(MessageID.IDS_XMLIGNORED, CultureInfo.CurrentUICulture); WriteLine(string.Format(CultureInfo.CurrentUICulture, message, symbol.GetDocumentationCommentId())); return; } // If there are no doc comments, then no further work is required (other than to report a diagnostic if one is required). if (docCommentNodes.IsEmpty) { if (maxDocumentationMode >= DocumentationMode.Diagnose && RequiresDocumentationComment(symbol)) { // Report the error at a location in the tree that was parsing doc comments. Location location = GetLocationInTreeReportingDocumentationCommentDiagnostics(symbol); if (location != null) { _diagnostics.Add(ErrorCode.WRN_MissingXMLComment, location, symbol); } } return; } _cancellationToken.ThrowIfCancellationRequested(); bool reportParameterOrTypeParameterDiagnostics = GetLocationInTreeReportingDocumentationCommentDiagnostics(symbol) != null; string withUnprocessedIncludes; bool haveParseError; HashSet<TypeParameterSymbol> documentedTypeParameters; HashSet<ParameterSymbol> documentedParameters; ImmutableArray<CSharpSyntaxNode> includeElementNodes; if (!TryProcessDocumentationCommentTriviaNodes( symbol, isPartialMethodDefinitionPart, docCommentNodes, reportParameterOrTypeParameterDiagnostics, out withUnprocessedIncludes, out haveParseError, out documentedTypeParameters, out documentedParameters, out includeElementNodes)) { return; } if (haveParseError) { // If the XML in any of the doc comments is invalid, skip all further processing (for this symbol) and // just write a comment saying that info was lost for this symbol. string message = ErrorFacts.GetMessage(MessageID.IDS_XMLIGNORED, CultureInfo.CurrentUICulture); WriteLine(string.Format(CultureInfo.CurrentUICulture, message, symbol.GetDocumentationCommentId())); return; } // If there are no include elements, then there's nothing to expand. if (!includeElementNodes.IsDefaultOrEmpty) { _cancellationToken.ThrowIfCancellationRequested(); // NOTE: we are expanding include elements AFTER formatting the comment, since the included text is pure // XML, not XML mixed with documentation comment trivia (e.g. ///). If we expanded them before formatting, // the formatting engine would have trouble determining what prefix to remove from each line. TextWriter expanderWriter = isPartialMethodDefinitionPart ? null : _writer; // Don't actually write partial method definition parts. IncludeElementExpander.ProcessIncludes(withUnprocessedIncludes, symbol, includeElementNodes, _compilation, ref documentedParameters, ref documentedTypeParameters, ref _includedFileCache, expanderWriter, _diagnostics, _cancellationToken); } else if (_writer != null && !isPartialMethodDefinitionPart) { // CONSIDER: The output would look a little different if we ran the XDocument through an XmlWriter. In particular, // formatting inside tags (e.g. <__tag___attr__=__"value"__>) would be normalized. Whitespace in elements would // (or should) not be affected. If we decide that this difference matters, we can run the XDocument through an XmlWriter. // Otherwise, just writing out the string saves a bunch of processing and does a better job of preserving whitespace. Write(withUnprocessedIncludes); } if (reportParameterOrTypeParameterDiagnostics) { _cancellationToken.ThrowIfCancellationRequested(); if (documentedParameters != null) { foreach (ParameterSymbol parameter in GetParameters(symbol)) { if (!documentedParameters.Contains(parameter)) { Location location = parameter.Locations[0]; Debug.Assert(location.SourceTree.ReportDocumentationCommentDiagnostics()); //Should be the same tree as for the symbol. // NOTE: parameter name, since the parameter would be displayed as just its type. _diagnostics.Add(ErrorCode.WRN_MissingParamTag, location, parameter.Name, symbol); } } } if (documentedTypeParameters != null) { foreach (TypeParameterSymbol typeParameter in GetTypeParameters(symbol)) { if (!documentedTypeParameters.Contains(typeParameter)) { Location location = typeParameter.Locations[0]; Debug.Assert(location.SourceTree.ReportDocumentationCommentDiagnostics()); //Should be the same tree as for the symbol. _diagnostics.Add(ErrorCode.WRN_MissingTypeParamTag, location, typeParameter, symbol); } } } } } private static bool ShouldSkip(Symbol symbol) { return symbol.IsImplicitlyDeclared || symbol.IsAccessor() || symbol is SynthesizedSimpleProgramEntryPointSymbol || symbol is SynthesizedRecordPropertySymbol; } /// <summary> /// Loop over the DocumentationCommentTriviaSyntaxes. Gather /// 1) concatenated XML, as a string; /// 2) whether or not the XML is valid; /// 3) set of type parameters covered by &lt;typeparam&gt; elements; /// 4) set of parameters covered by &lt;param&gt; elements; /// 5) list of &lt;include&gt; elements, as SyntaxNodes. /// </summary> /// <returns>True, if at least one documentation comment was processed; false, otherwise.</returns> /// <remarks>This was factored out for clarity, not because it's reusable.</remarks> private bool TryProcessDocumentationCommentTriviaNodes( Symbol symbol, bool isPartialMethodDefinitionPart, ImmutableArray<DocumentationCommentTriviaSyntax> docCommentNodes, bool reportParameterOrTypeParameterDiagnostics, out string withUnprocessedIncludes, out bool haveParseError, out HashSet<TypeParameterSymbol> documentedTypeParameters, out HashSet<ParameterSymbol> documentedParameters, out ImmutableArray<CSharpSyntaxNode> includeElementNodes) { Debug.Assert(!docCommentNodes.IsDefaultOrEmpty); bool processedDocComment = false; // Even if there are DocumentationCommentTriviaSyntax, we may not need to process any of them. ArrayBuilder<CSharpSyntaxNode> includeElementNodesBuilder = null; documentedParameters = null; documentedTypeParameters = null; // Saw an XmlException while parsing one of the DocumentationCommentTriviaSyntax nodes. haveParseError = false; // We're doing substitution and formatting per-trivia, rather than per-symbol, // because a single symbol can have both single-line and multi-line style // doc comments. foreach (DocumentationCommentTriviaSyntax trivia in docCommentNodes) { _cancellationToken.ThrowIfCancellationRequested(); bool reportDiagnosticsForCurrentTrivia = trivia.SyntaxTree.ReportDocumentationCommentDiagnostics(); if (!processedDocComment) { // Since we have to throw away all the parts if any part is bad, we need to write to an intermediate temp. BeginTemporaryString(); if (_processIncludes) { includeElementNodesBuilder = ArrayBuilder<CSharpSyntaxNode>.GetInstance(); } // We DO want to write out partial method definition parts if we're processing includes // because we need to have XML to process. if (!isPartialMethodDefinitionPart || _processIncludes) { WriteLine("<member name=\"{0}\">", symbol.GetDocumentationCommentId()); Indent(); } processedDocComment = true; } // Will respect the DocumentationMode. string substitutedText = DocumentationCommentWalker.GetSubstitutedText(_compilation, _diagnostics, symbol, trivia, includeElementNodesBuilder, ref documentedParameters, ref documentedTypeParameters); string formattedXml = FormatComment(substitutedText); // It would be preferable to just parse the concatenated XML at the end of the loop (we wouldn't have // to wrap it in a root element and we wouldn't have to reparse in the IncludeElementExpander), but // then we wouldn't know whether or where to report a diagnostic. XmlException e = XmlDocumentationCommentTextReader.ParseAndGetException(formattedXml); if (e != null) { haveParseError = true; if (reportDiagnosticsForCurrentTrivia) { Location location = new SourceLocation(trivia.SyntaxTree, new TextSpan(trivia.SpanStart, 0)); _diagnostics.Add(ErrorCode.WRN_XMLParseError, location, GetDescription(e)); } } // For partial methods, all parts are validated, but only the implementation part is written to the XML stream. if (!isPartialMethodDefinitionPart || _processIncludes) { // This string already has indentation and line breaks, so don't call WriteLine - just write the text directly. Write(formattedXml); } } if (!processedDocComment) { withUnprocessedIncludes = null; includeElementNodes = default(ImmutableArray<CSharpSyntaxNode>); return false; } if (!isPartialMethodDefinitionPart || _processIncludes) { Unindent(); WriteLine("</member>"); } // Free the temp. withUnprocessedIncludes = GetAndEndTemporaryString(); // Free the builder, even if there was an error. includeElementNodes = _processIncludes ? includeElementNodesBuilder.ToImmutableAndFree() : default(ImmutableArray<CSharpSyntaxNode>); return true; } private static Location GetLocationInTreeReportingDocumentationCommentDiagnostics(Symbol symbol) { foreach (Location location in symbol.Locations) { if (location.SourceTree.ReportDocumentationCommentDiagnostics()) { return location; } } return null; } /// <remarks> /// Similar to SymbolExtensions.GetParameters, but returns empty for unsupported symbols /// and handles delegates. /// </remarks> private static ImmutableArray<ParameterSymbol> GetParameters(Symbol symbol) { switch (symbol.Kind) { case SymbolKind.NamedType: MethodSymbol delegateInvoke = ((NamedTypeSymbol)symbol).DelegateInvokeMethod; if ((object)delegateInvoke != null) { return delegateInvoke.Parameters; } break; case SymbolKind.Method: case SymbolKind.Property: case SymbolKind.Event: return symbol.GetParameters(); } return ImmutableArray<ParameterSymbol>.Empty; } /// <remarks> /// Similar to SymbolExtensions.GetMemberTypeParameters, but returns empty for unsupported symbols. /// </remarks> private static ImmutableArray<TypeParameterSymbol> GetTypeParameters(Symbol symbol) { switch (symbol.Kind) { case SymbolKind.Method: case SymbolKind.NamedType: case SymbolKind.ErrorType: return symbol.GetMemberTypeParameters(); } return ImmutableArray<TypeParameterSymbol>.Empty; } /// <summary> /// A symbol requires a documentation comment if it was explicitly declared and /// will be visible outside the current assembly (ignoring InternalsVisibleTo). /// Exception: accessors do not require doc comments. /// </summary> private static bool RequiresDocumentationComment(Symbol symbol) { Debug.Assert((object)symbol != null); if (ShouldSkip(symbol)) { return false; } while ((object)symbol != null) { switch (symbol.DeclaredAccessibility) { case Accessibility.Public: case Accessibility.Protected: case Accessibility.ProtectedOrInternal: symbol = symbol.ContainingType; break; default: return false; } } return true; } /// <summary> /// Get all of the DocumentationCommentTriviaSyntax associated with any declaring syntax of the /// given symbol (except for partial methods, which only consider the part with the body). /// </summary> /// <returns>True if the nodes are all valid XML.</returns> private bool TryGetDocumentationCommentNodes(Symbol symbol, out DocumentationMode maxDocumentationMode, out ImmutableArray<DocumentationCommentTriviaSyntax> nodes) { maxDocumentationMode = DocumentationMode.None; nodes = default(ImmutableArray<DocumentationCommentTriviaSyntax>); ArrayBuilder<DocumentationCommentTriviaSyntax> builder = null; var diagnosticBag = _diagnostics.DiagnosticBag ?? DiagnosticBag.GetInstance(); foreach (SyntaxReference reference in symbol.DeclaringSyntaxReferences) { DocumentationMode currDocumentationMode = reference.SyntaxTree.Options.DocumentationMode; maxDocumentationMode = currDocumentationMode > maxDocumentationMode ? currDocumentationMode : maxDocumentationMode; ImmutableArray<DocumentationCommentTriviaSyntax> triviaList = SourceDocumentationCommentUtils.GetDocumentationCommentTriviaFromSyntaxNode((CSharpSyntaxNode)reference.GetSyntax(), diagnosticBag); foreach (var trivia in triviaList) { if (ContainsXmlParseDiagnostic(trivia)) { if (builder != null) { builder.Free(); } return false; } if (builder == null) { builder = ArrayBuilder<DocumentationCommentTriviaSyntax>.GetInstance(); } builder.Add(trivia); } } if (diagnosticBag != _diagnostics.DiagnosticBag) { diagnosticBag.Free(); } if (builder == null) { nodes = ImmutableArray<DocumentationCommentTriviaSyntax>.Empty; } else { builder.Sort(Comparer); nodes = builder.ToImmutableAndFree(); } return true; } private static bool ContainsXmlParseDiagnostic(DocumentationCommentTriviaSyntax node) { if (!node.ContainsDiagnostics) { return false; } foreach (Diagnostic diag in node.GetDiagnostics()) { if ((ErrorCode)diag.Code == ErrorCode.WRN_XMLParseError) { return true; } } return false; } private static readonly string[] s_newLineSequences = new[] { "\r\n", "\r", "\n" }; /// <summary> /// Given the full text of a documentation comment, strip off the comment punctuation (///, /**, etc) /// and add appropriate indentations. /// </summary> private string FormatComment(string substitutedText) { BeginTemporaryString(); if (TrimmedStringStartsWith(substitutedText, "///")) { //Debug.Assert(lines.Take(numLines).All(line => TrimmedStringStartsWith(line, "///"))); WriteFormattedSingleLineComment(substitutedText); } else { string[] lines = substitutedText.Split(s_newLineSequences, StringSplitOptions.None); int numLines = lines.Length; Debug.Assert(numLines > 0); if (string.IsNullOrEmpty(lines[numLines - 1])) { numLines--; Debug.Assert(numLines > 0); } Debug.Assert(TrimmedStringStartsWith(lines[0], "/**")); WriteFormattedMultiLineComment(lines, numLines); } return GetAndEndTemporaryString(); } /// <summary> /// Given a string, find the index of the first non-whitespace char. /// </summary> /// <param name="str">The string to search</param> /// <returns>The index of the first non-whitespace char in the string</returns> private static int GetIndexOfFirstNonWhitespaceChar(string str) { return GetIndexOfFirstNonWhitespaceChar(str, 0, str.Length); } /// <summary> /// Find the first non-whitespace character in a given substring. /// </summary> /// <param name="str">The string to search</param> /// <param name="start">The start index</param> /// <param name="end">The last index (non-inclusive)</param> /// <returns>The index of the first non-whitespace char after index start in the string up to, but not including the end index</returns> private static int GetIndexOfFirstNonWhitespaceChar(string str, int start, int end) { Debug.Assert(start >= 0); Debug.Assert(start <= str.Length); Debug.Assert(end >= 0); Debug.Assert(end <= str.Length); Debug.Assert(end >= start); for (; start < end; start++) { if (!SyntaxFacts.IsWhitespace(str[start])) { break; } } return start; } /// <summary> /// Determine if the given string starts with the given prefix if whitespace /// is first trimmed from the beginning. /// </summary> /// <param name="str">The string to search</param> /// <param name="prefix">The prefix</param> /// <returns>true if str.TrimStart().StartsWith(prefix)</returns> private static bool TrimmedStringStartsWith(string str, string prefix) { // PERF: Avoid calling string.Trim() because that allocates a new substring int start = GetIndexOfFirstNonWhitespaceChar(str); int len = str.Length - start; if (len < prefix.Length) { return false; } for (int i = 0; i < prefix.Length; i++) { if (prefix[i] != str[i + start]) { return false; } } return true; } /// <summary> /// Given a string which may contain newline sequences, get the index of the first newline /// sequence beginning at the given starting index. /// </summary> /// <param name="str">The string to split.</param> /// <param name="start">The starting index within the string.</param> /// <param name="newLineLength">The length of the newline sequence discovered. 0 if the end of the string was reached, otherwise either 1 or 2 chars</param> /// <returns>The index of the start of the first newline sequence following the start index</returns> private static int IndexOfNewLine(string str, int start, out int newLineLength) { for (; start < str.Length; start++) { switch (str[start]) { case '\r': if ((start + 1) < str.Length && str[start + 1] == '\n') { newLineLength = 2; } else { newLineLength = 1; } return start; case '\n': newLineLength = 1; return start; } } newLineLength = 0; return start; } /// <summary> /// Given the full text of a single-line style documentation comment, for each line, strip off /// the comment punctuation (///) and add appropriate indentations. /// </summary> private void WriteFormattedSingleLineComment(string text) { // PERF: Avoid allocating intermediate strings e.g. via Split, Trim or Substring bool skipSpace = true; for (int start = 0; start < text.Length;) { int newLineLength; int end = IndexOfNewLine(text, start, out newLineLength); int trimStart = GetIndexOfFirstNonWhitespaceChar(text, start, end); int trimmedLength = end - trimStart; if (trimmedLength < 4 || !SyntaxFacts.IsWhitespace(text[trimStart + 3])) { skipSpace = false; break; } start = end + newLineLength; } int substringStart = skipSpace ? 4 : 3; for (int start = 0; start < text.Length;) { int newLineLength; int end = IndexOfNewLine(text, start, out newLineLength); int trimStart = GetIndexOfFirstNonWhitespaceChar(text, start, end) + substringStart; WriteSubStringLine(text, trimStart, end - trimStart); start = end + newLineLength; } } /// <summary> /// Given the full text of a multi-line style documentation comment, broken into lines, strip off /// the comment punctuation (/**, */, etc) and add appropriate indentations. /// </summary> private void WriteFormattedMultiLineComment(string[] lines, int numLines) { bool skipFirstLine = lines[0].Trim() == "/**"; bool skipLastLine = lines[numLines - 1].Trim() == "*/"; if (skipLastLine) { numLines--; Debug.Assert(numLines > 0); } int skipLength = 0; if (numLines > 1) { string pattern = FindMultiLineCommentPattern(lines[1]); if (pattern != null) { bool allMatch = true; for (int i = 2; i < numLines; i++) { string currentLinePattern = LongestCommonPrefix(pattern, lines[i]); if (string.IsNullOrWhiteSpace(currentLinePattern)) { allMatch = false; break; } Debug.Assert(pattern.StartsWith(currentLinePattern, StringComparison.Ordinal)); pattern = currentLinePattern; } if (allMatch) { skipLength = pattern.Length; } } } if (!skipFirstLine) { string trimmed = lines[0].TrimStart(null); if (!skipLastLine && numLines == 1) { trimmed = TrimEndOfMultiLineComment(trimmed); } WriteLine(trimmed.Substring(SyntaxFacts.IsWhitespace(trimmed[3]) ? 4 : 3)); } for (int i = 1; i < numLines; i++) { string trimmed = lines[i].Substring(skipLength); // If we've already skipped the last line, this can't happen. if (!skipLastLine && i == numLines - 1) { trimmed = TrimEndOfMultiLineComment(trimmed); } WriteLine(trimmed); } } /// <summary> /// Remove "*/" and any following text, if it is present. /// </summary> private static string TrimEndOfMultiLineComment(string trimmed) { int index = trimmed.IndexOf("*/", StringComparison.Ordinal); if (index >= 0) { trimmed = trimmed.Substring(0, index); } return trimmed; } /// <summary> /// Return the longest prefix matching [whitespace]*[*][whitespace]*. /// </summary> private static string FindMultiLineCommentPattern(string line) { int length = 0; bool seenStar = false; foreach (char ch in line) { if (SyntaxFacts.IsWhitespace(ch)) { length++; } else if (!seenStar && ch == '*') { length++; seenStar = true; } else { break; } } return seenStar ? line.Substring(0, length) : null; } /// <summary> /// Return the longest common prefix of two strings /// </summary> private static string LongestCommonPrefix(string str1, string str2) { int pos = 0; int minLength = Math.Min(str1.Length, str2.Length); for (; pos < minLength && str1[pos] == str2[pos]; pos++) { } return str1.Substring(0, pos); } /// <summary> /// Bind a CrefSyntax and unwrap the result if it's an alias. /// </summary> /// <remarks> /// Does not respect DocumentationMode, so use a temporary bag if diagnostics are not desired. /// </remarks> private static string GetDocumentationCommentId(CrefSyntax crefSyntax, Binder binder, BindingDiagnosticBag diagnostics) { if (crefSyntax.ContainsDiagnostics) { return ToBadCrefString(crefSyntax); } Symbol ambiguityWinner; ImmutableArray<Symbol> symbols = binder.BindCref(crefSyntax, out ambiguityWinner, diagnostics); Symbol symbol; switch (symbols.Length) { case 0: return ToBadCrefString(crefSyntax); case 1: symbol = symbols[0]; break; default: symbol = ambiguityWinner; Debug.Assert((object)symbol != null); break; } if (symbol.Kind == SymbolKind.Alias) { symbol = ((AliasSymbol)symbol).GetAliasTarget(basesBeingResolved: null); } if (symbol is NamespaceSymbol ns) { Debug.Assert(!ns.IsGlobalNamespace); diagnostics.AddAssembliesUsedByNamespaceReference(ns); } else { diagnostics.AddDependencies(symbol as TypeSymbol ?? symbol.ContainingType); } return symbol.OriginalDefinition.GetDocumentationCommentId(); } /// <summary> /// Given a cref syntax that cannot be resolved, get the string that will be written to /// the documentation file in place of a documentation comment ID. /// </summary> private static string ToBadCrefString(CrefSyntax cref) { using (StringWriter tmp = new StringWriter(CultureInfo.InvariantCulture)) { cref.WriteTo(tmp); return "!:" + tmp.ToString().Replace("{", "&lt;").Replace("}", "&gt;"); } } /// <summary> /// Bind an XmlNameAttributeSyntax and update the sets of documented parameters and type parameters. /// </summary> /// <remarks> /// Does not respect DocumentationMode, so do not call unless diagnostics are desired. /// </remarks> private static void BindName( XmlNameAttributeSyntax syntax, Binder binder, Symbol memberSymbol, ref HashSet<ParameterSymbol> documentedParameters, ref HashSet<TypeParameterSymbol> documentedTypeParameters, BindingDiagnosticBag diagnostics) { XmlNameAttributeElementKind elementKind = syntax.GetElementKind(); // NOTE: We want the corresponding hash set to be non-null if we saw // any <param>/<typeparam> elements, even if they didn't bind (for // WRN_MissingParamTag and WRN_MissingTypeParamTag). if (elementKind == XmlNameAttributeElementKind.Parameter) { if (documentedParameters == null) { documentedParameters = new HashSet<ParameterSymbol>(); } } else if (elementKind == XmlNameAttributeElementKind.TypeParameter) { if (documentedTypeParameters == null) { documentedTypeParameters = new HashSet<TypeParameterSymbol>(); } } IdentifierNameSyntax identifier = syntax.Identifier; if (identifier.ContainsDiagnostics) { return; } CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = binder.GetNewCompoundUseSiteInfo(diagnostics); ImmutableArray<Symbol> referencedSymbols = binder.BindXmlNameAttribute(syntax, ref useSiteInfo); diagnostics.Add(syntax, useSiteInfo); if (referencedSymbols.IsEmpty) { switch (elementKind) { case XmlNameAttributeElementKind.Parameter: diagnostics.Add(ErrorCode.WRN_UnmatchedParamTag, identifier.Location, identifier); break; case XmlNameAttributeElementKind.ParameterReference: diagnostics.Add(ErrorCode.WRN_UnmatchedParamRefTag, identifier.Location, identifier, memberSymbol); break; case XmlNameAttributeElementKind.TypeParameter: diagnostics.Add(ErrorCode.WRN_UnmatchedTypeParamTag, identifier.Location, identifier); break; case XmlNameAttributeElementKind.TypeParameterReference: diagnostics.Add(ErrorCode.WRN_UnmatchedTypeParamRefTag, identifier.Location, identifier, memberSymbol); break; default: throw ExceptionUtilities.UnexpectedValue(elementKind); } } else { foreach (Symbol referencedSymbol in referencedSymbols) { if (elementKind == XmlNameAttributeElementKind.Parameter) { Debug.Assert(referencedSymbol.Kind == SymbolKind.Parameter); Debug.Assert(documentedParameters != null); // Restriction preserved from dev11: don't report this for the "value" parameter. // Here, we detect that case by checking the containing symbol - only "value" // parameters are contained by accessors, others are on the corresponding property/event. ParameterSymbol parameter = (ParameterSymbol)referencedSymbol; if (!parameter.ContainingSymbol.IsAccessor() && !documentedParameters.Add(parameter)) { diagnostics.Add(ErrorCode.WRN_DuplicateParamTag, syntax.Location, identifier); } } else if (elementKind == XmlNameAttributeElementKind.TypeParameter) { Debug.Assert(referencedSymbol.Kind == SymbolKind.TypeParameter); Debug.Assert(documentedTypeParameters != null); if (!documentedTypeParameters.Add((TypeParameterSymbol)referencedSymbol)) { diagnostics.Add(ErrorCode.WRN_DuplicateTypeParamTag, syntax.Location, identifier); } } } } } private IComparer<CSharpSyntaxNode> Comparer { get { if (_lazyComparer == null) { _lazyComparer = new SyntaxNodeLocationComparer(_compilation); } return _lazyComparer; } } private void BeginTemporaryString() { if (_temporaryStringBuilders == null) { _temporaryStringBuilders = new Stack<TemporaryStringBuilder>(); } _temporaryStringBuilders.Push(new TemporaryStringBuilder(_indentDepth)); } private string GetAndEndTemporaryString() { TemporaryStringBuilder t = _temporaryStringBuilders.Pop(); Debug.Assert(_indentDepth == t.InitialIndentDepth, $"Temporary strings should be indent-neutral (was {t.InitialIndentDepth}, is {_indentDepth})"); _indentDepth = t.InitialIndentDepth; return t.Pooled.ToStringAndFree(); } private void Indent() { _indentDepth++; } private void Unindent() { _indentDepth--; Debug.Assert(_indentDepth >= 0); } private void Write(string indentedAndWrappedString) { if (_temporaryStringBuilders != null && _temporaryStringBuilders.Count > 0) { StringBuilder builder = _temporaryStringBuilders.Peek().Pooled.Builder; builder.Append(indentedAndWrappedString); } else if (_writer != null) { _writer.Write(indentedAndWrappedString); } } private void WriteLine(string message) { if (_temporaryStringBuilders?.Count > 0) { StringBuilder builder = _temporaryStringBuilders.Peek().Pooled.Builder; builder.Append(MakeIndent(_indentDepth)); builder.AppendLine(message); } else if (_writer != null) { _writer.Write(MakeIndent(_indentDepth)); _writer.WriteLine(message); } } private void WriteSubStringLine(string message, int start, int length) { if (_temporaryStringBuilders?.Count > 0) { StringBuilder builder = _temporaryStringBuilders.Peek().Pooled.Builder; builder.Append(MakeIndent(_indentDepth)); builder.Append(message, start, length); builder.AppendLine(); } else if (_writer != null) { _writer.Write(MakeIndent(_indentDepth)); for (int i = 0; i < length; i++) { _writer.Write(message[start + i]); } _writer.WriteLine(); } } private void WriteLine(string format, params object[] args) { WriteLine(string.Format(format, args)); } private static string MakeIndent(int depth) { Debug.Assert(depth >= 0); // Since we know a lot about the structure of the output, // we should be able to do this without constructing any // new string objects. switch (depth) { case 0: return ""; case 1: return " "; case 2: return " "; case 3: return " "; default: Debug.Assert(false, "Didn't expect nesting to reach depth " + depth); return new string(' ', depth * 4); } } /// <remarks> /// WORKAROUND: /// We're taking a dependency on the location and structure of a framework assembly resource. This is not a robust solution. /// /// Possible alternatives: /// 1) Polish our XML parser until it matches MSXML. We don't want to reinvent the wheel. /// 2) Build a map that lets us go from XML string positions back to source positions. /// This is what the native compiler did, and it was a lot of work. We'd also still need to modify the message. /// 3) Do not report a diagnostic. This is very unhelpful. /// 4) Report a vague diagnostic (i.e. there's a problem somewhere in this doc comment). This is relatively unhelpful. /// 5) Always report the message in English, so that we can pull it apart without needing to consume resource files. /// This engenders a lot of ill will. /// 6) Report the exception message without modification and (optionally) include the text with respect to which the /// position is specified. This would not look sufficiently polished. /// </remarks> private static string GetDescription(XmlException e) { string message = e.Message; try { ResourceManager manager = new ResourceManager("System.Xml", typeof(XmlException).GetTypeInfo().Assembly); string locationTemplate = manager.GetString("Xml_MessageWithErrorPosition"); string locationString = string.Format(locationTemplate, "", e.LineNumber, e.LinePosition); // first arg is where the problem description goes int position = message.IndexOf(locationString, StringComparison.Ordinal); // Expect exact match return position < 0 ? message : message.Remove(position, locationString.Length); } catch { Debug.Assert(false, "If we hit this, then we might need to think about a different workaround " + "for stripping the location out the message."); // If anything at all goes wrong, just return the message verbatim. It probably // contains an invalid position, but it's better than nothing. return message; } } private struct TemporaryStringBuilder { public readonly PooledStringBuilder Pooled; public readonly int InitialIndentDepth; public TemporaryStringBuilder(int indentDepth) { this.InitialIndentDepth = indentDepth; this.Pooled = PooledStringBuilder.GetInstance(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Globalization; using System.IO; using System.Reflection; using System.Resources; using System.Text; using System.Threading; using System.Xml; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// Traverses the symbol table processing XML documentation comments and optionally writing them to /// a provided stream. /// </summary> internal partial class DocumentationCommentCompiler : CSharpSymbolVisitor { private readonly string _assemblyName; private readonly CSharpCompilation _compilation; private readonly TextWriter _writer; //never write directly - always use a helper private readonly SyntaxTree _filterTree; //if not null, limit analysis to types residing in this tree private readonly TextSpan? _filterSpanWithinTree; //if filterTree and filterSpanWithinTree is not null, limit analysis to types residing within this span in the filterTree. private readonly bool _processIncludes; private readonly bool _isForSingleSymbol; //minor differences in behavior between batch case and API case. private readonly BindingDiagnosticBag _diagnostics; private readonly CancellationToken _cancellationToken; private SyntaxNodeLocationComparer _lazyComparer; private DocumentationCommentIncludeCache _includedFileCache; private int _indentDepth; private Stack<TemporaryStringBuilder> _temporaryStringBuilders; private DocumentationCommentCompiler( string assemblyName, CSharpCompilation compilation, TextWriter writer, SyntaxTree filterTree, TextSpan? filterSpanWithinTree, bool processIncludes, bool isForSingleSymbol, BindingDiagnosticBag diagnostics, CancellationToken cancellationToken) { _assemblyName = assemblyName; _compilation = compilation; _writer = writer; _filterTree = filterTree; _filterSpanWithinTree = filterSpanWithinTree; _processIncludes = processIncludes; _isForSingleSymbol = isForSingleSymbol; _diagnostics = diagnostics; _cancellationToken = cancellationToken; } /// <summary> /// Traverses the symbol table processing XML documentation comments and optionally writing them to /// a provided stream. /// </summary> /// <param name="compilation">Compilation that owns the symbol table.</param> /// <param name="assemblyName">Assembly name override, if specified. Otherwise the <see cref="ISymbol.Name"/> of the source assembly is used.</param> /// <param name="xmlDocStream">Stream to which XML will be written, if specified.</param> /// <param name="diagnostics">Will be supplemented with documentation comment diagnostics.</param> /// <param name="cancellationToken">To stop traversing the symbol table early.</param> /// <param name="filterTree">Only report diagnostics from this syntax tree, if non-null.</param> /// <param name="filterSpanWithinTree">If <paramref name="filterTree"/> and filterSpanWithinTree is non-null, report diagnostics within this span in the <paramref name="filterTree"/>.</param> #nullable enable public static void WriteDocumentationCommentXml(CSharpCompilation compilation, string? assemblyName, Stream? xmlDocStream, BindingDiagnosticBag diagnostics, CancellationToken cancellationToken, SyntaxTree? filterTree = null, TextSpan? filterSpanWithinTree = null) #nullable disable { StreamWriter writer = null; if (xmlDocStream != null && xmlDocStream.CanWrite) { writer = new StreamWriter( stream: xmlDocStream, encoding: new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: false), bufferSize: 0x400, // Default. leaveOpen: true); // Don't close caller's stream. } try { using (writer) { var compiler = new DocumentationCommentCompiler(assemblyName ?? compilation.SourceAssembly.Name, compilation, writer, filterTree, filterSpanWithinTree, processIncludes: true, isForSingleSymbol: false, diagnostics: diagnostics, cancellationToken: cancellationToken); compiler.Visit(compilation.SourceAssembly.GlobalNamespace); Debug.Assert(compiler._indentDepth == 0); writer?.Flush(); } } catch (Exception e) { diagnostics.Add(ErrorCode.ERR_DocFileGen, Location.None, e.Message); } if (diagnostics.DiagnosticBag is DiagnosticBag diagnosticBag) { if (filterTree != null) { // Will respect the DocumentationMode. UnprocessedDocumentationCommentFinder.ReportUnprocessed(filterTree, filterSpanWithinTree, diagnosticBag, cancellationToken); } else { foreach (SyntaxTree tree in compilation.SyntaxTrees) { // Will respect the DocumentationMode. UnprocessedDocumentationCommentFinder.ReportUnprocessed(tree, null, diagnosticBag, cancellationToken); } } } } /// <summary> /// Gets the XML that would be written to the documentation comment file for this assembly. /// </summary> /// <param name="symbol">The symbol for which to retrieve documentation comments.</param> /// <param name="processIncludes">True to treat includes as semantically meaningful (pull in contents from other files and bind crefs, etc).</param> /// <param name="cancellationToken">To stop traversing the symbol table early.</param> internal static string GetDocumentationCommentXml(Symbol symbol, bool processIncludes, CancellationToken cancellationToken) { Debug.Assert( symbol.Kind == SymbolKind.Event || symbol.Kind == SymbolKind.Field || symbol.Kind == SymbolKind.Method || symbol.Kind == SymbolKind.NamedType || symbol.Kind == SymbolKind.Property); CSharpCompilation compilation = symbol.DeclaringCompilation; Debug.Assert(compilation != null); PooledStringBuilder pooled = PooledStringBuilder.GetInstance(); StringWriter writer = new StringWriter(pooled.Builder); var compiler = new DocumentationCommentCompiler( assemblyName: null, compilation: compilation, writer: writer, filterTree: null, filterSpanWithinTree: null, processIncludes: processIncludes, isForSingleSymbol: true, diagnostics: BindingDiagnosticBag.Discarded, cancellationToken: cancellationToken); compiler.Visit(symbol); Debug.Assert(compiler._indentDepth == 0); writer.Dispose(); return pooled.ToStringAndFree(); } /// <summary> /// Write header, descend into members, and write footer. /// </summary> public override void VisitNamespace(NamespaceSymbol symbol) { _cancellationToken.ThrowIfCancellationRequested(); if (symbol.IsGlobalNamespace) { Debug.Assert(_assemblyName != null); WriteLine("<?xml version=\"1.0\"?>"); WriteLine("<doc>"); Indent(); if (!_compilation.Options.OutputKind.IsNetModule()) { WriteLine("<assembly>"); Indent(); WriteLine("<name>{0}</name>", _assemblyName); Unindent(); WriteLine("</assembly>"); } WriteLine("<members>"); Indent(); } Debug.Assert(!_isForSingleSymbol); foreach (var s in symbol.GetMembers()) { _cancellationToken.ThrowIfCancellationRequested(); s.Accept(this); } if (symbol.IsGlobalNamespace) { Unindent(); WriteLine("</members>"); Unindent(); WriteLine("</doc>"); } } /// <summary> /// Write own documentation comments and then descend into members. /// </summary> public override void VisitNamedType(NamedTypeSymbol symbol) { _cancellationToken.ThrowIfCancellationRequested(); if (_filterTree != null && !symbol.IsDefinedInSourceTree(_filterTree, _filterSpanWithinTree)) { return; } DefaultVisit(symbol); if (!_isForSingleSymbol) { foreach (Symbol member in symbol.GetMembers()) { _cancellationToken.ThrowIfCancellationRequested(); member.Accept(this); } } } /// <summary> /// Compile documentation comments on the symbol and write them to the stream if one is provided. /// </summary> public override void DefaultVisit(Symbol symbol) { _cancellationToken.ThrowIfCancellationRequested(); if (ShouldSkip(symbol)) { return; } if (_filterTree != null && !symbol.IsDefinedInSourceTree(_filterTree, _filterSpanWithinTree)) { return; } bool shouldSkipPartialDefinitionComments = false; if (symbol.IsPartialDefinition()) { if (symbol is MethodSymbol { PartialImplementationPart: MethodSymbol implementationPart }) { Visit(implementationPart); foreach (var trivia in implementationPart.GetNonNullSyntaxNode().GetLeadingTrivia()) { if (trivia.Kind() is SyntaxKind.SingleLineDocumentationCommentTrivia or SyntaxKind.MultiLineDocumentationCommentTrivia) { // If the partial method implementation has doc comments, // we will not emit any doc comments found on the definition, // regardless of whether the partial implementation doc comments are valid. shouldSkipPartialDefinitionComments = true; break; } } } else { // The partial method has no implementation. Since it won't be present in the // output assembly, it shouldn't be included in the documentation file. shouldSkipPartialDefinitionComments = !_isForSingleSymbol; } } DocumentationMode maxDocumentationMode; ImmutableArray<DocumentationCommentTriviaSyntax> docCommentNodes; if (!TryGetDocumentationCommentNodes(symbol, out maxDocumentationMode, out docCommentNodes)) { // If the XML in any of the doc comments is invalid, skip all further processing (for this symbol) and // just write a comment saying that info was lost for this symbol. string message = ErrorFacts.GetMessage(MessageID.IDS_XMLIGNORED, CultureInfo.CurrentUICulture); WriteLine(string.Format(CultureInfo.CurrentUICulture, message, symbol.GetDocumentationCommentId())); return; } // If there are no doc comments, then no further work is required (other than to report a diagnostic if one is required). if (docCommentNodes.IsEmpty) { if (maxDocumentationMode >= DocumentationMode.Diagnose && RequiresDocumentationComment(symbol) // We never give a missing doc comment warning on a partial method // implementation, and we skip the missing doc comment warning on a partial // definition whose documentation we were not going to output anyway. && !symbol.IsPartialImplementation() && !shouldSkipPartialDefinitionComments) { // Report the error at a location in the tree that was parsing doc comments. Location location = GetLocationInTreeReportingDocumentationCommentDiagnostics(symbol); if (location != null) { _diagnostics.Add(ErrorCode.WRN_MissingXMLComment, location, symbol); } } return; } _cancellationToken.ThrowIfCancellationRequested(); bool reportParameterOrTypeParameterDiagnostics = GetLocationInTreeReportingDocumentationCommentDiagnostics(symbol) != null; string withUnprocessedIncludes; bool haveParseError; HashSet<TypeParameterSymbol> documentedTypeParameters; HashSet<ParameterSymbol> documentedParameters; ImmutableArray<CSharpSyntaxNode> includeElementNodes; if (!TryProcessDocumentationCommentTriviaNodes( symbol, shouldSkipPartialDefinitionComments, docCommentNodes, reportParameterOrTypeParameterDiagnostics, out withUnprocessedIncludes, out haveParseError, out documentedTypeParameters, out documentedParameters, out includeElementNodes)) { return; } if (haveParseError) { // If the XML in any of the doc comments is invalid, skip all further processing (for this symbol) and // just write a comment saying that info was lost for this symbol. string message = ErrorFacts.GetMessage(MessageID.IDS_XMLIGNORED, CultureInfo.CurrentUICulture); WriteLine(string.Format(CultureInfo.CurrentUICulture, message, symbol.GetDocumentationCommentId())); return; } // If there are no include elements, then there's nothing to expand. if (!includeElementNodes.IsDefaultOrEmpty) { _cancellationToken.ThrowIfCancellationRequested(); // NOTE: we are expanding include elements AFTER formatting the comment, since the included text is pure // XML, not XML mixed with documentation comment trivia (e.g. ///). If we expanded them before formatting, // the formatting engine would have trouble determining what prefix to remove from each line. TextWriter expanderWriter = shouldSkipPartialDefinitionComments ? null : _writer; // Don't actually write partial method definition parts. IncludeElementExpander.ProcessIncludes(withUnprocessedIncludes, symbol, includeElementNodes, _compilation, ref documentedParameters, ref documentedTypeParameters, ref _includedFileCache, expanderWriter, _diagnostics, _cancellationToken); } else if (_writer != null && !shouldSkipPartialDefinitionComments) { // CONSIDER: The output would look a little different if we ran the XDocument through an XmlWriter. In particular, // formatting inside tags (e.g. <__tag___attr__=__"value"__>) would be normalized. Whitespace in elements would // (or should) not be affected. If we decide that this difference matters, we can run the XDocument through an XmlWriter. // Otherwise, just writing out the string saves a bunch of processing and does a better job of preserving whitespace. Write(withUnprocessedIncludes); } if (reportParameterOrTypeParameterDiagnostics) { _cancellationToken.ThrowIfCancellationRequested(); if (documentedParameters != null) { foreach (ParameterSymbol parameter in GetParameters(symbol)) { if (!documentedParameters.Contains(parameter)) { Location location = parameter.Locations[0]; Debug.Assert(location.SourceTree.ReportDocumentationCommentDiagnostics()); //Should be the same tree as for the symbol. // NOTE: parameter name, since the parameter would be displayed as just its type. _diagnostics.Add(ErrorCode.WRN_MissingParamTag, location, parameter.Name, symbol); } } } if (documentedTypeParameters != null) { foreach (TypeParameterSymbol typeParameter in GetTypeParameters(symbol)) { if (!documentedTypeParameters.Contains(typeParameter)) { Location location = typeParameter.Locations[0]; Debug.Assert(location.SourceTree.ReportDocumentationCommentDiagnostics()); //Should be the same tree as for the symbol. _diagnostics.Add(ErrorCode.WRN_MissingTypeParamTag, location, typeParameter, symbol); } } } } } private static bool ShouldSkip(Symbol symbol) { return symbol.IsImplicitlyDeclared || symbol.IsAccessor() || symbol is SynthesizedSimpleProgramEntryPointSymbol || symbol is SynthesizedRecordPropertySymbol; } /// <summary> /// Loop over the DocumentationCommentTriviaSyntaxes. Gather /// 1) concatenated XML, as a string; /// 2) whether or not the XML is valid; /// 3) set of type parameters covered by &lt;typeparam&gt; elements; /// 4) set of parameters covered by &lt;param&gt; elements; /// 5) list of &lt;include&gt; elements, as SyntaxNodes. /// </summary> /// <returns>True, if at least one documentation comment was processed; false, otherwise.</returns> /// <remarks>This was factored out for clarity, not because it's reusable.</remarks> private bool TryProcessDocumentationCommentTriviaNodes( Symbol symbol, bool shouldSkipPartialDefinitionComments, ImmutableArray<DocumentationCommentTriviaSyntax> docCommentNodes, bool reportParameterOrTypeParameterDiagnostics, out string withUnprocessedIncludes, out bool haveParseError, out HashSet<TypeParameterSymbol> documentedTypeParameters, out HashSet<ParameterSymbol> documentedParameters, out ImmutableArray<CSharpSyntaxNode> includeElementNodes) { Debug.Assert(!docCommentNodes.IsDefaultOrEmpty); bool processedDocComment = false; // Even if there are DocumentationCommentTriviaSyntax, we may not need to process any of them. ArrayBuilder<CSharpSyntaxNode> includeElementNodesBuilder = null; documentedParameters = null; documentedTypeParameters = null; // Saw an XmlException while parsing one of the DocumentationCommentTriviaSyntax nodes. haveParseError = false; // We're doing substitution and formatting per-trivia, rather than per-symbol, // because a single symbol can have both single-line and multi-line style // doc comments. foreach (DocumentationCommentTriviaSyntax trivia in docCommentNodes) { _cancellationToken.ThrowIfCancellationRequested(); bool reportDiagnosticsForCurrentTrivia = trivia.SyntaxTree.ReportDocumentationCommentDiagnostics(); if (!processedDocComment) { // Since we have to throw away all the parts if any part is bad, we need to write to an intermediate temp. BeginTemporaryString(); if (_processIncludes) { includeElementNodesBuilder = ArrayBuilder<CSharpSyntaxNode>.GetInstance(); } // We DO want to write out partial method definition parts if we're processing includes // because we need to have XML to process. if (!shouldSkipPartialDefinitionComments || _processIncludes) { WriteLine("<member name=\"{0}\">", symbol.GetDocumentationCommentId()); Indent(); } processedDocComment = true; } // Will respect the DocumentationMode. string substitutedText = DocumentationCommentWalker.GetSubstitutedText(_compilation, _diagnostics, symbol, trivia, includeElementNodesBuilder, ref documentedParameters, ref documentedTypeParameters); string formattedXml = FormatComment(substitutedText); // It would be preferable to just parse the concatenated XML at the end of the loop (we wouldn't have // to wrap it in a root element and we wouldn't have to reparse in the IncludeElementExpander), but // then we wouldn't know whether or where to report a diagnostic. XmlException e = XmlDocumentationCommentTextReader.ParseAndGetException(formattedXml); if (e != null) { haveParseError = true; if (reportDiagnosticsForCurrentTrivia) { Location location = new SourceLocation(trivia.SyntaxTree, new TextSpan(trivia.SpanStart, 0)); _diagnostics.Add(ErrorCode.WRN_XMLParseError, location, GetDescription(e)); } } // For partial methods, all parts are validated, but only the implementation part is written to the XML stream. if (!shouldSkipPartialDefinitionComments || _processIncludes) { // This string already has indentation and line breaks, so don't call WriteLine - just write the text directly. Write(formattedXml); } } if (!processedDocComment) { withUnprocessedIncludes = null; includeElementNodes = default(ImmutableArray<CSharpSyntaxNode>); return false; } if (!shouldSkipPartialDefinitionComments || _processIncludes) { Unindent(); WriteLine("</member>"); } // Free the temp. withUnprocessedIncludes = GetAndEndTemporaryString(); // Free the builder, even if there was an error. includeElementNodes = _processIncludes ? includeElementNodesBuilder.ToImmutableAndFree() : default(ImmutableArray<CSharpSyntaxNode>); return true; } private static Location GetLocationInTreeReportingDocumentationCommentDiagnostics(Symbol symbol) { foreach (Location location in symbol.Locations) { if (location.SourceTree.ReportDocumentationCommentDiagnostics()) { return location; } } return null; } /// <remarks> /// Similar to SymbolExtensions.GetParameters, but returns empty for unsupported symbols /// and handles delegates. /// </remarks> private static ImmutableArray<ParameterSymbol> GetParameters(Symbol symbol) { switch (symbol.Kind) { case SymbolKind.NamedType: MethodSymbol delegateInvoke = ((NamedTypeSymbol)symbol).DelegateInvokeMethod; if ((object)delegateInvoke != null) { return delegateInvoke.Parameters; } break; case SymbolKind.Method: case SymbolKind.Property: case SymbolKind.Event: return symbol.GetParameters(); } return ImmutableArray<ParameterSymbol>.Empty; } /// <remarks> /// Similar to SymbolExtensions.GetMemberTypeParameters, but returns empty for unsupported symbols. /// </remarks> private static ImmutableArray<TypeParameterSymbol> GetTypeParameters(Symbol symbol) { switch (symbol.Kind) { case SymbolKind.Method: case SymbolKind.NamedType: case SymbolKind.ErrorType: return symbol.GetMemberTypeParameters(); } return ImmutableArray<TypeParameterSymbol>.Empty; } /// <summary> /// A symbol requires a documentation comment if it was explicitly declared and /// will be visible outside the current assembly (ignoring InternalsVisibleTo). /// Exception: accessors do not require doc comments. /// </summary> private static bool RequiresDocumentationComment(Symbol symbol) { Debug.Assert((object)symbol != null); if (ShouldSkip(symbol)) { return false; } while ((object)symbol != null) { switch (symbol.DeclaredAccessibility) { case Accessibility.Public: case Accessibility.Protected: case Accessibility.ProtectedOrInternal: symbol = symbol.ContainingType; break; default: return false; } } return true; } /// <summary> /// Get all of the DocumentationCommentTriviaSyntax associated with any declaring syntax of the /// given symbol (except for partial methods, which only consider the part with the body). /// </summary> /// <returns>True if the nodes are all valid XML.</returns> private bool TryGetDocumentationCommentNodes(Symbol symbol, out DocumentationMode maxDocumentationMode, out ImmutableArray<DocumentationCommentTriviaSyntax> nodes) { maxDocumentationMode = DocumentationMode.None; nodes = default(ImmutableArray<DocumentationCommentTriviaSyntax>); ArrayBuilder<DocumentationCommentTriviaSyntax> builder = null; var diagnosticBag = _diagnostics.DiagnosticBag ?? DiagnosticBag.GetInstance(); foreach (SyntaxReference reference in symbol.DeclaringSyntaxReferences) { DocumentationMode currDocumentationMode = reference.SyntaxTree.Options.DocumentationMode; maxDocumentationMode = currDocumentationMode > maxDocumentationMode ? currDocumentationMode : maxDocumentationMode; ImmutableArray<DocumentationCommentTriviaSyntax> triviaList = SourceDocumentationCommentUtils.GetDocumentationCommentTriviaFromSyntaxNode((CSharpSyntaxNode)reference.GetSyntax(), diagnosticBag); foreach (var trivia in triviaList) { if (ContainsXmlParseDiagnostic(trivia)) { if (builder != null) { builder.Free(); } return false; } if (builder == null) { builder = ArrayBuilder<DocumentationCommentTriviaSyntax>.GetInstance(); } builder.Add(trivia); } } if (diagnosticBag != _diagnostics.DiagnosticBag) { diagnosticBag.Free(); } if (builder == null) { nodes = ImmutableArray<DocumentationCommentTriviaSyntax>.Empty; } else { builder.Sort(Comparer); nodes = builder.ToImmutableAndFree(); } return true; } private static bool ContainsXmlParseDiagnostic(DocumentationCommentTriviaSyntax node) { if (!node.ContainsDiagnostics) { return false; } foreach (Diagnostic diag in node.GetDiagnostics()) { if ((ErrorCode)diag.Code == ErrorCode.WRN_XMLParseError) { return true; } } return false; } private static readonly string[] s_newLineSequences = new[] { "\r\n", "\r", "\n" }; /// <summary> /// Given the full text of a documentation comment, strip off the comment punctuation (///, /**, etc) /// and add appropriate indentations. /// </summary> private string FormatComment(string substitutedText) { BeginTemporaryString(); if (TrimmedStringStartsWith(substitutedText, "///")) { //Debug.Assert(lines.Take(numLines).All(line => TrimmedStringStartsWith(line, "///"))); WriteFormattedSingleLineComment(substitutedText); } else { string[] lines = substitutedText.Split(s_newLineSequences, StringSplitOptions.None); int numLines = lines.Length; Debug.Assert(numLines > 0); if (string.IsNullOrEmpty(lines[numLines - 1])) { numLines--; Debug.Assert(numLines > 0); } Debug.Assert(TrimmedStringStartsWith(lines[0], "/**")); WriteFormattedMultiLineComment(lines, numLines); } return GetAndEndTemporaryString(); } /// <summary> /// Given a string, find the index of the first non-whitespace char. /// </summary> /// <param name="str">The string to search</param> /// <returns>The index of the first non-whitespace char in the string</returns> private static int GetIndexOfFirstNonWhitespaceChar(string str) { return GetIndexOfFirstNonWhitespaceChar(str, 0, str.Length); } /// <summary> /// Find the first non-whitespace character in a given substring. /// </summary> /// <param name="str">The string to search</param> /// <param name="start">The start index</param> /// <param name="end">The last index (non-inclusive)</param> /// <returns>The index of the first non-whitespace char after index start in the string up to, but not including the end index</returns> private static int GetIndexOfFirstNonWhitespaceChar(string str, int start, int end) { Debug.Assert(start >= 0); Debug.Assert(start <= str.Length); Debug.Assert(end >= 0); Debug.Assert(end <= str.Length); Debug.Assert(end >= start); for (; start < end; start++) { if (!SyntaxFacts.IsWhitespace(str[start])) { break; } } return start; } /// <summary> /// Determine if the given string starts with the given prefix if whitespace /// is first trimmed from the beginning. /// </summary> /// <param name="str">The string to search</param> /// <param name="prefix">The prefix</param> /// <returns>true if str.TrimStart().StartsWith(prefix)</returns> private static bool TrimmedStringStartsWith(string str, string prefix) { // PERF: Avoid calling string.Trim() because that allocates a new substring int start = GetIndexOfFirstNonWhitespaceChar(str); int len = str.Length - start; if (len < prefix.Length) { return false; } for (int i = 0; i < prefix.Length; i++) { if (prefix[i] != str[i + start]) { return false; } } return true; } /// <summary> /// Given a string which may contain newline sequences, get the index of the first newline /// sequence beginning at the given starting index. /// </summary> /// <param name="str">The string to split.</param> /// <param name="start">The starting index within the string.</param> /// <param name="newLineLength">The length of the newline sequence discovered. 0 if the end of the string was reached, otherwise either 1 or 2 chars</param> /// <returns>The index of the start of the first newline sequence following the start index</returns> private static int IndexOfNewLine(string str, int start, out int newLineLength) { for (; start < str.Length; start++) { switch (str[start]) { case '\r': if ((start + 1) < str.Length && str[start + 1] == '\n') { newLineLength = 2; } else { newLineLength = 1; } return start; case '\n': newLineLength = 1; return start; } } newLineLength = 0; return start; } /// <summary> /// Given the full text of a single-line style documentation comment, for each line, strip off /// the comment punctuation (///) and add appropriate indentations. /// </summary> private void WriteFormattedSingleLineComment(string text) { // PERF: Avoid allocating intermediate strings e.g. via Split, Trim or Substring bool skipSpace = true; for (int start = 0; start < text.Length;) { int newLineLength; int end = IndexOfNewLine(text, start, out newLineLength); int trimStart = GetIndexOfFirstNonWhitespaceChar(text, start, end); int trimmedLength = end - trimStart; if (trimmedLength < 4 || !SyntaxFacts.IsWhitespace(text[trimStart + 3])) { skipSpace = false; break; } start = end + newLineLength; } int substringStart = skipSpace ? 4 : 3; for (int start = 0; start < text.Length;) { int newLineLength; int end = IndexOfNewLine(text, start, out newLineLength); int trimStart = GetIndexOfFirstNonWhitespaceChar(text, start, end) + substringStart; WriteSubStringLine(text, trimStart, end - trimStart); start = end + newLineLength; } } /// <summary> /// Given the full text of a multi-line style documentation comment, broken into lines, strip off /// the comment punctuation (/**, */, etc) and add appropriate indentations. /// </summary> private void WriteFormattedMultiLineComment(string[] lines, int numLines) { bool skipFirstLine = lines[0].Trim() == "/**"; bool skipLastLine = lines[numLines - 1].Trim() == "*/"; if (skipLastLine) { numLines--; Debug.Assert(numLines > 0); } int skipLength = 0; if (numLines > 1) { string pattern = FindMultiLineCommentPattern(lines[1]); if (pattern != null) { bool allMatch = true; for (int i = 2; i < numLines; i++) { string currentLinePattern = LongestCommonPrefix(pattern, lines[i]); if (string.IsNullOrWhiteSpace(currentLinePattern)) { allMatch = false; break; } Debug.Assert(pattern.StartsWith(currentLinePattern, StringComparison.Ordinal)); pattern = currentLinePattern; } if (allMatch) { skipLength = pattern.Length; } } } if (!skipFirstLine) { string trimmed = lines[0].TrimStart(null); if (!skipLastLine && numLines == 1) { trimmed = TrimEndOfMultiLineComment(trimmed); } WriteLine(trimmed.Substring(SyntaxFacts.IsWhitespace(trimmed[3]) ? 4 : 3)); } for (int i = 1; i < numLines; i++) { string trimmed = lines[i].Substring(skipLength); // If we've already skipped the last line, this can't happen. if (!skipLastLine && i == numLines - 1) { trimmed = TrimEndOfMultiLineComment(trimmed); } WriteLine(trimmed); } } /// <summary> /// Remove "*/" and any following text, if it is present. /// </summary> private static string TrimEndOfMultiLineComment(string trimmed) { int index = trimmed.IndexOf("*/", StringComparison.Ordinal); if (index >= 0) { trimmed = trimmed.Substring(0, index); } return trimmed; } /// <summary> /// Return the longest prefix matching [whitespace]*[*][whitespace]*. /// </summary> private static string FindMultiLineCommentPattern(string line) { int length = 0; bool seenStar = false; foreach (char ch in line) { if (SyntaxFacts.IsWhitespace(ch)) { length++; } else if (!seenStar && ch == '*') { length++; seenStar = true; } else { break; } } return seenStar ? line.Substring(0, length) : null; } /// <summary> /// Return the longest common prefix of two strings /// </summary> private static string LongestCommonPrefix(string str1, string str2) { int pos = 0; int minLength = Math.Min(str1.Length, str2.Length); for (; pos < minLength && str1[pos] == str2[pos]; pos++) { } return str1.Substring(0, pos); } /// <summary> /// Bind a CrefSyntax and unwrap the result if it's an alias. /// </summary> /// <remarks> /// Does not respect DocumentationMode, so use a temporary bag if diagnostics are not desired. /// </remarks> private static string GetDocumentationCommentId(CrefSyntax crefSyntax, Binder binder, BindingDiagnosticBag diagnostics) { if (crefSyntax.ContainsDiagnostics) { return ToBadCrefString(crefSyntax); } Symbol ambiguityWinner; ImmutableArray<Symbol> symbols = binder.BindCref(crefSyntax, out ambiguityWinner, diagnostics); Symbol symbol; switch (symbols.Length) { case 0: return ToBadCrefString(crefSyntax); case 1: symbol = symbols[0]; break; default: symbol = ambiguityWinner; Debug.Assert((object)symbol != null); break; } if (symbol.Kind == SymbolKind.Alias) { symbol = ((AliasSymbol)symbol).GetAliasTarget(basesBeingResolved: null); } if (symbol is NamespaceSymbol ns) { Debug.Assert(!ns.IsGlobalNamespace); diagnostics.AddAssembliesUsedByNamespaceReference(ns); } else { diagnostics.AddDependencies(symbol as TypeSymbol ?? symbol.ContainingType); } return symbol.OriginalDefinition.GetDocumentationCommentId(); } /// <summary> /// Given a cref syntax that cannot be resolved, get the string that will be written to /// the documentation file in place of a documentation comment ID. /// </summary> private static string ToBadCrefString(CrefSyntax cref) { using (StringWriter tmp = new StringWriter(CultureInfo.InvariantCulture)) { cref.WriteTo(tmp); return "!:" + tmp.ToString().Replace("{", "&lt;").Replace("}", "&gt;"); } } /// <summary> /// Bind an XmlNameAttributeSyntax and update the sets of documented parameters and type parameters. /// </summary> /// <remarks> /// Does not respect DocumentationMode, so do not call unless diagnostics are desired. /// </remarks> private static void BindName( XmlNameAttributeSyntax syntax, Binder binder, Symbol memberSymbol, ref HashSet<ParameterSymbol> documentedParameters, ref HashSet<TypeParameterSymbol> documentedTypeParameters, BindingDiagnosticBag diagnostics) { XmlNameAttributeElementKind elementKind = syntax.GetElementKind(); // NOTE: We want the corresponding hash set to be non-null if we saw // any <param>/<typeparam> elements, even if they didn't bind (for // WRN_MissingParamTag and WRN_MissingTypeParamTag). if (elementKind == XmlNameAttributeElementKind.Parameter) { if (documentedParameters == null) { documentedParameters = new HashSet<ParameterSymbol>(); } } else if (elementKind == XmlNameAttributeElementKind.TypeParameter) { if (documentedTypeParameters == null) { documentedTypeParameters = new HashSet<TypeParameterSymbol>(); } } IdentifierNameSyntax identifier = syntax.Identifier; if (identifier.ContainsDiagnostics) { return; } CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = binder.GetNewCompoundUseSiteInfo(diagnostics); ImmutableArray<Symbol> referencedSymbols = binder.BindXmlNameAttribute(syntax, ref useSiteInfo); diagnostics.Add(syntax, useSiteInfo); if (referencedSymbols.IsEmpty) { switch (elementKind) { case XmlNameAttributeElementKind.Parameter: diagnostics.Add(ErrorCode.WRN_UnmatchedParamTag, identifier.Location, identifier); break; case XmlNameAttributeElementKind.ParameterReference: diagnostics.Add(ErrorCode.WRN_UnmatchedParamRefTag, identifier.Location, identifier, memberSymbol); break; case XmlNameAttributeElementKind.TypeParameter: diagnostics.Add(ErrorCode.WRN_UnmatchedTypeParamTag, identifier.Location, identifier); break; case XmlNameAttributeElementKind.TypeParameterReference: diagnostics.Add(ErrorCode.WRN_UnmatchedTypeParamRefTag, identifier.Location, identifier, memberSymbol); break; default: throw ExceptionUtilities.UnexpectedValue(elementKind); } } else { foreach (Symbol referencedSymbol in referencedSymbols) { if (elementKind == XmlNameAttributeElementKind.Parameter) { Debug.Assert(referencedSymbol.Kind == SymbolKind.Parameter); Debug.Assert(documentedParameters != null); // Restriction preserved from dev11: don't report this for the "value" parameter. // Here, we detect that case by checking the containing symbol - only "value" // parameters are contained by accessors, others are on the corresponding property/event. ParameterSymbol parameter = (ParameterSymbol)referencedSymbol; if (!parameter.ContainingSymbol.IsAccessor() && !documentedParameters.Add(parameter)) { diagnostics.Add(ErrorCode.WRN_DuplicateParamTag, syntax.Location, identifier); } } else if (elementKind == XmlNameAttributeElementKind.TypeParameter) { Debug.Assert(referencedSymbol.Kind == SymbolKind.TypeParameter); Debug.Assert(documentedTypeParameters != null); if (!documentedTypeParameters.Add((TypeParameterSymbol)referencedSymbol)) { diagnostics.Add(ErrorCode.WRN_DuplicateTypeParamTag, syntax.Location, identifier); } } } } } private IComparer<CSharpSyntaxNode> Comparer { get { if (_lazyComparer == null) { _lazyComparer = new SyntaxNodeLocationComparer(_compilation); } return _lazyComparer; } } private void BeginTemporaryString() { if (_temporaryStringBuilders == null) { _temporaryStringBuilders = new Stack<TemporaryStringBuilder>(); } _temporaryStringBuilders.Push(new TemporaryStringBuilder(_indentDepth)); } private string GetAndEndTemporaryString() { TemporaryStringBuilder t = _temporaryStringBuilders.Pop(); Debug.Assert(_indentDepth == t.InitialIndentDepth, $"Temporary strings should be indent-neutral (was {t.InitialIndentDepth}, is {_indentDepth})"); _indentDepth = t.InitialIndentDepth; return t.Pooled.ToStringAndFree(); } private void Indent() { _indentDepth++; } private void Unindent() { _indentDepth--; Debug.Assert(_indentDepth >= 0); } private void Write(string indentedAndWrappedString) { if (_temporaryStringBuilders != null && _temporaryStringBuilders.Count > 0) { StringBuilder builder = _temporaryStringBuilders.Peek().Pooled.Builder; builder.Append(indentedAndWrappedString); } else if (_writer != null) { _writer.Write(indentedAndWrappedString); } } private void WriteLine(string message) { if (_temporaryStringBuilders?.Count > 0) { StringBuilder builder = _temporaryStringBuilders.Peek().Pooled.Builder; builder.Append(MakeIndent(_indentDepth)); builder.AppendLine(message); } else if (_writer != null) { _writer.Write(MakeIndent(_indentDepth)); _writer.WriteLine(message); } } private void WriteSubStringLine(string message, int start, int length) { if (_temporaryStringBuilders?.Count > 0) { StringBuilder builder = _temporaryStringBuilders.Peek().Pooled.Builder; builder.Append(MakeIndent(_indentDepth)); builder.Append(message, start, length); builder.AppendLine(); } else if (_writer != null) { _writer.Write(MakeIndent(_indentDepth)); for (int i = 0; i < length; i++) { _writer.Write(message[start + i]); } _writer.WriteLine(); } } private void WriteLine(string format, params object[] args) { WriteLine(string.Format(format, args)); } private static string MakeIndent(int depth) { Debug.Assert(depth >= 0); // Since we know a lot about the structure of the output, // we should be able to do this without constructing any // new string objects. switch (depth) { case 0: return ""; case 1: return " "; case 2: return " "; case 3: return " "; default: Debug.Assert(false, "Didn't expect nesting to reach depth " + depth); return new string(' ', depth * 4); } } /// <remarks> /// WORKAROUND: /// We're taking a dependency on the location and structure of a framework assembly resource. This is not a robust solution. /// /// Possible alternatives: /// 1) Polish our XML parser until it matches MSXML. We don't want to reinvent the wheel. /// 2) Build a map that lets us go from XML string positions back to source positions. /// This is what the native compiler did, and it was a lot of work. We'd also still need to modify the message. /// 3) Do not report a diagnostic. This is very unhelpful. /// 4) Report a vague diagnostic (i.e. there's a problem somewhere in this doc comment). This is relatively unhelpful. /// 5) Always report the message in English, so that we can pull it apart without needing to consume resource files. /// This engenders a lot of ill will. /// 6) Report the exception message without modification and (optionally) include the text with respect to which the /// position is specified. This would not look sufficiently polished. /// </remarks> private static string GetDescription(XmlException e) { string message = e.Message; try { ResourceManager manager = new ResourceManager("System.Xml", typeof(XmlException).GetTypeInfo().Assembly); string locationTemplate = manager.GetString("Xml_MessageWithErrorPosition"); string locationString = string.Format(locationTemplate, "", e.LineNumber, e.LinePosition); // first arg is where the problem description goes int position = message.IndexOf(locationString, StringComparison.Ordinal); // Expect exact match return position < 0 ? message : message.Remove(position, locationString.Length); } catch { Debug.Assert(false, "If we hit this, then we might need to think about a different workaround " + "for stripping the location out the message."); // If anything at all goes wrong, just return the message verbatim. It probably // contains an invalid position, but it's better than nothing. return message; } } private struct TemporaryStringBuilder { public readonly PooledStringBuilder Pooled; public readonly int InitialIndentDepth; public TemporaryStringBuilder(int indentDepth) { this.InitialIndentDepth = indentDepth; this.Pooled = PooledStringBuilder.GetInstance(); } } } }
1
dotnet/roslyn
56,419
Fix partial method doc comments
Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
RikkiGibson
"2021-09-15T20:47:39Z"
"2021-09-21T23:49:10Z"
0f60b3e9446f5d0fc14a570998c81a5d6c40cc23
8cda7462843d43d9b72039eede2f4cb43126cac2
Fix partial method doc comments. Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
./src/Compilers/CSharp/Portable/Symbols/Source/SourceOrdinaryMethodSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal sealed class SourceOrdinaryMethodSymbol : SourceOrdinaryMethodSymbolBase { private readonly TypeSymbol _explicitInterfaceType; private readonly bool _isExpressionBodied; private readonly bool _hasAnyBody; private readonly RefKind _refKind; private bool _lazyIsVararg; /// <summary> /// A collection of type parameter constraint types, populated when /// constraint types for the first type parameter is requested. /// Initialized in two steps. Hold a copy if accessing during initialization. /// </summary> private ImmutableArray<ImmutableArray<TypeWithAnnotations>> _lazyTypeParameterConstraintTypes; /// <summary> /// A collection of type parameter constraint kinds, populated when /// constraint kinds for the first type parameter is requested. /// Initialized in two steps. Hold a copy if accessing during initialization. /// </summary> private ImmutableArray<TypeParameterConstraintKind> _lazyTypeParameterConstraintKinds; /// <summary> /// If this symbol represents a partial method definition or implementation part, its other part (if any). /// This should be set, if at all, before this symbol appears among the members of its owner. /// The implementation part is not listed among the "members" of the enclosing type. /// </summary> private SourceOrdinaryMethodSymbol _otherPartOfPartial; public static SourceOrdinaryMethodSymbol CreateMethodSymbol( NamedTypeSymbol containingType, Binder bodyBinder, MethodDeclarationSyntax syntax, bool isNullableAnalysisEnabled, BindingDiagnosticBag diagnostics) { var interfaceSpecifier = syntax.ExplicitInterfaceSpecifier; var nameToken = syntax.Identifier; TypeSymbol explicitInterfaceType; var name = ExplicitInterfaceHelpers.GetMemberNameAndInterfaceSymbol(bodyBinder, interfaceSpecifier, nameToken.ValueText, diagnostics, out explicitInterfaceType, aliasQualifierOpt: out _); var location = new SourceLocation(nameToken); var methodKind = interfaceSpecifier == null ? MethodKind.Ordinary : MethodKind.ExplicitInterfaceImplementation; return new SourceOrdinaryMethodSymbol(containingType, explicitInterfaceType, name, location, syntax, methodKind, isNullableAnalysisEnabled, diagnostics); } private SourceOrdinaryMethodSymbol( NamedTypeSymbol containingType, TypeSymbol explicitInterfaceType, string name, Location location, MethodDeclarationSyntax syntax, MethodKind methodKind, bool isNullableAnalysisEnabled, BindingDiagnosticBag diagnostics) : base(containingType, name, location, syntax, methodKind, isIterator: SyntaxFacts.HasYieldOperations(syntax.Body), isExtensionMethod: syntax.ParameterList.Parameters.FirstOrDefault() is ParameterSyntax firstParam && !firstParam.IsArgList && firstParam.Modifiers.Any(SyntaxKind.ThisKeyword), isPartial: syntax.Modifiers.IndexOf(SyntaxKind.PartialKeyword) < 0, isReadOnly: false, hasBody: syntax.Body != null || syntax.ExpressionBody != null, isNullableAnalysisEnabled: isNullableAnalysisEnabled, diagnostics) { Debug.Assert(diagnostics.DiagnosticBag is object); _explicitInterfaceType = explicitInterfaceType; bool hasBlockBody = syntax.Body != null; _isExpressionBodied = !hasBlockBody && syntax.ExpressionBody != null; bool hasBody = hasBlockBody || _isExpressionBodied; _hasAnyBody = hasBody; _refKind = syntax.ReturnType.GetRefKind(); CheckForBlockAndExpressionBody( syntax.Body, syntax.ExpressionBody, syntax, diagnostics); } protected override ImmutableArray<TypeParameterSymbol> MakeTypeParameters(CSharpSyntaxNode node, BindingDiagnosticBag diagnostics) { var syntax = (MethodDeclarationSyntax)node; if (syntax.Arity == 0) { ReportErrorIfHasConstraints(syntax.ConstraintClauses, diagnostics.DiagnosticBag); return ImmutableArray<TypeParameterSymbol>.Empty; } else { return MakeTypeParameters(syntax, diagnostics); } } protected override (TypeWithAnnotations ReturnType, ImmutableArray<ParameterSymbol> Parameters, bool IsVararg, ImmutableArray<TypeParameterConstraintClause> DeclaredConstraintsForOverrideOrImplementation) MakeParametersAndBindReturnType(BindingDiagnosticBag diagnostics) { var syntax = GetSyntax(); var withTypeParamsBinder = this.DeclaringCompilation.GetBinderFactory(syntax.SyntaxTree).GetBinder(syntax.ReturnType, syntax, this); SyntaxToken arglistToken; // Constraint checking for parameter and return types must be delayed until // the method has been added to the containing type member list since // evaluating the constraints may depend on accessing this method from // the container (comparing this method to others to find overrides for // instance). Constraints are checked in AfterAddingTypeMembersChecks. var signatureBinder = withTypeParamsBinder.WithAdditionalFlagsAndContainingMemberOrLambda(BinderFlags.SuppressConstraintChecks, this); ImmutableArray<ParameterSymbol> parameters = ParameterHelpers.MakeParameters( signatureBinder, this, syntax.ParameterList, out arglistToken, allowRefOrOut: true, allowThis: true, addRefReadOnlyModifier: IsVirtual || IsAbstract, diagnostics: diagnostics); _lazyIsVararg = (arglistToken.Kind() == SyntaxKind.ArgListKeyword); RefKind refKind; var returnTypeSyntax = syntax.ReturnType.SkipRef(out refKind); TypeWithAnnotations returnType = signatureBinder.BindType(returnTypeSyntax, diagnostics); // span-like types are returnable in general if (returnType.IsRestrictedType(ignoreSpanLikeTypes: true)) { if (returnType.SpecialType == SpecialType.System_TypedReference && (this.ContainingType.SpecialType == SpecialType.System_TypedReference || this.ContainingType.SpecialType == SpecialType.System_ArgIterator)) { // Two special cases: methods in the special types TypedReference and ArgIterator are allowed to return TypedReference } else { // The return type of a method, delegate, or function pointer cannot be '{0}' diagnostics.Add(ErrorCode.ERR_MethodReturnCantBeRefAny, syntax.ReturnType.Location, returnType.Type); } } Debug.Assert(this.RefKind == RefKind.None || !returnType.IsVoidType() || returnTypeSyntax.HasErrors); ImmutableArray<TypeParameterConstraintClause> declaredConstraints = default; if (this.Arity != 0 && (syntax.ExplicitInterfaceSpecifier != null || IsOverride)) { // When a generic method overrides a generic method declared in a base class, or is an // explicit interface member implementation of a method in a base interface, the method // shall not specify any type-parameter-constraints-clauses, except for a struct, class, or default constraint. // In these cases, the type parameters of the method inherit constraints from the method being overridden or // implemented. if (syntax.ConstraintClauses.Count > 0) { Binder.CheckFeatureAvailability(syntax.SyntaxTree, MessageID.IDS_OverrideWithConstraints, diagnostics, syntax.ConstraintClauses[0].WhereKeyword.GetLocation()); declaredConstraints = signatureBinder.WithAdditionalFlags(BinderFlags.GenericConstraintsClause | BinderFlags.SuppressConstraintChecks). BindTypeParameterConstraintClauses(this, TypeParameters, syntax.TypeParameterList, syntax.ConstraintClauses, diagnostics, performOnlyCycleSafeValidation: false, isForOverride: true); Debug.Assert(declaredConstraints.All(clause => clause.ConstraintTypes.IsEmpty)); } // Force resolution of nullable type parameter used in the signature of an override or explicit interface implementation // based on constraints specified by the declaration. foreach (var param in parameters) { forceMethodTypeParameters(param.TypeWithAnnotations, this, declaredConstraints); } forceMethodTypeParameters(returnType, this, declaredConstraints); } return (returnType, parameters, _lazyIsVararg, declaredConstraints); static void forceMethodTypeParameters(TypeWithAnnotations type, SourceOrdinaryMethodSymbol method, ImmutableArray<TypeParameterConstraintClause> declaredConstraints) { type.VisitType(null, (type, args, unused2) => { if (type.DefaultType is TypeParameterSymbol typeParameterSymbol && typeParameterSymbol.DeclaringMethod == (object)args.method) { var asValueType = args.declaredConstraints.IsDefault || (args.declaredConstraints[typeParameterSymbol.Ordinal].Constraints & (TypeParameterConstraintKind.ReferenceType | TypeParameterConstraintKind.Default)) == 0; type.TryForceResolve(asValueType); } return false; }, typePredicate: null, arg: (method, declaredConstraints), canDigThroughNullable: false, useDefaultType: true); } } protected override void ExtensionMethodChecks(BindingDiagnosticBag diagnostics) { // errors relevant for extension methods if (IsExtensionMethod) { var syntax = GetSyntax(); var location = locations[0]; var parameter0Type = this.Parameters[0].TypeWithAnnotations; var parameter0RefKind = this.Parameters[0].RefKind; if (!parameter0Type.Type.IsValidExtensionParameterType()) { // Duplicate Dev10 behavior by selecting the parameter type. var parameterSyntax = syntax.ParameterList.Parameters[0]; Debug.Assert(parameterSyntax.Type != null); var loc = parameterSyntax.Type.Location; diagnostics.Add(ErrorCode.ERR_BadTypeforThis, loc, parameter0Type.Type); } else if (parameter0RefKind == RefKind.Ref && !parameter0Type.Type.IsValueType) { diagnostics.Add(ErrorCode.ERR_RefExtensionMustBeValueTypeOrConstrainedToOne, location, Name); } else if (parameter0RefKind == RefKind.In && parameter0Type.TypeKind != TypeKind.Struct) { diagnostics.Add(ErrorCode.ERR_InExtensionMustBeValueType, location, Name); } else if ((object)ContainingType.ContainingType != null) { diagnostics.Add(ErrorCode.ERR_ExtensionMethodsDecl, location, ContainingType.Name); } else if (!ContainingType.IsScriptClass && !(ContainingType.IsStatic && ContainingType.Arity == 0)) { // Duplicate Dev10 behavior by selecting the containing type identifier. However if there // is no containing type (in the interactive case for instance), select the method identifier. var typeDecl = syntax.Parent as TypeDeclarationSyntax; var identifier = (typeDecl != null) ? typeDecl.Identifier : syntax.Identifier; var loc = identifier.GetLocation(); diagnostics.Add(ErrorCode.ERR_BadExtensionAgg, loc); } else if (!IsStatic) { diagnostics.Add(ErrorCode.ERR_BadExtensionMeth, location); } else { // Verify ExtensionAttribute is available. var attributeConstructor = Binder.GetWellKnownTypeMember(DeclaringCompilation, WellKnownMember.System_Runtime_CompilerServices_ExtensionAttribute__ctor, out var useSiteInfo); Location thisLocation = syntax.ParameterList.Parameters[0].Modifiers.FirstOrDefault(SyntaxKind.ThisKeyword).GetLocation(); if ((object)attributeConstructor == null) { var memberDescriptor = WellKnownMembers.GetDescriptor(WellKnownMember.System_Runtime_CompilerServices_ExtensionAttribute__ctor); // do not use Binder.ReportUseSiteErrorForAttributeCtor in this case, because we'll need to report a special error id, not a generic use site error. diagnostics.Add( ErrorCode.ERR_ExtensionAttrNotFound, thisLocation, memberDescriptor.DeclaringTypeMetadataName); } else { diagnostics.Add(useSiteInfo, thisLocation); } } } } protected override MethodSymbol FindExplicitlyImplementedMethod(BindingDiagnosticBag diagnostics) { var syntax = GetSyntax(); return this.FindExplicitlyImplementedMethod(isOperator: false, _explicitInterfaceType, syntax.Identifier.ValueText, syntax.ExplicitInterfaceSpecifier, diagnostics); } protected override Location ReturnTypeLocation => GetSyntax().ReturnType.Location; protected override TypeSymbol ExplicitInterfaceType => _explicitInterfaceType; protected override bool HasAnyBody => _hasAnyBody; internal MethodDeclarationSyntax GetSyntax() { Debug.Assert(syntaxReferenceOpt != null); return (MethodDeclarationSyntax)syntaxReferenceOpt.GetSyntax(); } protected override void CompleteAsyncMethodChecksBetweenStartAndFinish() { if (IsPartialDefinition) { DeclaringCompilation.SymbolDeclaredEvent(this); } } public override ImmutableArray<ImmutableArray<TypeWithAnnotations>> GetTypeParameterConstraintTypes() { if (_lazyTypeParameterConstraintTypes.IsDefault) { GetTypeParameterConstraintKinds(); var diagnostics = BindingDiagnosticBag.GetInstance(); var syntax = GetSyntax(); var withTypeParametersBinder = this.DeclaringCompilation .GetBinderFactory(syntax.SyntaxTree) .GetBinder(syntax.ReturnType, syntax, this); var constraints = this.MakeTypeParameterConstraintTypes( withTypeParametersBinder, TypeParameters, syntax.TypeParameterList, syntax.ConstraintClauses, diagnostics); if (ImmutableInterlocked.InterlockedInitialize(ref _lazyTypeParameterConstraintTypes, constraints)) { this.AddDeclarationDiagnostics(diagnostics); } diagnostics.Free(); } return _lazyTypeParameterConstraintTypes; } public override ImmutableArray<TypeParameterConstraintKind> GetTypeParameterConstraintKinds() { if (_lazyTypeParameterConstraintKinds.IsDefault) { var syntax = GetSyntax(); var withTypeParametersBinder = this.DeclaringCompilation .GetBinderFactory(syntax.SyntaxTree) .GetBinder(syntax.ReturnType, syntax, this); var constraints = this.MakeTypeParameterConstraintKinds( withTypeParametersBinder, TypeParameters, syntax.TypeParameterList, syntax.ConstraintClauses); ImmutableInterlocked.InterlockedInitialize(ref _lazyTypeParameterConstraintKinds, constraints); } return _lazyTypeParameterConstraintKinds; } public override bool IsVararg { get { LazyMethodChecks(); return _lazyIsVararg; } } protected override int GetParameterCountFromSyntax() => GetSyntax().ParameterList.ParameterCount; public override RefKind RefKind { get { return _refKind; } } internal static void InitializePartialMethodParts(SourceOrdinaryMethodSymbol definition, SourceOrdinaryMethodSymbol implementation) { Debug.Assert(definition.IsPartialDefinition); Debug.Assert(implementation.IsPartialImplementation); Debug.Assert((object)definition._otherPartOfPartial == null || (object)definition._otherPartOfPartial == implementation); Debug.Assert((object)implementation._otherPartOfPartial == null || (object)implementation._otherPartOfPartial == definition); definition._otherPartOfPartial = implementation; implementation._otherPartOfPartial = definition; } /// <summary> /// If this is a partial implementation part returns the definition part and vice versa. /// </summary> internal SourceOrdinaryMethodSymbol OtherPartOfPartial { get { return _otherPartOfPartial; } } /// <summary> /// Returns true if this symbol represents a partial method definition (the part that specifies a signature but no body). /// </summary> internal bool IsPartialDefinition { get { return this.IsPartial && !_hasAnyBody && !HasExternModifier; } } /// <summary> /// Returns true if this symbol represents a partial method implementation (the part that specifies both signature and body). /// </summary> internal bool IsPartialImplementation { get { return this.IsPartial && (_hasAnyBody || HasExternModifier); } } /// <summary> /// True if this is a partial method that doesn't have an implementation part. /// </summary> internal bool IsPartialWithoutImplementation { get { return this.IsPartialDefinition && (object)_otherPartOfPartial == null; } } /// <summary> /// Returns the implementation part of a partial method definition, /// or null if this is not a partial method or it is the definition part. /// </summary> internal SourceOrdinaryMethodSymbol SourcePartialDefinition { get { return this.IsPartialImplementation ? _otherPartOfPartial : null; } } /// <summary> /// Returns the definition part of a partial method implementation, /// or null if this is not a partial method or it is the implementation part. /// </summary> internal SourceOrdinaryMethodSymbol SourcePartialImplementation { get { return this.IsPartialDefinition ? _otherPartOfPartial : null; } } public override MethodSymbol PartialDefinitionPart { get { return SourcePartialDefinition; } } public override MethodSymbol PartialImplementationPart { get { return SourcePartialImplementation; } } public sealed override bool IsExtern { get { return IsPartialDefinition ? _otherPartOfPartial?.IsExtern ?? false : HasExternModifier; } } public override string GetDocumentationCommentXml(CultureInfo preferredCulture = null, bool expandIncludes = false, CancellationToken cancellationToken = default(CancellationToken)) { ref var lazyDocComment = ref expandIncludes ? ref this.lazyExpandedDocComment : ref this.lazyDocComment; return SourceDocumentationCommentUtils.GetAndCacheDocumentationComment(SourcePartialImplementation ?? this, expandIncludes, ref lazyDocComment); } protected override SourceMemberMethodSymbol BoundAttributesSource { get { return this.SourcePartialDefinition; } } internal override OneOrMany<SyntaxList<AttributeListSyntax>> GetAttributeDeclarations() { if ((object)this.SourcePartialImplementation != null) { return OneOrMany.Create(ImmutableArray.Create(AttributeDeclarationSyntaxList, this.SourcePartialImplementation.AttributeDeclarationSyntaxList)); } else { return OneOrMany.Create(AttributeDeclarationSyntaxList); } } private SyntaxList<AttributeListSyntax> AttributeDeclarationSyntaxList { get { var sourceContainer = this.ContainingType as SourceMemberContainerTypeSymbol; if ((object)sourceContainer != null && sourceContainer.AnyMemberHasAttributes) { return this.GetSyntax().AttributeLists; } return default(SyntaxList<AttributeListSyntax>); } } internal override bool IsExpressionBodied { get { return _isExpressionBodied; } } protected override DeclarationModifiers MakeDeclarationModifiers(DeclarationModifiers allowedModifiers, BindingDiagnosticBag diagnostics) { var syntax = GetSyntax(); return ModifierUtils.MakeAndCheckNontypeMemberModifiers(syntax.Modifiers, defaultAccess: DeclarationModifiers.None, allowedModifiers, Locations[0], diagnostics, out _); } private ImmutableArray<TypeParameterSymbol> MakeTypeParameters(MethodDeclarationSyntax syntax, BindingDiagnosticBag diagnostics) { Debug.Assert(syntax.TypeParameterList != null); OverriddenMethodTypeParameterMapBase typeMap = null; if (this.IsOverride) { typeMap = new OverriddenMethodTypeParameterMap(this); } else if (this.IsExplicitInterfaceImplementation) { typeMap = new ExplicitInterfaceMethodTypeParameterMap(this); } var typeParameters = syntax.TypeParameterList.Parameters; var result = ArrayBuilder<TypeParameterSymbol>.GetInstance(); for (int ordinal = 0; ordinal < typeParameters.Count; ordinal++) { var parameter = typeParameters[ordinal]; if (parameter.VarianceKeyword.Kind() != SyntaxKind.None) { diagnostics.Add(ErrorCode.ERR_IllegalVarianceSyntax, parameter.VarianceKeyword.GetLocation()); } var identifier = parameter.Identifier; var location = identifier.GetLocation(); var name = identifier.ValueText; // Note: It is not an error to have a type parameter named the same as its enclosing method: void M<M>() {} for (int i = 0; i < result.Count; i++) { if (name == result[i].Name) { diagnostics.Add(ErrorCode.ERR_DuplicateTypeParameter, location, name); break; } } SourceMemberContainerTypeSymbol.ReportTypeNamedRecord(identifier.Text, this.DeclaringCompilation, diagnostics.DiagnosticBag, location); var tpEnclosing = ContainingType.FindEnclosingTypeParameter(name); if ((object)tpEnclosing != null) { // Type parameter '{0}' has the same name as the type parameter from outer type '{1}' diagnostics.Add(ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter, location, name, tpEnclosing.ContainingType); } var syntaxRefs = ImmutableArray.Create(parameter.GetReference()); var locations = ImmutableArray.Create(location); var typeParameter = (typeMap != null) ? (TypeParameterSymbol)new SourceOverridingMethodTypeParameterSymbol( typeMap, name, ordinal, locations, syntaxRefs) : new SourceMethodTypeParameterSymbol( this, name, ordinal, locations, syntaxRefs); result.Add(typeParameter); } return result.ToImmutableAndFree(); } internal override void ForceComplete(SourceLocation locationOpt, CancellationToken cancellationToken) { var implementingPart = this.SourcePartialImplementation; if ((object)implementingPart != null) { implementingPart.ForceComplete(locationOpt, cancellationToken); } base.ForceComplete(locationOpt, cancellationToken); } internal override bool IsDefinedInSourceTree( SyntaxTree tree, TextSpan? definedWithinSpan, CancellationToken cancellationToken = default(CancellationToken)) { // Since only the declaring (and not the implementing) part of a partial method appears in the member // list, we need to ensure we complete the implementation part when needed. return base.IsDefinedInSourceTree(tree, definedWithinSpan, cancellationToken) || this.SourcePartialImplementation?.IsDefinedInSourceTree(tree, definedWithinSpan, cancellationToken) == true; } protected override void CheckConstraintsForExplicitInterfaceType(ConversionsBase conversions, BindingDiagnosticBag diagnostics) { if ((object)_explicitInterfaceType != null) { var syntax = this.GetSyntax(); Debug.Assert(syntax.ExplicitInterfaceSpecifier != null); _explicitInterfaceType.CheckAllConstraints(DeclaringCompilation, conversions, new SourceLocation(syntax.ExplicitInterfaceSpecifier.Name), diagnostics); } } protected override void PartialMethodChecks(BindingDiagnosticBag diagnostics) { var implementingPart = this.SourcePartialImplementation; if ((object)implementingPart != null) { PartialMethodChecks(this, implementingPart, diagnostics); } } /// <summary> /// Report differences between the defining and implementing /// parts of a partial method. Diagnostics are reported on the /// implementing part, matching Dev10 behavior. /// </summary> private static void PartialMethodChecks(SourceOrdinaryMethodSymbol definition, SourceOrdinaryMethodSymbol implementation, BindingDiagnosticBag diagnostics) { Debug.Assert(!ReferenceEquals(definition, implementation)); MethodSymbol constructedDefinition = definition.ConstructIfGeneric(TypeMap.TypeParametersAsTypeSymbolsWithIgnoredAnnotations(implementation.TypeParameters)); bool hasTypeDifferences = !constructedDefinition.ReturnTypeWithAnnotations.Equals(implementation.ReturnTypeWithAnnotations, TypeCompareKind.AllIgnoreOptions); if (hasTypeDifferences) { diagnostics.Add(ErrorCode.ERR_PartialMethodReturnTypeDifference, implementation.Locations[0]); } else if (MemberSignatureComparer.ConsideringTupleNamesCreatesDifference(definition, implementation)) { hasTypeDifferences = true; diagnostics.Add(ErrorCode.ERR_PartialMethodInconsistentTupleNames, implementation.Locations[0], definition, implementation); } if (definition.RefKind != implementation.RefKind) { diagnostics.Add(ErrorCode.ERR_PartialMethodRefReturnDifference, implementation.Locations[0]); } if (definition.IsStatic != implementation.IsStatic) { diagnostics.Add(ErrorCode.ERR_PartialMethodStaticDifference, implementation.Locations[0]); } if (definition.IsDeclaredReadOnly != implementation.IsDeclaredReadOnly) { diagnostics.Add(ErrorCode.ERR_PartialMethodReadOnlyDifference, implementation.Locations[0]); } if (definition.IsExtensionMethod != implementation.IsExtensionMethod) { diagnostics.Add(ErrorCode.ERR_PartialMethodExtensionDifference, implementation.Locations[0]); } if (definition.IsUnsafe != implementation.IsUnsafe && definition.CompilationAllowsUnsafe()) // Don't cascade. { diagnostics.Add(ErrorCode.ERR_PartialMethodUnsafeDifference, implementation.Locations[0]); } if (definition.IsParams() != implementation.IsParams()) { diagnostics.Add(ErrorCode.ERR_PartialMethodParamsDifference, implementation.Locations[0]); } if (definition.HasExplicitAccessModifier != implementation.HasExplicitAccessModifier || definition.DeclaredAccessibility != implementation.DeclaredAccessibility) { diagnostics.Add(ErrorCode.ERR_PartialMethodAccessibilityDifference, implementation.Locations[0]); } if (definition.IsVirtual != implementation.IsVirtual || definition.IsOverride != implementation.IsOverride || definition.IsSealed != implementation.IsSealed || definition.IsNew != implementation.IsNew) { diagnostics.Add(ErrorCode.ERR_PartialMethodExtendedModDifference, implementation.Locations[0]); } PartialMethodConstraintsChecks(definition, implementation, diagnostics); if (SourceMemberContainerTypeSymbol.CheckValidNullableMethodOverride( implementation.DeclaringCompilation, constructedDefinition, implementation, diagnostics, static (diagnostics, implementedMethod, implementingMethod, topLevel, arg) => { // report only if this is an unsafe *nullability* difference diagnostics.Add(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnPartial, implementingMethod.Locations[0]); }, static (diagnostics, implementedMethod, implementingMethod, implementingParameter, blameAttributes, arg) => { diagnostics.Add(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnPartial, implementingMethod.Locations[0], new FormattedSymbol(implementingParameter, SymbolDisplayFormat.ShortFormat)); }, extraArgument: (object)null)) { hasTypeDifferences = true; } if ((!hasTypeDifferences && !MemberSignatureComparer.PartialMethodsStrictComparer.Equals(definition, implementation)) || hasDifferencesInParameterOrTypeParameterName(definition, implementation)) { diagnostics.Add(ErrorCode.WRN_PartialMethodTypeDifference, implementation.Locations[0], new FormattedSymbol(definition, SymbolDisplayFormat.MinimallyQualifiedFormat), new FormattedSymbol(implementation, SymbolDisplayFormat.MinimallyQualifiedFormat)); } static bool hasDifferencesInParameterOrTypeParameterName(SourceOrdinaryMethodSymbol definition, SourceOrdinaryMethodSymbol implementation) { return !definition.Parameters.SequenceEqual(implementation.Parameters, (a, b) => a.Name == b.Name) || !definition.TypeParameters.SequenceEqual(implementation.TypeParameters, (a, b) => a.Name == b.Name); } } private static void PartialMethodConstraintsChecks(SourceOrdinaryMethodSymbol definition, SourceOrdinaryMethodSymbol implementation, BindingDiagnosticBag diagnostics) { Debug.Assert(!ReferenceEquals(definition, implementation)); Debug.Assert(definition.Arity == implementation.Arity); var typeParameters1 = definition.TypeParameters; int arity = typeParameters1.Length; if (arity == 0) { return; } var typeParameters2 = implementation.TypeParameters; var indexedTypeParameters = IndexedTypeParameterSymbol.Take(arity); var typeMap1 = new TypeMap(typeParameters1, indexedTypeParameters, allowAlpha: true); var typeMap2 = new TypeMap(typeParameters2, indexedTypeParameters, allowAlpha: true); // Report any mismatched method constraints. for (int i = 0; i < arity; i++) { var typeParameter1 = typeParameters1[i]; var typeParameter2 = typeParameters2[i]; if (!MemberSignatureComparer.HaveSameConstraints(typeParameter1, typeMap1, typeParameter2, typeMap2)) { diagnostics.Add(ErrorCode.ERR_PartialMethodInconsistentConstraints, implementation.Locations[0], implementation, typeParameter2.Name); } else if (!MemberSignatureComparer.HaveSameNullabilityInConstraints(typeParameter1, typeMap1, typeParameter2, typeMap2)) { diagnostics.Add(ErrorCode.WRN_NullabilityMismatchInConstraintsOnPartialImplementation, implementation.Locations[0], implementation, typeParameter2.Name); } } } internal override bool CallsAreOmitted(SyntaxTree syntaxTree) { if (this.IsPartialWithoutImplementation) { return true; } return base.CallsAreOmitted(syntaxTree); } internal override bool GenerateDebugInfo => !IsAsync && !IsIterator; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal sealed class SourceOrdinaryMethodSymbol : SourceOrdinaryMethodSymbolBase { private readonly TypeSymbol _explicitInterfaceType; private readonly bool _isExpressionBodied; private readonly bool _hasAnyBody; private readonly RefKind _refKind; private bool _lazyIsVararg; /// <summary> /// A collection of type parameter constraint types, populated when /// constraint types for the first type parameter is requested. /// Initialized in two steps. Hold a copy if accessing during initialization. /// </summary> private ImmutableArray<ImmutableArray<TypeWithAnnotations>> _lazyTypeParameterConstraintTypes; /// <summary> /// A collection of type parameter constraint kinds, populated when /// constraint kinds for the first type parameter is requested. /// Initialized in two steps. Hold a copy if accessing during initialization. /// </summary> private ImmutableArray<TypeParameterConstraintKind> _lazyTypeParameterConstraintKinds; /// <summary> /// If this symbol represents a partial method definition or implementation part, its other part (if any). /// This should be set, if at all, before this symbol appears among the members of its owner. /// The implementation part is not listed among the "members" of the enclosing type. /// </summary> private SourceOrdinaryMethodSymbol _otherPartOfPartial; public static SourceOrdinaryMethodSymbol CreateMethodSymbol( NamedTypeSymbol containingType, Binder bodyBinder, MethodDeclarationSyntax syntax, bool isNullableAnalysisEnabled, BindingDiagnosticBag diagnostics) { var interfaceSpecifier = syntax.ExplicitInterfaceSpecifier; var nameToken = syntax.Identifier; TypeSymbol explicitInterfaceType; var name = ExplicitInterfaceHelpers.GetMemberNameAndInterfaceSymbol(bodyBinder, interfaceSpecifier, nameToken.ValueText, diagnostics, out explicitInterfaceType, aliasQualifierOpt: out _); var location = new SourceLocation(nameToken); var methodKind = interfaceSpecifier == null ? MethodKind.Ordinary : MethodKind.ExplicitInterfaceImplementation; return new SourceOrdinaryMethodSymbol(containingType, explicitInterfaceType, name, location, syntax, methodKind, isNullableAnalysisEnabled, diagnostics); } private SourceOrdinaryMethodSymbol( NamedTypeSymbol containingType, TypeSymbol explicitInterfaceType, string name, Location location, MethodDeclarationSyntax syntax, MethodKind methodKind, bool isNullableAnalysisEnabled, BindingDiagnosticBag diagnostics) : base(containingType, name, location, syntax, methodKind, isIterator: SyntaxFacts.HasYieldOperations(syntax.Body), isExtensionMethod: syntax.ParameterList.Parameters.FirstOrDefault() is ParameterSyntax firstParam && !firstParam.IsArgList && firstParam.Modifiers.Any(SyntaxKind.ThisKeyword), isPartial: syntax.Modifiers.IndexOf(SyntaxKind.PartialKeyword) < 0, isReadOnly: false, hasBody: syntax.Body != null || syntax.ExpressionBody != null, isNullableAnalysisEnabled: isNullableAnalysisEnabled, diagnostics) { Debug.Assert(diagnostics.DiagnosticBag is object); _explicitInterfaceType = explicitInterfaceType; bool hasBlockBody = syntax.Body != null; _isExpressionBodied = !hasBlockBody && syntax.ExpressionBody != null; bool hasBody = hasBlockBody || _isExpressionBodied; _hasAnyBody = hasBody; _refKind = syntax.ReturnType.GetRefKind(); CheckForBlockAndExpressionBody( syntax.Body, syntax.ExpressionBody, syntax, diagnostics); } protected override ImmutableArray<TypeParameterSymbol> MakeTypeParameters(CSharpSyntaxNode node, BindingDiagnosticBag diagnostics) { var syntax = (MethodDeclarationSyntax)node; if (syntax.Arity == 0) { ReportErrorIfHasConstraints(syntax.ConstraintClauses, diagnostics.DiagnosticBag); return ImmutableArray<TypeParameterSymbol>.Empty; } else { return MakeTypeParameters(syntax, diagnostics); } } protected override (TypeWithAnnotations ReturnType, ImmutableArray<ParameterSymbol> Parameters, bool IsVararg, ImmutableArray<TypeParameterConstraintClause> DeclaredConstraintsForOverrideOrImplementation) MakeParametersAndBindReturnType(BindingDiagnosticBag diagnostics) { var syntax = GetSyntax(); var withTypeParamsBinder = this.DeclaringCompilation.GetBinderFactory(syntax.SyntaxTree).GetBinder(syntax.ReturnType, syntax, this); SyntaxToken arglistToken; // Constraint checking for parameter and return types must be delayed until // the method has been added to the containing type member list since // evaluating the constraints may depend on accessing this method from // the container (comparing this method to others to find overrides for // instance). Constraints are checked in AfterAddingTypeMembersChecks. var signatureBinder = withTypeParamsBinder.WithAdditionalFlagsAndContainingMemberOrLambda(BinderFlags.SuppressConstraintChecks, this); ImmutableArray<ParameterSymbol> parameters = ParameterHelpers.MakeParameters( signatureBinder, this, syntax.ParameterList, out arglistToken, allowRefOrOut: true, allowThis: true, addRefReadOnlyModifier: IsVirtual || IsAbstract, diagnostics: diagnostics); _lazyIsVararg = (arglistToken.Kind() == SyntaxKind.ArgListKeyword); RefKind refKind; var returnTypeSyntax = syntax.ReturnType.SkipRef(out refKind); TypeWithAnnotations returnType = signatureBinder.BindType(returnTypeSyntax, diagnostics); // span-like types are returnable in general if (returnType.IsRestrictedType(ignoreSpanLikeTypes: true)) { if (returnType.SpecialType == SpecialType.System_TypedReference && (this.ContainingType.SpecialType == SpecialType.System_TypedReference || this.ContainingType.SpecialType == SpecialType.System_ArgIterator)) { // Two special cases: methods in the special types TypedReference and ArgIterator are allowed to return TypedReference } else { // The return type of a method, delegate, or function pointer cannot be '{0}' diagnostics.Add(ErrorCode.ERR_MethodReturnCantBeRefAny, syntax.ReturnType.Location, returnType.Type); } } Debug.Assert(this.RefKind == RefKind.None || !returnType.IsVoidType() || returnTypeSyntax.HasErrors); ImmutableArray<TypeParameterConstraintClause> declaredConstraints = default; if (this.Arity != 0 && (syntax.ExplicitInterfaceSpecifier != null || IsOverride)) { // When a generic method overrides a generic method declared in a base class, or is an // explicit interface member implementation of a method in a base interface, the method // shall not specify any type-parameter-constraints-clauses, except for a struct, class, or default constraint. // In these cases, the type parameters of the method inherit constraints from the method being overridden or // implemented. if (syntax.ConstraintClauses.Count > 0) { Binder.CheckFeatureAvailability(syntax.SyntaxTree, MessageID.IDS_OverrideWithConstraints, diagnostics, syntax.ConstraintClauses[0].WhereKeyword.GetLocation()); declaredConstraints = signatureBinder.WithAdditionalFlags(BinderFlags.GenericConstraintsClause | BinderFlags.SuppressConstraintChecks). BindTypeParameterConstraintClauses(this, TypeParameters, syntax.TypeParameterList, syntax.ConstraintClauses, diagnostics, performOnlyCycleSafeValidation: false, isForOverride: true); Debug.Assert(declaredConstraints.All(clause => clause.ConstraintTypes.IsEmpty)); } // Force resolution of nullable type parameter used in the signature of an override or explicit interface implementation // based on constraints specified by the declaration. foreach (var param in parameters) { forceMethodTypeParameters(param.TypeWithAnnotations, this, declaredConstraints); } forceMethodTypeParameters(returnType, this, declaredConstraints); } return (returnType, parameters, _lazyIsVararg, declaredConstraints); static void forceMethodTypeParameters(TypeWithAnnotations type, SourceOrdinaryMethodSymbol method, ImmutableArray<TypeParameterConstraintClause> declaredConstraints) { type.VisitType(null, (type, args, unused2) => { if (type.DefaultType is TypeParameterSymbol typeParameterSymbol && typeParameterSymbol.DeclaringMethod == (object)args.method) { var asValueType = args.declaredConstraints.IsDefault || (args.declaredConstraints[typeParameterSymbol.Ordinal].Constraints & (TypeParameterConstraintKind.ReferenceType | TypeParameterConstraintKind.Default)) == 0; type.TryForceResolve(asValueType); } return false; }, typePredicate: null, arg: (method, declaredConstraints), canDigThroughNullable: false, useDefaultType: true); } } protected override void ExtensionMethodChecks(BindingDiagnosticBag diagnostics) { // errors relevant for extension methods if (IsExtensionMethod) { var syntax = GetSyntax(); var location = locations[0]; var parameter0Type = this.Parameters[0].TypeWithAnnotations; var parameter0RefKind = this.Parameters[0].RefKind; if (!parameter0Type.Type.IsValidExtensionParameterType()) { // Duplicate Dev10 behavior by selecting the parameter type. var parameterSyntax = syntax.ParameterList.Parameters[0]; Debug.Assert(parameterSyntax.Type != null); var loc = parameterSyntax.Type.Location; diagnostics.Add(ErrorCode.ERR_BadTypeforThis, loc, parameter0Type.Type); } else if (parameter0RefKind == RefKind.Ref && !parameter0Type.Type.IsValueType) { diagnostics.Add(ErrorCode.ERR_RefExtensionMustBeValueTypeOrConstrainedToOne, location, Name); } else if (parameter0RefKind == RefKind.In && parameter0Type.TypeKind != TypeKind.Struct) { diagnostics.Add(ErrorCode.ERR_InExtensionMustBeValueType, location, Name); } else if ((object)ContainingType.ContainingType != null) { diagnostics.Add(ErrorCode.ERR_ExtensionMethodsDecl, location, ContainingType.Name); } else if (!ContainingType.IsScriptClass && !(ContainingType.IsStatic && ContainingType.Arity == 0)) { // Duplicate Dev10 behavior by selecting the containing type identifier. However if there // is no containing type (in the interactive case for instance), select the method identifier. var typeDecl = syntax.Parent as TypeDeclarationSyntax; var identifier = (typeDecl != null) ? typeDecl.Identifier : syntax.Identifier; var loc = identifier.GetLocation(); diagnostics.Add(ErrorCode.ERR_BadExtensionAgg, loc); } else if (!IsStatic) { diagnostics.Add(ErrorCode.ERR_BadExtensionMeth, location); } else { // Verify ExtensionAttribute is available. var attributeConstructor = Binder.GetWellKnownTypeMember(DeclaringCompilation, WellKnownMember.System_Runtime_CompilerServices_ExtensionAttribute__ctor, out var useSiteInfo); Location thisLocation = syntax.ParameterList.Parameters[0].Modifiers.FirstOrDefault(SyntaxKind.ThisKeyword).GetLocation(); if ((object)attributeConstructor == null) { var memberDescriptor = WellKnownMembers.GetDescriptor(WellKnownMember.System_Runtime_CompilerServices_ExtensionAttribute__ctor); // do not use Binder.ReportUseSiteErrorForAttributeCtor in this case, because we'll need to report a special error id, not a generic use site error. diagnostics.Add( ErrorCode.ERR_ExtensionAttrNotFound, thisLocation, memberDescriptor.DeclaringTypeMetadataName); } else { diagnostics.Add(useSiteInfo, thisLocation); } } } } protected override MethodSymbol FindExplicitlyImplementedMethod(BindingDiagnosticBag diagnostics) { var syntax = GetSyntax(); return this.FindExplicitlyImplementedMethod(isOperator: false, _explicitInterfaceType, syntax.Identifier.ValueText, syntax.ExplicitInterfaceSpecifier, diagnostics); } protected override Location ReturnTypeLocation => GetSyntax().ReturnType.Location; protected override TypeSymbol ExplicitInterfaceType => _explicitInterfaceType; protected override bool HasAnyBody => _hasAnyBody; internal MethodDeclarationSyntax GetSyntax() { Debug.Assert(syntaxReferenceOpt != null); return (MethodDeclarationSyntax)syntaxReferenceOpt.GetSyntax(); } protected override void CompleteAsyncMethodChecksBetweenStartAndFinish() { if (IsPartialDefinition) { DeclaringCompilation.SymbolDeclaredEvent(this); } } public override ImmutableArray<ImmutableArray<TypeWithAnnotations>> GetTypeParameterConstraintTypes() { if (_lazyTypeParameterConstraintTypes.IsDefault) { GetTypeParameterConstraintKinds(); var diagnostics = BindingDiagnosticBag.GetInstance(); var syntax = GetSyntax(); var withTypeParametersBinder = this.DeclaringCompilation .GetBinderFactory(syntax.SyntaxTree) .GetBinder(syntax.ReturnType, syntax, this); var constraints = this.MakeTypeParameterConstraintTypes( withTypeParametersBinder, TypeParameters, syntax.TypeParameterList, syntax.ConstraintClauses, diagnostics); if (ImmutableInterlocked.InterlockedInitialize(ref _lazyTypeParameterConstraintTypes, constraints)) { this.AddDeclarationDiagnostics(diagnostics); } diagnostics.Free(); } return _lazyTypeParameterConstraintTypes; } public override ImmutableArray<TypeParameterConstraintKind> GetTypeParameterConstraintKinds() { if (_lazyTypeParameterConstraintKinds.IsDefault) { var syntax = GetSyntax(); var withTypeParametersBinder = this.DeclaringCompilation .GetBinderFactory(syntax.SyntaxTree) .GetBinder(syntax.ReturnType, syntax, this); var constraints = this.MakeTypeParameterConstraintKinds( withTypeParametersBinder, TypeParameters, syntax.TypeParameterList, syntax.ConstraintClauses); ImmutableInterlocked.InterlockedInitialize(ref _lazyTypeParameterConstraintKinds, constraints); } return _lazyTypeParameterConstraintKinds; } public override bool IsVararg { get { LazyMethodChecks(); return _lazyIsVararg; } } protected override int GetParameterCountFromSyntax() => GetSyntax().ParameterList.ParameterCount; public override RefKind RefKind { get { return _refKind; } } internal static void InitializePartialMethodParts(SourceOrdinaryMethodSymbol definition, SourceOrdinaryMethodSymbol implementation) { Debug.Assert(definition.IsPartialDefinition); Debug.Assert(implementation.IsPartialImplementation); Debug.Assert((object)definition._otherPartOfPartial == null || (object)definition._otherPartOfPartial == implementation); Debug.Assert((object)implementation._otherPartOfPartial == null || (object)implementation._otherPartOfPartial == definition); definition._otherPartOfPartial = implementation; implementation._otherPartOfPartial = definition; } /// <summary> /// If this is a partial implementation part returns the definition part and vice versa. /// </summary> internal SourceOrdinaryMethodSymbol OtherPartOfPartial { get { return _otherPartOfPartial; } } /// <summary> /// Returns true if this symbol represents a partial method definition (the part that specifies a signature but no body). /// </summary> internal bool IsPartialDefinition { get { return this.IsPartial && !_hasAnyBody && !HasExternModifier; } } /// <summary> /// Returns true if this symbol represents a partial method implementation (the part that specifies both signature and body). /// </summary> internal bool IsPartialImplementation { get { return this.IsPartial && (_hasAnyBody || HasExternModifier); } } /// <summary> /// True if this is a partial method that doesn't have an implementation part. /// </summary> internal bool IsPartialWithoutImplementation { get { return this.IsPartialDefinition && (object)_otherPartOfPartial == null; } } /// <summary> /// Returns the implementation part of a partial method definition, /// or null if this is not a partial method or it is the definition part. /// </summary> internal SourceOrdinaryMethodSymbol SourcePartialDefinition { get { return this.IsPartialImplementation ? _otherPartOfPartial : null; } } /// <summary> /// Returns the definition part of a partial method implementation, /// or null if this is not a partial method or it is the implementation part. /// </summary> internal SourceOrdinaryMethodSymbol SourcePartialImplementation { get { return this.IsPartialDefinition ? _otherPartOfPartial : null; } } public override MethodSymbol PartialDefinitionPart { get { return SourcePartialDefinition; } } public override MethodSymbol PartialImplementationPart { get { return SourcePartialImplementation; } } public sealed override bool IsExtern { get { return IsPartialDefinition ? _otherPartOfPartial?.IsExtern ?? false : HasExternModifier; } } public override string GetDocumentationCommentXml(CultureInfo preferredCulture = null, bool expandIncludes = false, CancellationToken cancellationToken = default(CancellationToken)) { ref var lazyDocComment = ref expandIncludes ? ref this.lazyExpandedDocComment : ref this.lazyDocComment; return SourceDocumentationCommentUtils.GetAndCacheDocumentationComment(this, expandIncludes, ref lazyDocComment); } protected override SourceMemberMethodSymbol BoundAttributesSource { get { return this.SourcePartialDefinition; } } internal override OneOrMany<SyntaxList<AttributeListSyntax>> GetAttributeDeclarations() { if ((object)this.SourcePartialImplementation != null) { return OneOrMany.Create(ImmutableArray.Create(AttributeDeclarationSyntaxList, this.SourcePartialImplementation.AttributeDeclarationSyntaxList)); } else { return OneOrMany.Create(AttributeDeclarationSyntaxList); } } private SyntaxList<AttributeListSyntax> AttributeDeclarationSyntaxList { get { var sourceContainer = this.ContainingType as SourceMemberContainerTypeSymbol; if ((object)sourceContainer != null && sourceContainer.AnyMemberHasAttributes) { return this.GetSyntax().AttributeLists; } return default(SyntaxList<AttributeListSyntax>); } } internal override bool IsExpressionBodied { get { return _isExpressionBodied; } } protected override DeclarationModifiers MakeDeclarationModifiers(DeclarationModifiers allowedModifiers, BindingDiagnosticBag diagnostics) { var syntax = GetSyntax(); return ModifierUtils.MakeAndCheckNontypeMemberModifiers(syntax.Modifiers, defaultAccess: DeclarationModifiers.None, allowedModifiers, Locations[0], diagnostics, out _); } private ImmutableArray<TypeParameterSymbol> MakeTypeParameters(MethodDeclarationSyntax syntax, BindingDiagnosticBag diagnostics) { Debug.Assert(syntax.TypeParameterList != null); OverriddenMethodTypeParameterMapBase typeMap = null; if (this.IsOverride) { typeMap = new OverriddenMethodTypeParameterMap(this); } else if (this.IsExplicitInterfaceImplementation) { typeMap = new ExplicitInterfaceMethodTypeParameterMap(this); } var typeParameters = syntax.TypeParameterList.Parameters; var result = ArrayBuilder<TypeParameterSymbol>.GetInstance(); for (int ordinal = 0; ordinal < typeParameters.Count; ordinal++) { var parameter = typeParameters[ordinal]; if (parameter.VarianceKeyword.Kind() != SyntaxKind.None) { diagnostics.Add(ErrorCode.ERR_IllegalVarianceSyntax, parameter.VarianceKeyword.GetLocation()); } var identifier = parameter.Identifier; var location = identifier.GetLocation(); var name = identifier.ValueText; // Note: It is not an error to have a type parameter named the same as its enclosing method: void M<M>() {} for (int i = 0; i < result.Count; i++) { if (name == result[i].Name) { diagnostics.Add(ErrorCode.ERR_DuplicateTypeParameter, location, name); break; } } SourceMemberContainerTypeSymbol.ReportTypeNamedRecord(identifier.Text, this.DeclaringCompilation, diagnostics.DiagnosticBag, location); var tpEnclosing = ContainingType.FindEnclosingTypeParameter(name); if ((object)tpEnclosing != null) { // Type parameter '{0}' has the same name as the type parameter from outer type '{1}' diagnostics.Add(ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter, location, name, tpEnclosing.ContainingType); } var syntaxRefs = ImmutableArray.Create(parameter.GetReference()); var locations = ImmutableArray.Create(location); var typeParameter = (typeMap != null) ? (TypeParameterSymbol)new SourceOverridingMethodTypeParameterSymbol( typeMap, name, ordinal, locations, syntaxRefs) : new SourceMethodTypeParameterSymbol( this, name, ordinal, locations, syntaxRefs); result.Add(typeParameter); } return result.ToImmutableAndFree(); } internal override void ForceComplete(SourceLocation locationOpt, CancellationToken cancellationToken) { var implementingPart = this.SourcePartialImplementation; if ((object)implementingPart != null) { implementingPart.ForceComplete(locationOpt, cancellationToken); } base.ForceComplete(locationOpt, cancellationToken); } internal override bool IsDefinedInSourceTree( SyntaxTree tree, TextSpan? definedWithinSpan, CancellationToken cancellationToken = default(CancellationToken)) { // Since only the declaring (and not the implementing) part of a partial method appears in the member // list, we need to ensure we complete the implementation part when needed. return base.IsDefinedInSourceTree(tree, definedWithinSpan, cancellationToken) || this.SourcePartialImplementation?.IsDefinedInSourceTree(tree, definedWithinSpan, cancellationToken) == true; } protected override void CheckConstraintsForExplicitInterfaceType(ConversionsBase conversions, BindingDiagnosticBag diagnostics) { if ((object)_explicitInterfaceType != null) { var syntax = this.GetSyntax(); Debug.Assert(syntax.ExplicitInterfaceSpecifier != null); _explicitInterfaceType.CheckAllConstraints(DeclaringCompilation, conversions, new SourceLocation(syntax.ExplicitInterfaceSpecifier.Name), diagnostics); } } protected override void PartialMethodChecks(BindingDiagnosticBag diagnostics) { var implementingPart = this.SourcePartialImplementation; if ((object)implementingPart != null) { PartialMethodChecks(this, implementingPart, diagnostics); } } /// <summary> /// Report differences between the defining and implementing /// parts of a partial method. Diagnostics are reported on the /// implementing part, matching Dev10 behavior. /// </summary> private static void PartialMethodChecks(SourceOrdinaryMethodSymbol definition, SourceOrdinaryMethodSymbol implementation, BindingDiagnosticBag diagnostics) { Debug.Assert(!ReferenceEquals(definition, implementation)); MethodSymbol constructedDefinition = definition.ConstructIfGeneric(TypeMap.TypeParametersAsTypeSymbolsWithIgnoredAnnotations(implementation.TypeParameters)); bool hasTypeDifferences = !constructedDefinition.ReturnTypeWithAnnotations.Equals(implementation.ReturnTypeWithAnnotations, TypeCompareKind.AllIgnoreOptions); if (hasTypeDifferences) { diagnostics.Add(ErrorCode.ERR_PartialMethodReturnTypeDifference, implementation.Locations[0]); } else if (MemberSignatureComparer.ConsideringTupleNamesCreatesDifference(definition, implementation)) { hasTypeDifferences = true; diagnostics.Add(ErrorCode.ERR_PartialMethodInconsistentTupleNames, implementation.Locations[0], definition, implementation); } if (definition.RefKind != implementation.RefKind) { diagnostics.Add(ErrorCode.ERR_PartialMethodRefReturnDifference, implementation.Locations[0]); } if (definition.IsStatic != implementation.IsStatic) { diagnostics.Add(ErrorCode.ERR_PartialMethodStaticDifference, implementation.Locations[0]); } if (definition.IsDeclaredReadOnly != implementation.IsDeclaredReadOnly) { diagnostics.Add(ErrorCode.ERR_PartialMethodReadOnlyDifference, implementation.Locations[0]); } if (definition.IsExtensionMethod != implementation.IsExtensionMethod) { diagnostics.Add(ErrorCode.ERR_PartialMethodExtensionDifference, implementation.Locations[0]); } if (definition.IsUnsafe != implementation.IsUnsafe && definition.CompilationAllowsUnsafe()) // Don't cascade. { diagnostics.Add(ErrorCode.ERR_PartialMethodUnsafeDifference, implementation.Locations[0]); } if (definition.IsParams() != implementation.IsParams()) { diagnostics.Add(ErrorCode.ERR_PartialMethodParamsDifference, implementation.Locations[0]); } if (definition.HasExplicitAccessModifier != implementation.HasExplicitAccessModifier || definition.DeclaredAccessibility != implementation.DeclaredAccessibility) { diagnostics.Add(ErrorCode.ERR_PartialMethodAccessibilityDifference, implementation.Locations[0]); } if (definition.IsVirtual != implementation.IsVirtual || definition.IsOverride != implementation.IsOverride || definition.IsSealed != implementation.IsSealed || definition.IsNew != implementation.IsNew) { diagnostics.Add(ErrorCode.ERR_PartialMethodExtendedModDifference, implementation.Locations[0]); } PartialMethodConstraintsChecks(definition, implementation, diagnostics); if (SourceMemberContainerTypeSymbol.CheckValidNullableMethodOverride( implementation.DeclaringCompilation, constructedDefinition, implementation, diagnostics, static (diagnostics, implementedMethod, implementingMethod, topLevel, arg) => { // report only if this is an unsafe *nullability* difference diagnostics.Add(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnPartial, implementingMethod.Locations[0]); }, static (diagnostics, implementedMethod, implementingMethod, implementingParameter, blameAttributes, arg) => { diagnostics.Add(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnPartial, implementingMethod.Locations[0], new FormattedSymbol(implementingParameter, SymbolDisplayFormat.ShortFormat)); }, extraArgument: (object)null)) { hasTypeDifferences = true; } if ((!hasTypeDifferences && !MemberSignatureComparer.PartialMethodsStrictComparer.Equals(definition, implementation)) || hasDifferencesInParameterOrTypeParameterName(definition, implementation)) { diagnostics.Add(ErrorCode.WRN_PartialMethodTypeDifference, implementation.Locations[0], new FormattedSymbol(definition, SymbolDisplayFormat.MinimallyQualifiedFormat), new FormattedSymbol(implementation, SymbolDisplayFormat.MinimallyQualifiedFormat)); } static bool hasDifferencesInParameterOrTypeParameterName(SourceOrdinaryMethodSymbol definition, SourceOrdinaryMethodSymbol implementation) { return !definition.Parameters.SequenceEqual(implementation.Parameters, (a, b) => a.Name == b.Name) || !definition.TypeParameters.SequenceEqual(implementation.TypeParameters, (a, b) => a.Name == b.Name); } } private static void PartialMethodConstraintsChecks(SourceOrdinaryMethodSymbol definition, SourceOrdinaryMethodSymbol implementation, BindingDiagnosticBag diagnostics) { Debug.Assert(!ReferenceEquals(definition, implementation)); Debug.Assert(definition.Arity == implementation.Arity); var typeParameters1 = definition.TypeParameters; int arity = typeParameters1.Length; if (arity == 0) { return; } var typeParameters2 = implementation.TypeParameters; var indexedTypeParameters = IndexedTypeParameterSymbol.Take(arity); var typeMap1 = new TypeMap(typeParameters1, indexedTypeParameters, allowAlpha: true); var typeMap2 = new TypeMap(typeParameters2, indexedTypeParameters, allowAlpha: true); // Report any mismatched method constraints. for (int i = 0; i < arity; i++) { var typeParameter1 = typeParameters1[i]; var typeParameter2 = typeParameters2[i]; if (!MemberSignatureComparer.HaveSameConstraints(typeParameter1, typeMap1, typeParameter2, typeMap2)) { diagnostics.Add(ErrorCode.ERR_PartialMethodInconsistentConstraints, implementation.Locations[0], implementation, typeParameter2.Name); } else if (!MemberSignatureComparer.HaveSameNullabilityInConstraints(typeParameter1, typeMap1, typeParameter2, typeMap2)) { diagnostics.Add(ErrorCode.WRN_NullabilityMismatchInConstraintsOnPartialImplementation, implementation.Locations[0], implementation, typeParameter2.Name); } } } internal override bool CallsAreOmitted(SyntaxTree syntaxTree) { if (this.IsPartialWithoutImplementation) { return true; } return base.CallsAreOmitted(syntaxTree); } internal override bool GenerateDebugInfo => !IsAsync && !IsIterator; } }
1
dotnet/roslyn
56,419
Fix partial method doc comments
Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
RikkiGibson
"2021-09-15T20:47:39Z"
"2021-09-21T23:49:10Z"
0f60b3e9446f5d0fc14a570998c81a5d6c40cc23
8cda7462843d43d9b72039eede2f4cb43126cac2
Fix partial method doc comments. Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
./src/Compilers/CSharp/Test/Symbol/DocumentationComments/DocumentationCommentCompilerTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Threading; using System.Xml; using System.Xml.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class DocumentationCommentCompilerTests : CSharpTestBase { public static CSharpCompilation CreateCompilationUtil( CSharpTestSource source, IEnumerable<MetadataReference> references = null, CSharpCompilationOptions options = null, string assemblyName = "Test") => CreateCompilation( source, references, targetFramework: TargetFramework.Mscorlib40, options: (options ?? TestOptions.ReleaseDll).WithXmlReferenceResolver(XmlFileResolver.Default), parseOptions: TestOptions.RegularWithDocumentationComments, assemblyName: assemblyName); #region Single-line styleWRN_UnqualifiedNestedTypeInCref [Fact] public void SingleLine_OneLine() { var source = @" /// <summary>Text</summary> public class C { } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <summary>Text</summary> </member> </members> </doc> ".Trim(); Assert.Equal(expected, actual); } [Fact] public void SingleLine_MultipleLines() { var source = @" /// <summary> /// Text /// </summary> public class C { } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <summary> Text </summary> </member> </members> </doc> ".Trim(); Assert.Equal(expected, actual); } [Fact] public void SingleLine_EmptyOneLine() { var source = @" /// public class C { } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> </member> </members> </doc> ".Trim(); Assert.Equal(expected, actual); } [Fact] public void SingleLine_EmptyMultipleLines() { var source = @" /// /// /// public class C { } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> </member> </members> </doc> ".Trim(); Assert.Equal(expected, actual); } [Fact] public void SingleLine_NoLeadingSpaces() { var source = @" ///<summary> ///Text ///</summary> public class C { } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <summary> Text </summary> </member> </members> </doc> ".Trim(); Assert.Equal(expected, actual); } [Fact] public void SingleLine_SomeLeadingSpaces() { var source = @" ///<summary> /// Text /// </summary> public class C { } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <summary> Text </summary> </member> </members> </doc> ".Trim(); Assert.Equal(expected, actual); } [Fact] public void SingleLine_LeadingTab() { var source = @" /// <summary> /// Tabbed /// </summary> public class C { } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <summary> Tabbed </summary> </member> </members> </doc> ".Trim(); Assert.Equal(expected, actual); } [Fact] public void SingleLine_WhitespaceBefore() { var source = @" /// <summary> /// Text /// </summary> public class C { } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <summary> Text </summary> </member> </members> </doc> ".Trim(); Assert.Equal(expected, actual); } [Fact] public void SingleLine_BlankLines() { var source = @" /// /// <summary> /// Text /// </summary> /// public class C { } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <summary> Text </summary> </member> </members> </doc> ".Trim(); Assert.Equal(expected, actual); } #endregion Single-line style #region Multi-line style [Fact] public void MultiLine_OneLine() { var source = @" /** <summary>Text</summary> */ public class C { } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <summary>Text</summary> </member> </members> </doc> ".Trim(); Assert.Equal(expected, actual); } [Fact] public void MultiLine_EmptyOneLine() { var source = @" /** */ public class C { } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> </member> </members> </doc> ".Trim(); Assert.Equal(expected, actual); } [Fact] public void MultiLine_EmptyTwoLines() { var source = @" /** */ public class C { } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> </member> </members> </doc> ".Trim(); Assert.Equal(expected, actual); } [Fact] public void MultiLine_EmptyThreeLines() { var source = @" /** */ public class C { } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> </member> </members> </doc> ".Trim(); Assert.Equal(expected, actual); } [Fact] public void MultiLine_FirstLineSpace() { var source = @" /** <summary> * Text * </summary> */ public class C { } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <summary> Text </summary> </member> </members> </doc> ".Trim(); Assert.Equal(expected, actual); } [Fact] public void MultiLine_FirstLineNoSpace() { var source = @" /**<summary> * Text * </summary> */ public class C { } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <summary> Text </summary> </member> </members> </doc> ".Trim(); Assert.Equal(expected, actual); } [Fact] public void MultiLine_StarsPattern() { var source = @" /** * <summary> * Text * </summary> */ public class C { } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <summary> Text </summary> </member> </members> </doc> ".Trim(); Assert.Equal(expected, actual); } [Fact] public void MultiLine_StarsNoPattern() { var source = @" /** * <summary> * Text * </summary> */ public class C { } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> * <summary> * Text * </summary> </member> </members> </doc> ".Trim(); Assert.Equal(expected, actual); } [Fact] public void MultiLine_WhitespacePattern() { var source = @" /** <summary> Text </summary> */ public class C { } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <summary> Text </summary> </member> </members> </doc> ".Trim(); Assert.Equal(expected, actual); } [Fact] public void MultiLine_WhitespaceNoPattern() { var source = @" /** <summary> Text </summary> */ public class C { } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <summary> Text </summary> </member> </members> </doc> ".Trim(); Assert.Equal(expected, actual); } [Fact] public void MultiLine_LegacyTests() { var source = @" class A { /** * <summary> * /** * * * </summary> */ public void foo1(){} /** * /// * /// * /** */ public void foo2(){} /** /// <summary> /// /// </summary> */ public void foo3(){} // Test: // should not be xml comment /** // <summary> // // </summary> */ public void foo4(){} } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""M:A.foo1""> <summary> /** </summary> </member> <member name=""M:A.foo2""> /// /// /** </member> <member name=""M:A.foo3""> /// <summary> /// /// </summary> </member> <member name=""M:A.foo4""> // <summary> // // </summary> </member> </members> </doc> ".Trim(); Assert.Equal(expected, actual); } [WorkItem(547164, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547164")] [Fact] public void MultiLine_PatternShorterOnSubsequentLine() { var source = @" //repro.cs public class Point { /** * <summary>Instance variable in the * Point Class.</summary> */ private int x; /** * <summary>This is the entry point of the Point class testing * program.</summary> */ public static void Main() { } } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp, // (3,14): warning CS1591: Missing XML comment for publicly visible type or member 'Point' // public class Point Diagnostic(ErrorCode.WRN_MissingXMLComment, "Point").WithArguments("Point")); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""F:Point.x""> <summary>Instance variable in the Point Class.</summary> </member> <member name=""M:Point.Main""> <summary>This is the entry point of the Point class testing program.</summary> </member> </members> </doc> ".Trim(); Assert.Equal(expected, actual); } #endregion Multi-line style #region Partial types [Fact] public void PartialTypes_OneFile() { var source = @" /// <summary>Summary 1</summary> public partial class C { } /// <summary>Summary 2</summary> public partial class C { } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <summary>Summary 1</summary> <summary>Summary 2</summary> </member> </members> </doc> ".Trim(); Assert.Equal(expected, actual); } [Fact] public void PartialTypes_MultipleFiles() { var source1 = @" /// <summary>Summary 1</summary> public partial class C { } "; var source2 = @" /// <summary>Summary 2</summary> public partial class C { } "; var tree1 = SyntaxFactory.ParseSyntaxTree(source1, options: TestOptions.RegularWithDocumentationComments); var tree2 = SyntaxFactory.ParseSyntaxTree(source2, options: TestOptions.RegularWithDocumentationComments); // Files passed in order. var compA = CreateCompilation(new[] { tree1, tree2 }, assemblyName: "Test"); var actualA = GetDocumentationCommentText(compA); var expectedA = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <summary>Summary 1</summary> <summary>Summary 2</summary> </member> </members> </doc> ".Trim(); Assert.Equal(expectedA, actualA); // Files passed in reverse order. var compB = CreateCompilation(new[] { tree2, tree1 }, assemblyName: "Test"); var actualB = GetDocumentationCommentText(compB); var expectedB = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <summary>Summary 2</summary> <summary>Summary 1</summary> </member> </members> </doc> ".Trim(); Assert.Equal(expectedB, actualB); } [Fact] public void PartialTypes_MultipleStyles() { var source = @" /// <summary>Summary 1</summary> public partial class C { } /** <summary>Summary 2</summary> */ public partial class C { } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <summary>Summary 1</summary> <summary>Summary 2</summary> </member> </members> </doc> ".Trim(); Assert.Equal(expected, actual); } #endregion Partial types #region Partial methods [Fact] public void PartialMethods_OneFile() { var source = @" partial class C { /// <summary>Summary 1</summary> partial void M(); } partial class C { /// <summary>Summary 2</summary> partial void M() { } } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""M:C.M""> <summary>Summary 2</summary> </member> </members> </doc> ".Trim(); Assert.Equal(expected, actual); } [Fact] public void PartialMethods_MultipleFiles() { var source1 = @" partial class C { /** <summary>Summary 1</summary>*/ partial void M() { } } "; var source2 = @" partial class C { /** <summary>Summary 2</summary>*/ partial void M(); } "; var tree1 = SyntaxFactory.ParseSyntaxTree(source1, options: TestOptions.RegularWithDocumentationComments); var tree2 = SyntaxFactory.ParseSyntaxTree(source2, options: TestOptions.RegularWithDocumentationComments); // Files passed in order. var compA = CreateCompilation(new[] { tree1, tree2 }, assemblyName: "Test"); var actualA = GetDocumentationCommentText(compA); var expectedA = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""M:C.M""> <summary>Summary 1</summary> </member> </members> </doc> ".Trim(); Assert.Equal(expectedA, actualA); // Files passed in reverse order. var compB = CreateCompilation(new[] { tree2, tree1 }, assemblyName: "Test"); var actualB = GetDocumentationCommentText(compB); var expectedB = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""M:C.M""> <summary>Summary 1</summary> </member> </members> </doc> ".Trim(); Assert.Equal(expectedB, actualB); } [Fact] public void ExtendedPartialMethods_MultipleFiles() { var source1 = @" partial class C { /** <summary>Summary 1</summary>*/ public partial int M() => 42; } "; var source2 = @" partial class C { /** <summary>Summary 2</summary>*/ public partial int M(); } "; var tree1 = SyntaxFactory.ParseSyntaxTree(source1, options: TestOptions.RegularWithDocumentationComments); var tree2 = SyntaxFactory.ParseSyntaxTree(source2, options: TestOptions.RegularWithDocumentationComments); // Files passed in order. var compA = CreateCompilation(new[] { tree1, tree2 }, assemblyName: "Test"); var actualA = GetDocumentationCommentText(compA); var expectedA = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""M:C.M""> <summary>Summary 1</summary> </member> </members> </doc> ".Trim(); Assert.Equal(expectedA, actualA); // Files passed in reverse order. var compB = CreateCompilation(new[] { tree2, tree1 }, assemblyName: "Test"); var actualB = GetDocumentationCommentText(compB); var expectedB = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""M:C.M""> <summary>Summary 1</summary> </member> </members> </doc> ".Trim(); Assert.Equal(expectedB, actualB); } #endregion Partial methods #region Crefs [Fact] public void ValidCrefs() { var source = @" /// <summary> /// A <see cref=""C""/> B /// <see cref=""object""/> C. /// </summary> public class C { } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <summary> A <see cref=""T:C""/> B <see cref=""T:System.Object""/> C. </summary> </member> </members> </doc> ".Trim(); Assert.Equal(expected, actual); } [Fact] public void InvalidCrefs() { var source = @" /// <summary> /// A <see cref=""Q""/>. /// </summary> public class C { } /// <summary> /// A <see cref=""R{S, T}""/>. /// </summary> public class D { } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp, // (3,18): warning CS1574: XML comment has cref attribute 'Q' that could not be resolved // /// A <see cref="Q"/>. Diagnostic(ErrorCode.WRN_BadXMLRef, "Q").WithArguments("Q"), // (8,18): warning CS1574: XML comment has cref attribute 'R{S, T}' that could not be resolved // /// A <see cref="R{S, T}"/>. Diagnostic(ErrorCode.WRN_BadXMLRef, "R{S, T}").WithArguments("R{S, T}")); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <summary> A <see cref=""!:Q""/>. </summary> </member> <member name=""T:D""> <summary> A <see cref=""!:R&lt;S, T&gt;""/>. </summary> </member> </members> </doc> ".Trim(); Assert.Equal(expected, actual); } #endregion Crefs #region Output name [Fact] public void AssemblyNameFromCompilationName() { var source = @" /// A <see cref=""Main""/>. public class C { static void Main() {} } "; var comp = CreateCompilationUtil(source, assemblyName: "CompilationName"); var actual = GetDocumentationCommentText(comp); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>CompilationName</name> </assembly> <members> <member name=""T:C""> A <see cref=""M:C.Main""/>. </member> </members> </doc> ".Trim(); Assert.Equal(expected, actual); } [Fact] public void AssemblyNameFromOutputName() { var source = @" /// A <see cref=""Main""/>. public class C { static void Main() {} } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp, "OutputName"); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>OutputName</name> </assembly> <members> <member name=""T:C""> A <see cref=""M:C.Main""/>. </member> </members> </doc> ".Trim(); Assert.Equal(expected, actual); } #endregion Output name #region WRN_UnprocessedXMLComment [Fact] public void UnprocessedXMLComment_Types() { var source = @" class C<T> : object where T : I { } struct S<T, U> where T : U { } interface I { } delegate void D<T, U>(T t, U u) where T : U; enum E : byte { } "; var revisedSource = new DocumentationCommentAdder().Visit(Parse(source).GetCompilationUnitRoot()).ToFullString(); // Manually verified that positions match dev11. CreateCompilationUtil(revisedSource).VerifyDiagnostics( // (2,15): warning CS1587: XML comment is not placed on a valid language element // /** 0 */class /** 1 */C/** 2 */</** 3 */T/** 4 */> /** 5 */: /** 6 */object /** 7 */where /** 8 */T /** 9 */: /** 10 */I Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (2,24): warning CS1587: XML comment is not placed on a valid language element // /** 0 */class /** 1 */C/** 2 */</** 3 */T/** 4 */> /** 5 */: /** 6 */object /** 7 */where /** 8 */T /** 9 */: /** 10 */I Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (2,33): warning CS1587: XML comment is not placed on a valid language element // /** 0 */class /** 1 */C/** 2 */</** 3 */T/** 4 */> /** 5 */: /** 6 */object /** 7 */where /** 8 */T /** 9 */: /** 10 */I Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (2,42): warning CS1587: XML comment is not placed on a valid language element // /** 0 */class /** 1 */C/** 2 */</** 3 */T/** 4 */> /** 5 */: /** 6 */object /** 7 */where /** 8 */T /** 9 */: /** 10 */I Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (2,52): warning CS1587: XML comment is not placed on a valid language element // /** 0 */class /** 1 */C/** 2 */</** 3 */T/** 4 */> /** 5 */: /** 6 */object /** 7 */where /** 8 */T /** 9 */: /** 10 */I Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (2,62): warning CS1587: XML comment is not placed on a valid language element // /** 0 */class /** 1 */C/** 2 */</** 3 */T/** 4 */> /** 5 */: /** 6 */object /** 7 */where /** 8 */T /** 9 */: /** 10 */I Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (2,77): warning CS1587: XML comment is not placed on a valid language element // /** 0 */class /** 1 */C/** 2 */</** 3 */T/** 4 */> /** 5 */: /** 6 */object /** 7 */where /** 8 */T /** 9 */: /** 10 */I Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (2,91): warning CS1587: XML comment is not placed on a valid language element // /** 0 */class /** 1 */C/** 2 */</** 3 */T/** 4 */> /** 5 */: /** 6 */object /** 7 */where /** 8 */T /** 9 */: /** 10 */I Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (2,101): warning CS1587: XML comment is not placed on a valid language element // /** 0 */class /** 1 */C/** 2 */</** 3 */T/** 4 */> /** 5 */: /** 6 */object /** 7 */where /** 8 */T /** 9 */: /** 10 */I Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (2,111): warning CS1587: XML comment is not placed on a valid language element // /** 0 */class /** 1 */C/** 2 */</** 3 */T/** 4 */> /** 5 */: /** 6 */object /** 7 */where /** 8 */T /** 9 */: /** 10 */I Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (3,1): warning CS1587: XML comment is not placed on a valid language element // /** 11 */{ Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (5,1): warning CS1587: XML comment is not placed on a valid language element // /** 12 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (7,17): warning CS1587: XML comment is not placed on a valid language element // /** 13 */struct /** 14 */S/** 15 */</** 16 */T/** 17 */, /** 18 */U/** 19 */> /** 20 */where /** 21 */T /** 22 */: /** 23 */U Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (7,27): warning CS1587: XML comment is not placed on a valid language element // /** 13 */struct /** 14 */S/** 15 */</** 16 */T/** 17 */, /** 18 */U/** 19 */> /** 20 */where /** 21 */T /** 22 */: /** 23 */U Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (7,37): warning CS1587: XML comment is not placed on a valid language element // /** 13 */struct /** 14 */S/** 15 */</** 16 */T/** 17 */, /** 18 */U/** 19 */> /** 20 */where /** 21 */T /** 22 */: /** 23 */U Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (7,47): warning CS1587: XML comment is not placed on a valid language element // /** 13 */struct /** 14 */S/** 15 */</** 16 */T/** 17 */, /** 18 */U/** 19 */> /** 20 */where /** 21 */T /** 22 */: /** 23 */U Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (7,58): warning CS1587: XML comment is not placed on a valid language element // /** 13 */struct /** 14 */S/** 15 */</** 16 */T/** 17 */, /** 18 */U/** 19 */> /** 20 */where /** 21 */T /** 22 */: /** 23 */U Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (7,68): warning CS1587: XML comment is not placed on a valid language element // /** 13 */struct /** 14 */S/** 15 */</** 16 */T/** 17 */, /** 18 */U/** 19 */> /** 20 */where /** 21 */T /** 22 */: /** 23 */U Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (7,79): warning CS1587: XML comment is not placed on a valid language element // /** 13 */struct /** 14 */S/** 15 */</** 16 */T/** 17 */, /** 18 */U/** 19 */> /** 20 */where /** 21 */T /** 22 */: /** 23 */U Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (7,94): warning CS1587: XML comment is not placed on a valid language element // /** 13 */struct /** 14 */S/** 15 */</** 16 */T/** 17 */, /** 18 */U/** 19 */> /** 20 */where /** 21 */T /** 22 */: /** 23 */U Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (7,105): warning CS1587: XML comment is not placed on a valid language element // /** 13 */struct /** 14 */S/** 15 */</** 16 */T/** 17 */, /** 18 */U/** 19 */> /** 20 */where /** 21 */T /** 22 */: /** 23 */U Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (7,116): warning CS1587: XML comment is not placed on a valid language element // /** 13 */struct /** 14 */S/** 15 */</** 16 */T/** 17 */, /** 18 */U/** 19 */> /** 20 */where /** 21 */T /** 22 */: /** 23 */U Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (8,1): warning CS1587: XML comment is not placed on a valid language element // /** 24 */{ Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (10,1): warning CS1587: XML comment is not placed on a valid language element // /** 25 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (12,20): warning CS1587: XML comment is not placed on a valid language element // /** 26 */interface /** 27 */I Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (13,1): warning CS1587: XML comment is not placed on a valid language element // /** 28 */{ Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (15,1): warning CS1587: XML comment is not placed on a valid language element // /** 29 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (17,19): warning CS1587: XML comment is not placed on a valid language element // /** 30 */delegate /** 31 */void /** 32 */D/** 33 */</** 34 */T/** 35 */, /** 36 */U/** 37 */>/** 38 */(/** 39 */T /** 40 */t/** 41 */, /** 42 */U /** 43 */u/** 44 */) /** 45 */where /** 46 */T /** 47 */: /** 48 */U/** 49 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (17,33): warning CS1587: XML comment is not placed on a valid language element // /** 30 */delegate /** 31 */void /** 32 */D/** 33 */</** 34 */T/** 35 */, /** 36 */U/** 37 */>/** 38 */(/** 39 */T /** 40 */t/** 41 */, /** 42 */U /** 43 */u/** 44 */) /** 45 */where /** 46 */T /** 47 */: /** 48 */U/** 49 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (17,43): warning CS1587: XML comment is not placed on a valid language element // /** 30 */delegate /** 31 */void /** 32 */D/** 33 */</** 34 */T/** 35 */, /** 36 */U/** 37 */>/** 38 */(/** 39 */T /** 40 */t/** 41 */, /** 42 */U /** 43 */u/** 44 */) /** 45 */where /** 46 */T /** 47 */: /** 48 */U/** 49 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (17,53): warning CS1587: XML comment is not placed on a valid language element // /** 30 */delegate /** 31 */void /** 32 */D/** 33 */</** 34 */T/** 35 */, /** 36 */U/** 37 */>/** 38 */(/** 39 */T /** 40 */t/** 41 */, /** 42 */U /** 43 */u/** 44 */) /** 45 */where /** 46 */T /** 47 */: /** 48 */U/** 49 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (17,63): warning CS1587: XML comment is not placed on a valid language element // /** 30 */delegate /** 31 */void /** 32 */D/** 33 */</** 34 */T/** 35 */, /** 36 */U/** 37 */>/** 38 */(/** 39 */T /** 40 */t/** 41 */, /** 42 */U /** 43 */u/** 44 */) /** 45 */where /** 46 */T /** 47 */: /** 48 */U/** 49 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (17,74): warning CS1587: XML comment is not placed on a valid language element // /** 30 */delegate /** 31 */void /** 32 */D/** 33 */</** 34 */T/** 35 */, /** 36 */U/** 37 */>/** 38 */(/** 39 */T /** 40 */t/** 41 */, /** 42 */U /** 43 */u/** 44 */) /** 45 */where /** 46 */T /** 47 */: /** 48 */U/** 49 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (17,84): warning CS1587: XML comment is not placed on a valid language element // /** 30 */delegate /** 31 */void /** 32 */D/** 33 */</** 34 */T/** 35 */, /** 36 */U/** 37 */>/** 38 */(/** 39 */T /** 40 */t/** 41 */, /** 42 */U /** 43 */u/** 44 */) /** 45 */where /** 46 */T /** 47 */: /** 48 */U/** 49 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (17,94): warning CS1587: XML comment is not placed on a valid language element // /** 30 */delegate /** 31 */void /** 32 */D/** 33 */</** 34 */T/** 35 */, /** 36 */U/** 37 */>/** 38 */(/** 39 */T /** 40 */t/** 41 */, /** 42 */U /** 43 */u/** 44 */) /** 45 */where /** 46 */T /** 47 */: /** 48 */U/** 49 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (17,104): warning CS1587: XML comment is not placed on a valid language element // /** 30 */delegate /** 31 */void /** 32 */D/** 33 */</** 34 */T/** 35 */, /** 36 */U/** 37 */>/** 38 */(/** 39 */T /** 40 */t/** 41 */, /** 42 */U /** 43 */u/** 44 */) /** 45 */where /** 46 */T /** 47 */: /** 48 */U/** 49 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (17,115): warning CS1587: XML comment is not placed on a valid language element // /** 30 */delegate /** 31 */void /** 32 */D/** 33 */</** 34 */T/** 35 */, /** 36 */U/** 37 */>/** 38 */(/** 39 */T /** 40 */t/** 41 */, /** 42 */U /** 43 */u/** 44 */) /** 45 */where /** 46 */T /** 47 */: /** 48 */U/** 49 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (17,125): warning CS1587: XML comment is not placed on a valid language element // /** 30 */delegate /** 31 */void /** 32 */D/** 33 */</** 34 */T/** 35 */, /** 36 */U/** 37 */>/** 38 */(/** 39 */T /** 40 */t/** 41 */, /** 42 */U /** 43 */u/** 44 */) /** 45 */where /** 46 */T /** 47 */: /** 48 */U/** 49 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (17,136): warning CS1587: XML comment is not placed on a valid language element // /** 30 */delegate /** 31 */void /** 32 */D/** 33 */</** 34 */T/** 35 */, /** 36 */U/** 37 */>/** 38 */(/** 39 */T /** 40 */t/** 41 */, /** 42 */U /** 43 */u/** 44 */) /** 45 */where /** 46 */T /** 47 */: /** 48 */U/** 49 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (17,147): warning CS1587: XML comment is not placed on a valid language element // /** 30 */delegate /** 31 */void /** 32 */D/** 33 */</** 34 */T/** 35 */, /** 36 */U/** 37 */>/** 38 */(/** 39 */T /** 40 */t/** 41 */, /** 42 */U /** 43 */u/** 44 */) /** 45 */where /** 46 */T /** 47 */: /** 48 */U/** 49 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (17,157): warning CS1587: XML comment is not placed on a valid language element // /** 30 */delegate /** 31 */void /** 32 */D/** 33 */</** 34 */T/** 35 */, /** 36 */U/** 37 */>/** 38 */(/** 39 */T /** 40 */t/** 41 */, /** 42 */U /** 43 */u/** 44 */) /** 45 */where /** 46 */T /** 47 */: /** 48 */U/** 49 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (17,168): warning CS1587: XML comment is not placed on a valid language element // /** 30 */delegate /** 31 */void /** 32 */D/** 33 */</** 34 */T/** 35 */, /** 36 */U/** 37 */>/** 38 */(/** 39 */T /** 40 */t/** 41 */, /** 42 */U /** 43 */u/** 44 */) /** 45 */where /** 46 */T /** 47 */: /** 48 */U/** 49 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (17,183): warning CS1587: XML comment is not placed on a valid language element // /** 30 */delegate /** 31 */void /** 32 */D/** 33 */</** 34 */T/** 35 */, /** 36 */U/** 37 */>/** 38 */(/** 39 */T /** 40 */t/** 41 */, /** 42 */U /** 43 */u/** 44 */) /** 45 */where /** 46 */T /** 47 */: /** 48 */U/** 49 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (17,194): warning CS1587: XML comment is not placed on a valid language element // /** 30 */delegate /** 31 */void /** 32 */D/** 33 */</** 34 */T/** 35 */, /** 36 */U/** 37 */>/** 38 */(/** 39 */T /** 40 */t/** 41 */, /** 42 */U /** 43 */u/** 44 */) /** 45 */where /** 46 */T /** 47 */: /** 48 */U/** 49 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (17,205): warning CS1587: XML comment is not placed on a valid language element // /** 30 */delegate /** 31 */void /** 32 */D/** 33 */</** 34 */T/** 35 */, /** 36 */U/** 37 */>/** 38 */(/** 39 */T /** 40 */t/** 41 */, /** 42 */U /** 43 */u/** 44 */) /** 45 */where /** 46 */T /** 47 */: /** 48 */U/** 49 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (17,215): warning CS1587: XML comment is not placed on a valid language element // /** 30 */delegate /** 31 */void /** 32 */D/** 33 */</** 34 */T/** 35 */, /** 36 */U/** 37 */>/** 38 */(/** 39 */T /** 40 */t/** 41 */, /** 42 */U /** 43 */u/** 44 */) /** 45 */where /** 46 */T /** 47 */: /** 48 */U/** 49 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (19,15): warning CS1587: XML comment is not placed on a valid language element // /** 50 */enum /** 51 */E /** 52 */: /** 53 */byte Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (19,26): warning CS1587: XML comment is not placed on a valid language element // /** 50 */enum /** 51 */E /** 52 */: /** 53 */byte Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (19,37): warning CS1587: XML comment is not placed on a valid language element // /** 50 */enum /** 51 */E /** 52 */: /** 53 */byte Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (20,1): warning CS1587: XML comment is not placed on a valid language element // /** 54 */{ Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (22,1): warning CS1587: XML comment is not placed on a valid language element // /** 55 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (23,1): warning CS1587: XML comment is not placed on a valid language element // /** 56 */ Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/")); } [Fact] public void UnprocessedXMLComment_Members() { var source = @" class C { private int field; private int Property { get; set; } private int this[int x] { get { return 0; } set { } } private event System.Action FieldLikeEvent; private event System.Action CustomEvent { add { } remove { } } private void Method<T, U>(T t, U u) where T : U { } public static int operator +(C c) { return 0; } public static explicit operator int(C c) { return 0; } private C(int x) : base() { } } enum E { A, } "; var revisedSource = new DocumentationCommentAdder().Visit(Parse(source).GetCompilationUnitRoot()).ToFullString(); // Manually verified that positions match dev11. CreateCompilationUtil(revisedSource).VerifyDiagnostics( // (4,41): warning CS0169: The field 'C.field' is never used // /** 3 */private /** 4 */int /** 5 */field/** 6 */; Diagnostic(ErrorCode.WRN_UnreferencedField, "field").WithArguments("C.field"), // (7,87): warning CS0067: The event 'C.FieldLikeEvent' is never used // /** 34 */private /** 35 */event /** 36 */System/** 37 */./** 38 */Action /** 39 */FieldLikeEvent/** 40 */; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "FieldLikeEvent").WithArguments("C.FieldLikeEvent"), // (2,15): warning CS1587: XML comment is not placed on a valid language element // /** 0 */class /** 1 */C Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (3,1): warning CS1587: XML comment is not placed on a valid language element // /** 2 */{ Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (4,21): warning CS1587: XML comment is not placed on a valid language element // /** 3 */private /** 4 */int /** 5 */field/** 6 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (4,33): warning CS1587: XML comment is not placed on a valid language element // /** 3 */private /** 4 */int /** 5 */field/** 6 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (4,46): warning CS1587: XML comment is not placed on a valid language element // /** 3 */private /** 4 */int /** 5 */field/** 6 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (5,21): warning CS1587: XML comment is not placed on a valid language element // /** 7 */private /** 8 */int /** 9 */Property /** 10 */{ /** 11 */get/** 12 */; /** 13 */set/** 14 */; /** 15 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (5,33): warning CS1587: XML comment is not placed on a valid language element // /** 7 */private /** 8 */int /** 9 */Property /** 10 */{ /** 11 */get/** 12 */; /** 13 */set/** 14 */; /** 15 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (5,50): warning CS1587: XML comment is not placed on a valid language element // /** 7 */private /** 8 */int /** 9 */Property /** 10 */{ /** 11 */get/** 12 */; /** 13 */set/** 14 */; /** 15 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (5,61): warning CS1587: XML comment is not placed on a valid language element // /** 7 */private /** 8 */int /** 9 */Property /** 10 */{ /** 11 */get/** 12 */; /** 13 */set/** 14 */; /** 15 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (5,73): warning CS1587: XML comment is not placed on a valid language element // /** 7 */private /** 8 */int /** 9 */Property /** 10 */{ /** 11 */get/** 12 */; /** 13 */set/** 14 */; /** 15 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (5,84): warning CS1587: XML comment is not placed on a valid language element // /** 7 */private /** 8 */int /** 9 */Property /** 10 */{ /** 11 */get/** 12 */; /** 13 */set/** 14 */; /** 15 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (5,96): warning CS1587: XML comment is not placed on a valid language element // /** 7 */private /** 8 */int /** 9 */Property /** 10 */{ /** 11 */get/** 12 */; /** 13 */set/** 14 */; /** 15 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (5,107): warning CS1587: XML comment is not placed on a valid language element // /** 7 */private /** 8 */int /** 9 */Property /** 10 */{ /** 11 */get/** 12 */; /** 13 */set/** 14 */; /** 15 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (6,22): warning CS1587: XML comment is not placed on a valid language element // /** 16 */private /** 17 */int /** 18 */this/** 19 */[/** 20 */int /** 21 */x/** 22 */] /** 23 */{ /** 24 */get /** 25 */{ /** 26 */return /** 27 */0/** 28 */; /** 29 */} /** 30 */set /** 31 */{ /** 32 */} /** 33 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (6,35): warning CS1587: XML comment is not placed on a valid language element // /** 16 */private /** 17 */int /** 18 */this/** 19 */[/** 20 */int /** 21 */x/** 22 */] /** 23 */{ /** 24 */get /** 25 */{ /** 26 */return /** 27 */0/** 28 */; /** 29 */} /** 30 */set /** 31 */{ /** 32 */} /** 33 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (6,48): warning CS1587: XML comment is not placed on a valid language element // /** 16 */private /** 17 */int /** 18 */this/** 19 */[/** 20 */int /** 21 */x/** 22 */] /** 23 */{ /** 24 */get /** 25 */{ /** 26 */return /** 27 */0/** 28 */; /** 29 */} /** 30 */set /** 31 */{ /** 32 */} /** 33 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (6,58): warning CS1587: XML comment is not placed on a valid language element // /** 16 */private /** 17 */int /** 18 */this/** 19 */[/** 20 */int /** 21 */x/** 22 */] /** 23 */{ /** 24 */get /** 25 */{ /** 26 */return /** 27 */0/** 28 */; /** 29 */} /** 30 */set /** 31 */{ /** 32 */} /** 33 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (6,71): warning CS1587: XML comment is not placed on a valid language element // /** 16 */private /** 17 */int /** 18 */this/** 19 */[/** 20 */int /** 21 */x/** 22 */] /** 23 */{ /** 24 */get /** 25 */{ /** 26 */return /** 27 */0/** 28 */; /** 29 */} /** 30 */set /** 31 */{ /** 32 */} /** 33 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (6,81): warning CS1587: XML comment is not placed on a valid language element // /** 16 */private /** 17 */int /** 18 */this/** 19 */[/** 20 */int /** 21 */x/** 22 */] /** 23 */{ /** 24 */get /** 25 */{ /** 26 */return /** 27 */0/** 28 */; /** 29 */} /** 30 */set /** 31 */{ /** 32 */} /** 33 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (6,92): warning CS1587: XML comment is not placed on a valid language element // /** 16 */private /** 17 */int /** 18 */this/** 19 */[/** 20 */int /** 21 */x/** 22 */] /** 23 */{ /** 24 */get /** 25 */{ /** 26 */return /** 27 */0/** 28 */; /** 29 */} /** 30 */set /** 31 */{ /** 32 */} /** 33 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (6,103): warning CS1587: XML comment is not placed on a valid language element // /** 16 */private /** 17 */int /** 18 */this/** 19 */[/** 20 */int /** 21 */x/** 22 */] /** 23 */{ /** 24 */get /** 25 */{ /** 26 */return /** 27 */0/** 28 */; /** 29 */} /** 30 */set /** 31 */{ /** 32 */} /** 33 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (6,116): warning CS1587: XML comment is not placed on a valid language element // /** 16 */private /** 17 */int /** 18 */this/** 19 */[/** 20 */int /** 21 */x/** 22 */] /** 23 */{ /** 24 */get /** 25 */{ /** 26 */return /** 27 */0/** 28 */; /** 29 */} /** 30 */set /** 31 */{ /** 32 */} /** 33 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (6,127): warning CS1587: XML comment is not placed on a valid language element // /** 16 */private /** 17 */int /** 18 */this/** 19 */[/** 20 */int /** 21 */x/** 22 */] /** 23 */{ /** 24 */get /** 25 */{ /** 26 */return /** 27 */0/** 28 */; /** 29 */} /** 30 */set /** 31 */{ /** 32 */} /** 33 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (6,143): warning CS1587: XML comment is not placed on a valid language element // /** 16 */private /** 17 */int /** 18 */this/** 19 */[/** 20 */int /** 21 */x/** 22 */] /** 23 */{ /** 24 */get /** 25 */{ /** 26 */return /** 27 */0/** 28 */; /** 29 */} /** 30 */set /** 31 */{ /** 32 */} /** 33 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (6,153): warning CS1587: XML comment is not placed on a valid language element // /** 16 */private /** 17 */int /** 18 */this/** 19 */[/** 20 */int /** 21 */x/** 22 */] /** 23 */{ /** 24 */get /** 25 */{ /** 26 */return /** 27 */0/** 28 */; /** 29 */} /** 30 */set /** 31 */{ /** 32 */} /** 33 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (6,164): warning CS1587: XML comment is not placed on a valid language element // /** 16 */private /** 17 */int /** 18 */this/** 19 */[/** 20 */int /** 21 */x/** 22 */] /** 23 */{ /** 24 */get /** 25 */{ /** 26 */return /** 27 */0/** 28 */; /** 29 */} /** 30 */set /** 31 */{ /** 32 */} /** 33 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (6,175): warning CS1587: XML comment is not placed on a valid language element // /** 16 */private /** 17 */int /** 18 */this/** 19 */[/** 20 */int /** 21 */x/** 22 */] /** 23 */{ /** 24 */get /** 25 */{ /** 26 */return /** 27 */0/** 28 */; /** 29 */} /** 30 */set /** 31 */{ /** 32 */} /** 33 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (6,188): warning CS1587: XML comment is not placed on a valid language element // /** 16 */private /** 17 */int /** 18 */this/** 19 */[/** 20 */int /** 21 */x/** 22 */] /** 23 */{ /** 24 */get /** 25 */{ /** 26 */return /** 27 */0/** 28 */; /** 29 */} /** 30 */set /** 31 */{ /** 32 */} /** 33 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (6,199): warning CS1587: XML comment is not placed on a valid language element // /** 16 */private /** 17 */int /** 18 */this/** 19 */[/** 20 */int /** 21 */x/** 22 */] /** 23 */{ /** 24 */get /** 25 */{ /** 26 */return /** 27 */0/** 28 */; /** 29 */} /** 30 */set /** 31 */{ /** 32 */} /** 33 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (6,210): warning CS1587: XML comment is not placed on a valid language element // /** 16 */private /** 17 */int /** 18 */this/** 19 */[/** 20 */int /** 21 */x/** 22 */] /** 23 */{ /** 24 */get /** 25 */{ /** 26 */return /** 27 */0/** 28 */; /** 29 */} /** 30 */set /** 31 */{ /** 32 */} /** 33 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (7,22): warning CS1587: XML comment is not placed on a valid language element // /** 34 */private /** 35 */event /** 36 */System/** 37 */./** 38 */Action /** 39 */FieldLikeEvent/** 40 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (7,37): warning CS1587: XML comment is not placed on a valid language element // /** 34 */private /** 35 */event /** 36 */System/** 37 */./** 38 */Action /** 39 */FieldLikeEvent/** 40 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (7,52): warning CS1587: XML comment is not placed on a valid language element // /** 34 */private /** 35 */event /** 36 */System/** 37 */./** 38 */Action /** 39 */FieldLikeEvent/** 40 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (7,62): warning CS1587: XML comment is not placed on a valid language element // /** 34 */private /** 35 */event /** 36 */System/** 37 */./** 38 */Action /** 39 */FieldLikeEvent/** 40 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (7,78): warning CS1587: XML comment is not placed on a valid language element // /** 34 */private /** 35 */event /** 36 */System/** 37 */./** 38 */Action /** 39 */FieldLikeEvent/** 40 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (7,101): warning CS1587: XML comment is not placed on a valid language element // /** 34 */private /** 35 */event /** 36 */System/** 37 */./** 38 */Action /** 39 */FieldLikeEvent/** 40 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (8,22): warning CS1587: XML comment is not placed on a valid language element // /** 41 */private /** 42 */event /** 43 */System/** 44 */./** 45 */Action /** 46 */CustomEvent /** 47 */{ /** 48 */add /** 49 */{ /** 50 */} /** 51 */remove /** 52 */{ /** 53 */} /** 54 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (8,37): warning CS1587: XML comment is not placed on a valid language element // /** 41 */private /** 42 */event /** 43 */System/** 44 */./** 45 */Action /** 46 */CustomEvent /** 47 */{ /** 48 */add /** 49 */{ /** 50 */} /** 51 */remove /** 52 */{ /** 53 */} /** 54 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (8,52): warning CS1587: XML comment is not placed on a valid language element // /** 41 */private /** 42 */event /** 43 */System/** 44 */./** 45 */Action /** 46 */CustomEvent /** 47 */{ /** 48 */add /** 49 */{ /** 50 */} /** 51 */remove /** 52 */{ /** 53 */} /** 54 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (8,62): warning CS1587: XML comment is not placed on a valid language element // /** 41 */private /** 42 */event /** 43 */System/** 44 */./** 45 */Action /** 46 */CustomEvent /** 47 */{ /** 48 */add /** 49 */{ /** 50 */} /** 51 */remove /** 52 */{ /** 53 */} /** 54 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (8,78): warning CS1587: XML comment is not placed on a valid language element // /** 41 */private /** 42 */event /** 43 */System/** 44 */./** 45 */Action /** 46 */CustomEvent /** 47 */{ /** 48 */add /** 49 */{ /** 50 */} /** 51 */remove /** 52 */{ /** 53 */} /** 54 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (8,99): warning CS1587: XML comment is not placed on a valid language element // /** 41 */private /** 42 */event /** 43 */System/** 44 */./** 45 */Action /** 46 */CustomEvent /** 47 */{ /** 48 */add /** 49 */{ /** 50 */} /** 51 */remove /** 52 */{ /** 53 */} /** 54 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (8,110): warning CS1587: XML comment is not placed on a valid language element // /** 41 */private /** 42 */event /** 43 */System/** 44 */./** 45 */Action /** 46 */CustomEvent /** 47 */{ /** 48 */add /** 49 */{ /** 50 */} /** 51 */remove /** 52 */{ /** 53 */} /** 54 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (8,123): warning CS1587: XML comment is not placed on a valid language element // /** 41 */private /** 42 */event /** 43 */System/** 44 */./** 45 */Action /** 46 */CustomEvent /** 47 */{ /** 48 */add /** 49 */{ /** 50 */} /** 51 */remove /** 52 */{ /** 53 */} /** 54 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (8,134): warning CS1587: XML comment is not placed on a valid language element // /** 41 */private /** 42 */event /** 43 */System/** 44 */./** 45 */Action /** 46 */CustomEvent /** 47 */{ /** 48 */add /** 49 */{ /** 50 */} /** 51 */remove /** 52 */{ /** 53 */} /** 54 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (8,145): warning CS1587: XML comment is not placed on a valid language element // /** 41 */private /** 42 */event /** 43 */System/** 44 */./** 45 */Action /** 46 */CustomEvent /** 47 */{ /** 48 */add /** 49 */{ /** 50 */} /** 51 */remove /** 52 */{ /** 53 */} /** 54 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (8,161): warning CS1587: XML comment is not placed on a valid language element // /** 41 */private /** 42 */event /** 43 */System/** 44 */./** 45 */Action /** 46 */CustomEvent /** 47 */{ /** 48 */add /** 49 */{ /** 50 */} /** 51 */remove /** 52 */{ /** 53 */} /** 54 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (8,172): warning CS1587: XML comment is not placed on a valid language element // /** 41 */private /** 42 */event /** 43 */System/** 44 */./** 45 */Action /** 46 */CustomEvent /** 47 */{ /** 48 */add /** 49 */{ /** 50 */} /** 51 */remove /** 52 */{ /** 53 */} /** 54 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (8,183): warning CS1587: XML comment is not placed on a valid language element // /** 41 */private /** 42 */event /** 43 */System/** 44 */./** 45 */Action /** 46 */CustomEvent /** 47 */{ /** 48 */add /** 49 */{ /** 50 */} /** 51 */remove /** 52 */{ /** 53 */} /** 54 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (9,22): warning CS1587: XML comment is not placed on a valid language element // /** 55 */private /** 56 */void /** 57 */Method/** 58 */</** 59 */T/** 60 */, /** 61 */U/** 62 */>/** 63 */(/** 64 */T /** 65 */t/** 66 */, /** 67 */U /** 68 */u/** 69 */) /** 70 */where /** 71 */T /** 72 */: /** 73 */U /** 74 */{ /** 75 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (9,36): warning CS1587: XML comment is not placed on a valid language element // /** 55 */private /** 56 */void /** 57 */Method/** 58 */</** 59 */T/** 60 */, /** 61 */U/** 62 */>/** 63 */(/** 64 */T /** 65 */t/** 66 */, /** 67 */U /** 68 */u/** 69 */) /** 70 */where /** 71 */T /** 72 */: /** 73 */U /** 74 */{ /** 75 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (9,51): warning CS1587: XML comment is not placed on a valid language element // /** 55 */private /** 56 */void /** 57 */Method/** 58 */</** 59 */T/** 60 */, /** 61 */U/** 62 */>/** 63 */(/** 64 */T /** 65 */t/** 66 */, /** 67 */U /** 68 */u/** 69 */) /** 70 */where /** 71 */T /** 72 */: /** 73 */U /** 74 */{ /** 75 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (9,61): warning CS1587: XML comment is not placed on a valid language element // /** 55 */private /** 56 */void /** 57 */Method/** 58 */</** 59 */T/** 60 */, /** 61 */U/** 62 */>/** 63 */(/** 64 */T /** 65 */t/** 66 */, /** 67 */U /** 68 */u/** 69 */) /** 70 */where /** 71 */T /** 72 */: /** 73 */U /** 74 */{ /** 75 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (9,71): warning CS1587: XML comment is not placed on a valid language element // /** 55 */private /** 56 */void /** 57 */Method/** 58 */</** 59 */T/** 60 */, /** 61 */U/** 62 */>/** 63 */(/** 64 */T /** 65 */t/** 66 */, /** 67 */U /** 68 */u/** 69 */) /** 70 */where /** 71 */T /** 72 */: /** 73 */U /** 74 */{ /** 75 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (9,82): warning CS1587: XML comment is not placed on a valid language element // /** 55 */private /** 56 */void /** 57 */Method/** 58 */</** 59 */T/** 60 */, /** 61 */U/** 62 */>/** 63 */(/** 64 */T /** 65 */t/** 66 */, /** 67 */U /** 68 */u/** 69 */) /** 70 */where /** 71 */T /** 72 */: /** 73 */U /** 74 */{ /** 75 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (9,92): warning CS1587: XML comment is not placed on a valid language element // /** 55 */private /** 56 */void /** 57 */Method/** 58 */</** 59 */T/** 60 */, /** 61 */U/** 62 */>/** 63 */(/** 64 */T /** 65 */t/** 66 */, /** 67 */U /** 68 */u/** 69 */) /** 70 */where /** 71 */T /** 72 */: /** 73 */U /** 74 */{ /** 75 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (9,102): warning CS1587: XML comment is not placed on a valid language element // /** 55 */private /** 56 */void /** 57 */Method/** 58 */</** 59 */T/** 60 */, /** 61 */U/** 62 */>/** 63 */(/** 64 */T /** 65 */t/** 66 */, /** 67 */U /** 68 */u/** 69 */) /** 70 */where /** 71 */T /** 72 */: /** 73 */U /** 74 */{ /** 75 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (9,112): warning CS1587: XML comment is not placed on a valid language element // /** 55 */private /** 56 */void /** 57 */Method/** 58 */</** 59 */T/** 60 */, /** 61 */U/** 62 */>/** 63 */(/** 64 */T /** 65 */t/** 66 */, /** 67 */U /** 68 */u/** 69 */) /** 70 */where /** 71 */T /** 72 */: /** 73 */U /** 74 */{ /** 75 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (9,123): warning CS1587: XML comment is not placed on a valid language element // /** 55 */private /** 56 */void /** 57 */Method/** 58 */</** 59 */T/** 60 */, /** 61 */U/** 62 */>/** 63 */(/** 64 */T /** 65 */t/** 66 */, /** 67 */U /** 68 */u/** 69 */) /** 70 */where /** 71 */T /** 72 */: /** 73 */U /** 74 */{ /** 75 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (9,133): warning CS1587: XML comment is not placed on a valid language element // /** 55 */private /** 56 */void /** 57 */Method/** 58 */</** 59 */T/** 60 */, /** 61 */U/** 62 */>/** 63 */(/** 64 */T /** 65 */t/** 66 */, /** 67 */U /** 68 */u/** 69 */) /** 70 */where /** 71 */T /** 72 */: /** 73 */U /** 74 */{ /** 75 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (9,144): warning CS1587: XML comment is not placed on a valid language element // /** 55 */private /** 56 */void /** 57 */Method/** 58 */</** 59 */T/** 60 */, /** 61 */U/** 62 */>/** 63 */(/** 64 */T /** 65 */t/** 66 */, /** 67 */U /** 68 */u/** 69 */) /** 70 */where /** 71 */T /** 72 */: /** 73 */U /** 74 */{ /** 75 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (9,155): warning CS1587: XML comment is not placed on a valid language element // /** 55 */private /** 56 */void /** 57 */Method/** 58 */</** 59 */T/** 60 */, /** 61 */U/** 62 */>/** 63 */(/** 64 */T /** 65 */t/** 66 */, /** 67 */U /** 68 */u/** 69 */) /** 70 */where /** 71 */T /** 72 */: /** 73 */U /** 74 */{ /** 75 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (9,165): warning CS1587: XML comment is not placed on a valid language element // /** 55 */private /** 56 */void /** 57 */Method/** 58 */</** 59 */T/** 60 */, /** 61 */U/** 62 */>/** 63 */(/** 64 */T /** 65 */t/** 66 */, /** 67 */U /** 68 */u/** 69 */) /** 70 */where /** 71 */T /** 72 */: /** 73 */U /** 74 */{ /** 75 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (9,176): warning CS1587: XML comment is not placed on a valid language element // /** 55 */private /** 56 */void /** 57 */Method/** 58 */</** 59 */T/** 60 */, /** 61 */U/** 62 */>/** 63 */(/** 64 */T /** 65 */t/** 66 */, /** 67 */U /** 68 */u/** 69 */) /** 70 */where /** 71 */T /** 72 */: /** 73 */U /** 74 */{ /** 75 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (9,191): warning CS1587: XML comment is not placed on a valid language element // /** 55 */private /** 56 */void /** 57 */Method/** 58 */</** 59 */T/** 60 */, /** 61 */U/** 62 */>/** 63 */(/** 64 */T /** 65 */t/** 66 */, /** 67 */U /** 68 */u/** 69 */) /** 70 */where /** 71 */T /** 72 */: /** 73 */U /** 74 */{ /** 75 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (9,202): warning CS1587: XML comment is not placed on a valid language element // /** 55 */private /** 56 */void /** 57 */Method/** 58 */</** 59 */T/** 60 */, /** 61 */U/** 62 */>/** 63 */(/** 64 */T /** 65 */t/** 66 */, /** 67 */U /** 68 */u/** 69 */) /** 70 */where /** 71 */T /** 72 */: /** 73 */U /** 74 */{ /** 75 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (9,213): warning CS1587: XML comment is not placed on a valid language element // /** 55 */private /** 56 */void /** 57 */Method/** 58 */</** 59 */T/** 60 */, /** 61 */U/** 62 */>/** 63 */(/** 64 */T /** 65 */t/** 66 */, /** 67 */U /** 68 */u/** 69 */) /** 70 */where /** 71 */T /** 72 */: /** 73 */U /** 74 */{ /** 75 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (9,224): warning CS1587: XML comment is not placed on a valid language element // /** 55 */private /** 56 */void /** 57 */Method/** 58 */</** 59 */T/** 60 */, /** 61 */U/** 62 */>/** 63 */(/** 64 */T /** 65 */t/** 66 */, /** 67 */U /** 68 */u/** 69 */) /** 70 */where /** 71 */T /** 72 */: /** 73 */U /** 74 */{ /** 75 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (9,235): warning CS1587: XML comment is not placed on a valid language element // /** 55 */private /** 56 */void /** 57 */Method/** 58 */</** 59 */T/** 60 */, /** 61 */U/** 62 */>/** 63 */(/** 64 */T /** 65 */t/** 66 */, /** 67 */U /** 68 */u/** 69 */) /** 70 */where /** 71 */T /** 72 */: /** 73 */U /** 74 */{ /** 75 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (10,21): warning CS1587: XML comment is not placed on a valid language element // /** 76 */public /** 77 */static /** 78 */int /** 79 */operator /** 80 */+/** 81 */(/** 82 */C /** 83 */c/** 84 */) /** 85 */{ /** 86 */return /** 87 */0/** 88 */; /** 89 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (10,37): warning CS1587: XML comment is not placed on a valid language element // /** 76 */public /** 77 */static /** 78 */int /** 79 */operator /** 80 */+/** 81 */(/** 82 */C /** 83 */c/** 84 */) /** 85 */{ /** 86 */return /** 87 */0/** 88 */; /** 89 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (10,50): warning CS1587: XML comment is not placed on a valid language element // /** 76 */public /** 77 */static /** 78 */int /** 79 */operator /** 80 */+/** 81 */(/** 82 */C /** 83 */c/** 84 */) /** 85 */{ /** 86 */return /** 87 */0/** 88 */; /** 89 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (10,68): warning CS1587: XML comment is not placed on a valid language element // /** 76 */public /** 77 */static /** 78 */int /** 79 */operator /** 80 */+/** 81 */(/** 82 */C /** 83 */c/** 84 */) /** 85 */{ /** 86 */return /** 87 */0/** 88 */; /** 89 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (10,78): warning CS1587: XML comment is not placed on a valid language element // /** 76 */public /** 77 */static /** 78 */int /** 79 */operator /** 80 */+/** 81 */(/** 82 */C /** 83 */c/** 84 */) /** 85 */{ /** 86 */return /** 87 */0/** 88 */; /** 89 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (10,88): warning CS1587: XML comment is not placed on a valid language element // /** 76 */public /** 77 */static /** 78 */int /** 79 */operator /** 80 */+/** 81 */(/** 82 */C /** 83 */c/** 84 */) /** 85 */{ /** 86 */return /** 87 */0/** 88 */; /** 89 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (10,99): warning CS1587: XML comment is not placed on a valid language element // /** 76 */public /** 77 */static /** 78 */int /** 79 */operator /** 80 */+/** 81 */(/** 82 */C /** 83 */c/** 84 */) /** 85 */{ /** 86 */return /** 87 */0/** 88 */; /** 89 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (10,109): warning CS1587: XML comment is not placed on a valid language element // /** 76 */public /** 77 */static /** 78 */int /** 79 */operator /** 80 */+/** 81 */(/** 82 */C /** 83 */c/** 84 */) /** 85 */{ /** 86 */return /** 87 */0/** 88 */; /** 89 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (10,120): warning CS1587: XML comment is not placed on a valid language element // /** 76 */public /** 77 */static /** 78 */int /** 79 */operator /** 80 */+/** 81 */(/** 82 */C /** 83 */c/** 84 */) /** 85 */{ /** 86 */return /** 87 */0/** 88 */; /** 89 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (10,131): warning CS1587: XML comment is not placed on a valid language element // /** 76 */public /** 77 */static /** 78 */int /** 79 */operator /** 80 */+/** 81 */(/** 82 */C /** 83 */c/** 84 */) /** 85 */{ /** 86 */return /** 87 */0/** 88 */; /** 89 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (10,147): warning CS1587: XML comment is not placed on a valid language element // /** 76 */public /** 77 */static /** 78 */int /** 79 */operator /** 80 */+/** 81 */(/** 82 */C /** 83 */c/** 84 */) /** 85 */{ /** 86 */return /** 87 */0/** 88 */; /** 89 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (10,157): warning CS1587: XML comment is not placed on a valid language element // /** 76 */public /** 77 */static /** 78 */int /** 79 */operator /** 80 */+/** 81 */(/** 82 */C /** 83 */c/** 84 */) /** 85 */{ /** 86 */return /** 87 */0/** 88 */; /** 89 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (10,168): warning CS1587: XML comment is not placed on a valid language element // /** 76 */public /** 77 */static /** 78 */int /** 79 */operator /** 80 */+/** 81 */(/** 82 */C /** 83 */c/** 84 */) /** 85 */{ /** 86 */return /** 87 */0/** 88 */; /** 89 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (11,21): warning CS1587: XML comment is not placed on a valid language element // /** 90 */public /** 91 */static /** 92 */explicit /** 93 */operator /** 94 */int/** 95 */(/** 96 */C /** 97 */c/** 98 */) /** 99 */{ /** 100 */return /** 101 */0/** 102 */; /** 103 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (11,37): warning CS1587: XML comment is not placed on a valid language element // /** 90 */public /** 91 */static /** 92 */explicit /** 93 */operator /** 94 */int/** 95 */(/** 96 */C /** 97 */c/** 98 */) /** 99 */{ /** 100 */return /** 101 */0/** 102 */; /** 103 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (11,55): warning CS1587: XML comment is not placed on a valid language element // /** 90 */public /** 91 */static /** 92 */explicit /** 93 */operator /** 94 */int/** 95 */(/** 96 */C /** 97 */c/** 98 */) /** 99 */{ /** 100 */return /** 101 */0/** 102 */; /** 103 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (11,73): warning CS1587: XML comment is not placed on a valid language element // /** 90 */public /** 91 */static /** 92 */explicit /** 93 */operator /** 94 */int/** 95 */(/** 96 */C /** 97 */c/** 98 */) /** 99 */{ /** 100 */return /** 101 */0/** 102 */; /** 103 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (11,85): warning CS1587: XML comment is not placed on a valid language element // /** 90 */public /** 91 */static /** 92 */explicit /** 93 */operator /** 94 */int/** 95 */(/** 96 */C /** 97 */c/** 98 */) /** 99 */{ /** 100 */return /** 101 */0/** 102 */; /** 103 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (11,95): warning CS1587: XML comment is not placed on a valid language element // /** 90 */public /** 91 */static /** 92 */explicit /** 93 */operator /** 94 */int/** 95 */(/** 96 */C /** 97 */c/** 98 */) /** 99 */{ /** 100 */return /** 101 */0/** 102 */; /** 103 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (11,106): warning CS1587: XML comment is not placed on a valid language element // /** 90 */public /** 91 */static /** 92 */explicit /** 93 */operator /** 94 */int/** 95 */(/** 96 */C /** 97 */c/** 98 */) /** 99 */{ /** 100 */return /** 101 */0/** 102 */; /** 103 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (11,116): warning CS1587: XML comment is not placed on a valid language element // /** 90 */public /** 91 */static /** 92 */explicit /** 93 */operator /** 94 */int/** 95 */(/** 96 */C /** 97 */c/** 98 */) /** 99 */{ /** 100 */return /** 101 */0/** 102 */; /** 103 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (11,127): warning CS1587: XML comment is not placed on a valid language element // /** 90 */public /** 91 */static /** 92 */explicit /** 93 */operator /** 94 */int/** 95 */(/** 96 */C /** 97 */c/** 98 */) /** 99 */{ /** 100 */return /** 101 */0/** 102 */; /** 103 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (11,138): warning CS1587: XML comment is not placed on a valid language element // /** 90 */public /** 91 */static /** 92 */explicit /** 93 */operator /** 94 */int/** 95 */(/** 96 */C /** 97 */c/** 98 */) /** 99 */{ /** 100 */return /** 101 */0/** 102 */; /** 103 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (11,155): warning CS1587: XML comment is not placed on a valid language element // /** 90 */public /** 91 */static /** 92 */explicit /** 93 */operator /** 94 */int/** 95 */(/** 96 */C /** 97 */c/** 98 */) /** 99 */{ /** 100 */return /** 101 */0/** 102 */; /** 103 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (11,166): warning CS1587: XML comment is not placed on a valid language element // /** 90 */public /** 91 */static /** 92 */explicit /** 93 */operator /** 94 */int/** 95 */(/** 96 */C /** 97 */c/** 98 */) /** 99 */{ /** 100 */return /** 101 */0/** 102 */; /** 103 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (11,178): warning CS1587: XML comment is not placed on a valid language element // /** 90 */public /** 91 */static /** 92 */explicit /** 93 */operator /** 94 */int/** 95 */(/** 96 */C /** 97 */c/** 98 */) /** 99 */{ /** 100 */return /** 101 */0/** 102 */; /** 103 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (12,23): warning CS1587: XML comment is not placed on a valid language element // /** 104 */private /** 105 */C/** 106 */(/** 107 */int /** 108 */x/** 109 */) /** 110 */: /** 111 */base/** 112 */(/** 113 */) /** 114 */{ /** 115 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (12,34): warning CS1587: XML comment is not placed on a valid language element // /** 104 */private /** 105 */C/** 106 */(/** 107 */int /** 108 */x/** 109 */) /** 110 */: /** 111 */base/** 112 */(/** 113 */) /** 114 */{ /** 115 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (12,45): warning CS1587: XML comment is not placed on a valid language element // /** 104 */private /** 105 */C/** 106 */(/** 107 */int /** 108 */x/** 109 */) /** 110 */: /** 111 */base/** 112 */(/** 113 */) /** 114 */{ /** 115 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (12,59): warning CS1587: XML comment is not placed on a valid language element // /** 104 */private /** 105 */C/** 106 */(/** 107 */int /** 108 */x/** 109 */) /** 110 */: /** 111 */base/** 112 */(/** 113 */) /** 114 */{ /** 115 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (12,70): warning CS1587: XML comment is not placed on a valid language element // /** 104 */private /** 105 */C/** 106 */(/** 107 */int /** 108 */x/** 109 */) /** 110 */: /** 111 */base/** 112 */(/** 113 */) /** 114 */{ /** 115 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (12,82): warning CS1587: XML comment is not placed on a valid language element // /** 104 */private /** 105 */C/** 106 */(/** 107 */int /** 108 */x/** 109 */) /** 110 */: /** 111 */base/** 112 */(/** 113 */) /** 114 */{ /** 115 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (12,94): warning CS1587: XML comment is not placed on a valid language element // /** 104 */private /** 105 */C/** 106 */(/** 107 */int /** 108 */x/** 109 */) /** 110 */: /** 111 */base/** 112 */(/** 113 */) /** 114 */{ /** 115 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (12,108): warning CS1587: XML comment is not placed on a valid language element // /** 104 */private /** 105 */C/** 106 */(/** 107 */int /** 108 */x/** 109 */) /** 110 */: /** 111 */base/** 112 */(/** 113 */) /** 114 */{ /** 115 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (12,119): warning CS1587: XML comment is not placed on a valid language element // /** 104 */private /** 105 */C/** 106 */(/** 107 */int /** 108 */x/** 109 */) /** 110 */: /** 111 */base/** 112 */(/** 113 */) /** 114 */{ /** 115 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (12,131): warning CS1587: XML comment is not placed on a valid language element // /** 104 */private /** 105 */C/** 106 */(/** 107 */int /** 108 */x/** 109 */) /** 110 */: /** 111 */base/** 112 */(/** 113 */) /** 114 */{ /** 115 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (12,143): warning CS1587: XML comment is not placed on a valid language element // /** 104 */private /** 105 */C/** 106 */(/** 107 */int /** 108 */x/** 109 */) /** 110 */: /** 111 */base/** 112 */(/** 113 */) /** 114 */{ /** 115 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (13,1): warning CS1587: XML comment is not placed on a valid language element // /** 116 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (15,16): warning CS1587: XML comment is not placed on a valid language element // /** 117 */enum /** 118 */E Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (16,1): warning CS1587: XML comment is not placed on a valid language element // /** 119 */{ Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (17,16): warning CS1587: XML comment is not placed on a valid language element // /** 120 */A/** 121 */, Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (18,1): warning CS1587: XML comment is not placed on a valid language element // /** 122 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (19,1): warning CS1587: XML comment is not placed on a valid language element // /** 123 */ Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/")); } [Fact] public void UnprocessedXMLComment_Expressions() { var source = @" class C { private int field = 1; private event System.Action FieldLikeEvent = () => { return; }; private C(int x = 1, int y = 2) { } private C(int x) : this(x, x + 1) { int y = x--; } } enum E { A = 1 + 1, } "; var revisedSource = new DocumentationCommentAdder().Visit(Parse(source).GetCompilationUnitRoot()).ToFullString(); // Manually verified that positions match dev11. CreateCompilationUtil(revisedSource).VerifyDiagnostics( // (4,41): warning CS0414: The field 'C.field' is assigned but its value is never used // /** 3 */private /** 4 */int /** 5 */field /** 6 */= /** 7 */1/** 8 */; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "field").WithArguments("C.field"), // (2,15): warning CS1587: XML comment is not placed on a valid language element // /** 0 */class /** 1 */C Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (3,1): warning CS1587: XML comment is not placed on a valid language element // /** 2 */{ Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (4,21): warning CS1587: XML comment is not placed on a valid language element // /** 3 */private /** 4 */int /** 5 */field /** 6 */= /** 7 */1/** 8 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (4,33): warning CS1587: XML comment is not placed on a valid language element // /** 3 */private /** 4 */int /** 5 */field /** 6 */= /** 7 */1/** 8 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (4,47): warning CS1587: XML comment is not placed on a valid language element // /** 3 */private /** 4 */int /** 5 */field /** 6 */= /** 7 */1/** 8 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (4,57): warning CS1587: XML comment is not placed on a valid language element // /** 3 */private /** 4 */int /** 5 */field /** 6 */= /** 7 */1/** 8 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (4,66): warning CS1587: XML comment is not placed on a valid language element // /** 3 */private /** 4 */int /** 5 */field /** 6 */= /** 7 */1/** 8 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (5,21): warning CS1587: XML comment is not placed on a valid language element // /** 9 */private /** 10 */event /** 11 */System/** 12 */./** 13 */Action /** 14 */FieldLikeEvent /** 15 */= /** 16 */(/** 17 */) /** 18 */=> /** 19 */{ /** 20 */return/** 21 */; /** 22 */}/** 23 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (5,36): warning CS1587: XML comment is not placed on a valid language element // /** 9 */private /** 10 */event /** 11 */System/** 12 */./** 13 */Action /** 14 */FieldLikeEvent /** 15 */= /** 16 */(/** 17 */) /** 18 */=> /** 19 */{ /** 20 */return/** 21 */; /** 22 */}/** 23 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (5,51): warning CS1587: XML comment is not placed on a valid language element // /** 9 */private /** 10 */event /** 11 */System/** 12 */./** 13 */Action /** 14 */FieldLikeEvent /** 15 */= /** 16 */(/** 17 */) /** 18 */=> /** 19 */{ /** 20 */return/** 21 */; /** 22 */}/** 23 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (5,61): warning CS1587: XML comment is not placed on a valid language element // /** 9 */private /** 10 */event /** 11 */System/** 12 */./** 13 */Action /** 14 */FieldLikeEvent /** 15 */= /** 16 */(/** 17 */) /** 18 */=> /** 19 */{ /** 20 */return/** 21 */; /** 22 */}/** 23 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (5,77): warning CS1587: XML comment is not placed on a valid language element // /** 9 */private /** 10 */event /** 11 */System/** 12 */./** 13 */Action /** 14 */FieldLikeEvent /** 15 */= /** 16 */(/** 17 */) /** 18 */=> /** 19 */{ /** 20 */return/** 21 */; /** 22 */}/** 23 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (5,101): warning CS1587: XML comment is not placed on a valid language element // /** 9 */private /** 10 */event /** 11 */System/** 12 */./** 13 */Action /** 14 */FieldLikeEvent /** 15 */= /** 16 */(/** 17 */) /** 18 */=> /** 19 */{ /** 20 */return/** 21 */; /** 22 */}/** 23 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (5,112): warning CS1587: XML comment is not placed on a valid language element // /** 9 */private /** 10 */event /** 11 */System/** 12 */./** 13 */Action /** 14 */FieldLikeEvent /** 15 */= /** 16 */(/** 17 */) /** 18 */=> /** 19 */{ /** 20 */return/** 21 */; /** 22 */}/** 23 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (5,122): warning CS1587: XML comment is not placed on a valid language element // /** 9 */private /** 10 */event /** 11 */System/** 12 */./** 13 */Action /** 14 */FieldLikeEvent /** 15 */= /** 16 */(/** 17 */) /** 18 */=> /** 19 */{ /** 20 */return/** 21 */; /** 22 */}/** 23 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (5,133): warning CS1587: XML comment is not placed on a valid language element // /** 9 */private /** 10 */event /** 11 */System/** 12 */./** 13 */Action /** 14 */FieldLikeEvent /** 15 */= /** 16 */(/** 17 */) /** 18 */=> /** 19 */{ /** 20 */return/** 21 */; /** 22 */}/** 23 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (5,145): warning CS1587: XML comment is not placed on a valid language element // /** 9 */private /** 10 */event /** 11 */System/** 12 */./** 13 */Action /** 14 */FieldLikeEvent /** 15 */= /** 16 */(/** 17 */) /** 18 */=> /** 19 */{ /** 20 */return/** 21 */; /** 22 */}/** 23 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (5,156): warning CS1587: XML comment is not placed on a valid language element // /** 9 */private /** 10 */event /** 11 */System/** 12 */./** 13 */Action /** 14 */FieldLikeEvent /** 15 */= /** 16 */(/** 17 */) /** 18 */=> /** 19 */{ /** 20 */return/** 21 */; /** 22 */}/** 23 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (5,171): warning CS1587: XML comment is not placed on a valid language element // /** 9 */private /** 10 */event /** 11 */System/** 12 */./** 13 */Action /** 14 */FieldLikeEvent /** 15 */= /** 16 */(/** 17 */) /** 18 */=> /** 19 */{ /** 20 */return/** 21 */; /** 22 */}/** 23 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (5,182): warning CS1587: XML comment is not placed on a valid language element // /** 9 */private /** 10 */event /** 11 */System/** 12 */./** 13 */Action /** 14 */FieldLikeEvent /** 15 */= /** 16 */(/** 17 */) /** 18 */=> /** 19 */{ /** 20 */return/** 21 */; /** 22 */}/** 23 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (5,192): warning CS1587: XML comment is not placed on a valid language element // /** 9 */private /** 10 */event /** 11 */System/** 12 */./** 13 */Action /** 14 */FieldLikeEvent /** 15 */= /** 16 */(/** 17 */) /** 18 */=> /** 19 */{ /** 20 */return/** 21 */; /** 22 */}/** 23 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (6,22): warning CS1587: XML comment is not placed on a valid language element // /** 24 */private /** 25 */C/** 26 */(/** 27 */int /** 28 */x /** 29 */= /** 30 */1/** 31 */, /** 32 */int /** 33 */y /** 34 */= /** 35 */2/** 36 */) /** 37 */{ /** 38 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (6,32): warning CS1587: XML comment is not placed on a valid language element // /** 24 */private /** 25 */C/** 26 */(/** 27 */int /** 28 */x /** 29 */= /** 30 */1/** 31 */, /** 32 */int /** 33 */y /** 34 */= /** 35 */2/** 36 */) /** 37 */{ /** 38 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (6,42): warning CS1587: XML comment is not placed on a valid language element // /** 24 */private /** 25 */C/** 26 */(/** 27 */int /** 28 */x /** 29 */= /** 30 */1/** 31 */, /** 32 */int /** 33 */y /** 34 */= /** 35 */2/** 36 */) /** 37 */{ /** 38 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (6,55): warning CS1587: XML comment is not placed on a valid language element // /** 24 */private /** 25 */C/** 26 */(/** 27 */int /** 28 */x /** 29 */= /** 30 */1/** 31 */, /** 32 */int /** 33 */y /** 34 */= /** 35 */2/** 36 */) /** 37 */{ /** 38 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (6,66): warning CS1587: XML comment is not placed on a valid language element // /** 24 */private /** 25 */C/** 26 */(/** 27 */int /** 28 */x /** 29 */= /** 30 */1/** 31 */, /** 32 */int /** 33 */y /** 34 */= /** 35 */2/** 36 */) /** 37 */{ /** 38 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (6,77): warning CS1587: XML comment is not placed on a valid language element // /** 24 */private /** 25 */C/** 26 */(/** 27 */int /** 28 */x /** 29 */= /** 30 */1/** 31 */, /** 32 */int /** 33 */y /** 34 */= /** 35 */2/** 36 */) /** 37 */{ /** 38 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (6,87): warning CS1587: XML comment is not placed on a valid language element // /** 24 */private /** 25 */C/** 26 */(/** 27 */int /** 28 */x /** 29 */= /** 30 */1/** 31 */, /** 32 */int /** 33 */y /** 34 */= /** 35 */2/** 36 */) /** 37 */{ /** 38 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (6,98): warning CS1587: XML comment is not placed on a valid language element // /** 24 */private /** 25 */C/** 26 */(/** 27 */int /** 28 */x /** 29 */= /** 30 */1/** 31 */, /** 32 */int /** 33 */y /** 34 */= /** 35 */2/** 36 */) /** 37 */{ /** 38 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (6,111): warning CS1587: XML comment is not placed on a valid language element // /** 24 */private /** 25 */C/** 26 */(/** 27 */int /** 28 */x /** 29 */= /** 30 */1/** 31 */, /** 32 */int /** 33 */y /** 34 */= /** 35 */2/** 36 */) /** 37 */{ /** 38 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (6,122): warning CS1587: XML comment is not placed on a valid language element // /** 24 */private /** 25 */C/** 26 */(/** 27 */int /** 28 */x /** 29 */= /** 30 */1/** 31 */, /** 32 */int /** 33 */y /** 34 */= /** 35 */2/** 36 */) /** 37 */{ /** 38 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (6,133): warning CS1587: XML comment is not placed on a valid language element // /** 24 */private /** 25 */C/** 26 */(/** 27 */int /** 28 */x /** 29 */= /** 30 */1/** 31 */, /** 32 */int /** 33 */y /** 34 */= /** 35 */2/** 36 */) /** 37 */{ /** 38 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (6,143): warning CS1587: XML comment is not placed on a valid language element // /** 24 */private /** 25 */C/** 26 */(/** 27 */int /** 28 */x /** 29 */= /** 30 */1/** 31 */, /** 32 */int /** 33 */y /** 34 */= /** 35 */2/** 36 */) /** 37 */{ /** 38 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (6,154): warning CS1587: XML comment is not placed on a valid language element // /** 24 */private /** 25 */C/** 26 */(/** 27 */int /** 28 */x /** 29 */= /** 30 */1/** 31 */, /** 32 */int /** 33 */y /** 34 */= /** 35 */2/** 36 */) /** 37 */{ /** 38 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (6,165): warning CS1587: XML comment is not placed on a valid language element // /** 24 */private /** 25 */C/** 26 */(/** 27 */int /** 28 */x /** 29 */= /** 30 */1/** 31 */, /** 32 */int /** 33 */y /** 34 */= /** 35 */2/** 36 */) /** 37 */{ /** 38 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (7,22): warning CS1587: XML comment is not placed on a valid language element // /** 39 */private /** 40 */C/** 41 */(/** 42 */int /** 43 */x/** 44 */) /** 45 */: /** 46 */this/** 47 */(/** 48 */x/** 49 */, /** 50 */x /** 51 */+ /** 52 */1/** 53 */) Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (7,32): warning CS1587: XML comment is not placed on a valid language element // /** 39 */private /** 40 */C/** 41 */(/** 42 */int /** 43 */x/** 44 */) /** 45 */: /** 46 */this/** 47 */(/** 48 */x/** 49 */, /** 50 */x /** 51 */+ /** 52 */1/** 53 */) Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (7,42): warning CS1587: XML comment is not placed on a valid language element // /** 39 */private /** 40 */C/** 41 */(/** 42 */int /** 43 */x/** 44 */) /** 45 */: /** 46 */this/** 47 */(/** 48 */x/** 49 */, /** 50 */x /** 51 */+ /** 52 */1/** 53 */) Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (7,55): warning CS1587: XML comment is not placed on a valid language element // /** 39 */private /** 40 */C/** 41 */(/** 42 */int /** 43 */x/** 44 */) /** 45 */: /** 46 */this/** 47 */(/** 48 */x/** 49 */, /** 50 */x /** 51 */+ /** 52 */1/** 53 */) Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (7,65): warning CS1587: XML comment is not placed on a valid language element // /** 39 */private /** 40 */C/** 41 */(/** 42 */int /** 43 */x/** 44 */) /** 45 */: /** 46 */this/** 47 */(/** 48 */x/** 49 */, /** 50 */x /** 51 */+ /** 52 */1/** 53 */) Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (7,76): warning CS1587: XML comment is not placed on a valid language element // /** 39 */private /** 40 */C/** 41 */(/** 42 */int /** 43 */x/** 44 */) /** 45 */: /** 46 */this/** 47 */(/** 48 */x/** 49 */, /** 50 */x /** 51 */+ /** 52 */1/** 53 */) Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (7,87): warning CS1587: XML comment is not placed on a valid language element // /** 39 */private /** 40 */C/** 41 */(/** 42 */int /** 43 */x/** 44 */) /** 45 */: /** 46 */this/** 47 */(/** 48 */x/** 49 */, /** 50 */x /** 51 */+ /** 52 */1/** 53 */) Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (7,100): warning CS1587: XML comment is not placed on a valid language element // /** 39 */private /** 40 */C/** 41 */(/** 42 */int /** 43 */x/** 44 */) /** 45 */: /** 46 */this/** 47 */(/** 48 */x/** 49 */, /** 50 */x /** 51 */+ /** 52 */1/** 53 */) Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (7,110): warning CS1587: XML comment is not placed on a valid language element // /** 39 */private /** 40 */C/** 41 */(/** 42 */int /** 43 */x/** 44 */) /** 45 */: /** 46 */this/** 47 */(/** 48 */x/** 49 */, /** 50 */x /** 51 */+ /** 52 */1/** 53 */) Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (7,120): warning CS1587: XML comment is not placed on a valid language element // /** 39 */private /** 40 */C/** 41 */(/** 42 */int /** 43 */x/** 44 */) /** 45 */: /** 46 */this/** 47 */(/** 48 */x/** 49 */, /** 50 */x /** 51 */+ /** 52 */1/** 53 */) Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (7,131): warning CS1587: XML comment is not placed on a valid language element // /** 39 */private /** 40 */C/** 41 */(/** 42 */int /** 43 */x/** 44 */) /** 45 */: /** 46 */this/** 47 */(/** 48 */x/** 49 */, /** 50 */x /** 51 */+ /** 52 */1/** 53 */) Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (7,142): warning CS1587: XML comment is not placed on a valid language element // /** 39 */private /** 40 */C/** 41 */(/** 42 */int /** 43 */x/** 44 */) /** 45 */: /** 46 */this/** 47 */(/** 48 */x/** 49 */, /** 50 */x /** 51 */+ /** 52 */1/** 53 */) Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (7,153): warning CS1587: XML comment is not placed on a valid language element // /** 39 */private /** 40 */C/** 41 */(/** 42 */int /** 43 */x/** 44 */) /** 45 */: /** 46 */this/** 47 */(/** 48 */x/** 49 */, /** 50 */x /** 51 */+ /** 52 */1/** 53 */) Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (7,163): warning CS1587: XML comment is not placed on a valid language element // /** 39 */private /** 40 */C/** 41 */(/** 42 */int /** 43 */x/** 44 */) /** 45 */: /** 46 */this/** 47 */(/** 48 */x/** 49 */, /** 50 */x /** 51 */+ /** 52 */1/** 53 */) Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (8,5): warning CS1587: XML comment is not placed on a valid language element // /** 54 */{ Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (9,9): warning CS1587: XML comment is not placed on a valid language element // /** 55 */int /** 56 */y /** 57 */= /** 58 */x/** 59 */--/** 60 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (9,22): warning CS1587: XML comment is not placed on a valid language element // /** 55 */int /** 56 */y /** 57 */= /** 58 */x/** 59 */--/** 60 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (9,33): warning CS1587: XML comment is not placed on a valid language element // /** 55 */int /** 56 */y /** 57 */= /** 58 */x/** 59 */--/** 60 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (9,44): warning CS1587: XML comment is not placed on a valid language element // /** 55 */int /** 56 */y /** 57 */= /** 58 */x/** 59 */--/** 60 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (9,54): warning CS1587: XML comment is not placed on a valid language element // /** 55 */int /** 56 */y /** 57 */= /** 58 */x/** 59 */--/** 60 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (9,65): warning CS1587: XML comment is not placed on a valid language element // /** 55 */int /** 56 */y /** 57 */= /** 58 */x/** 59 */--/** 60 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (10,5): warning CS1587: XML comment is not placed on a valid language element // /** 61 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (11,1): warning CS1587: XML comment is not placed on a valid language element // /** 62 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (13,15): warning CS1587: XML comment is not placed on a valid language element // /** 63 */enum /** 64 */E Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (14,1): warning CS1587: XML comment is not placed on a valid language element // /** 65 */{ Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (15,16): warning CS1587: XML comment is not placed on a valid language element // /** 66 */A /** 67 */= /** 68 */1 /** 69 */+ /** 70 */1/** 71 */, Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (15,27): warning CS1587: XML comment is not placed on a valid language element // /** 66 */A /** 67 */= /** 68 */1 /** 69 */+ /** 70 */1/** 71 */, Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (15,38): warning CS1587: XML comment is not placed on a valid language element // /** 66 */A /** 67 */= /** 68 */1 /** 69 */+ /** 70 */1/** 71 */, Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (15,49): warning CS1587: XML comment is not placed on a valid language element // /** 66 */A /** 67 */= /** 68 */1 /** 69 */+ /** 70 */1/** 71 */, Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (15,59): warning CS1587: XML comment is not placed on a valid language element // /** 66 */A /** 67 */= /** 68 */1 /** 69 */+ /** 70 */1/** 71 */, Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (16,1): warning CS1587: XML comment is not placed on a valid language element // /** 72 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (17,1): warning CS1587: XML comment is not placed on a valid language element // /** 73 */ Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/")); } [Fact] public void UnprocessedXMLComment_AfterAttribute() { var source = @" [System.Serializable] /// Comment class C { } "; CreateCompilationUtil(source).VerifyDiagnostics( // (3,1): warning CS1587: XML comment is not placed on a valid language element // /// Comment Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/")); } [Fact] public void UnprocessedXMLComment_CompiledOut() { var source = @" class C { #if false /// Comment #endif } "; CreateCompilationUtil(source).VerifyDiagnostics(); } [Fact] public void UnprocessedXMLComment_FilterTree() { var source1 = @" partial class C { /// Unprocessed 1 } "; var source2 = @" partial class C { /// Unprocessed 2 } "; var tree1 = Parse(source1, options: TestOptions.RegularWithDocumentationComments); var tree2 = Parse(source2, options: TestOptions.RegularWithDocumentationComments); var comp = CreateCompilation(new[] { tree1, tree2 }); comp.GetSemanticModel(tree1).GetDiagnostics().Verify( // (4,5): warning CS1587: XML comment is not placed on a valid language element // /// Unprocessed 1 Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/")); comp.GetSemanticModel(tree2).GetDiagnostics().Verify( // (4,5): warning CS1587: XML comment is not placed on a valid language element // /// Unprocessed 2 Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/")); } [Fact] public void UnprocessedXMLComment_Unparsed() { var source = @" partial class C { /// Unprocessed 1 } "; CreateCompilation(source).VerifyDiagnostics(); } [WorkItem(547139, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547139")] [Fact] public void UnprocessedXMLComment_Accessor() { var source = @" class MyClass { string MyProperty { get; /// <param name=""a"" /> /// <param name=""b"" /> set; } } "; CreateCompilationUtil(source).VerifyDiagnostics( // (7,9): warning CS1587: XML comment is not placed on a valid language element // /// <param name="a" /> Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/")); } /// <summary> /// Insert a numbered documentation comment as leading trivia on every token. /// </summary> private class DocumentationCommentAdder : CSharpSyntaxRewriter { private int _count; public override SyntaxToken VisitToken(SyntaxToken token) { var newToken = base.VisitToken(token); if (newToken.Width == 0 && newToken.Kind() != SyntaxKind.EndOfFileToken) { return newToken; } var existingLeadingTrivia = token.LeadingTrivia; var newLeadingTrivia = SyntaxFactory.ParseToken("/** " + (_count++) + " */1)").LeadingTrivia; return newToken.WithLeadingTrivia(existingLeadingTrivia.Concat(newLeadingTrivia)); } } #endregion WRN_UnprocessedXMLComment #region Invalid XML [Fact] public void InvalidXml() { var source = @" /// <unterminated_tag class C1 { } /// <unterminated_element> class C2 { } /// <no_attribute_value attr/> class C3 { } /// <bad_attribute_value attr=""&""/> class C4 { } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp); var expected = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <!-- Badly formed XML comment ignored for member ""T:C1"" --> <!-- Badly formed XML comment ignored for member ""T:C2"" --> <!-- Badly formed XML comment ignored for member ""T:C3"" --> <!-- Badly formed XML comment ignored for member ""T:C4"" --> </members> </doc> ").Trim(); Assert.Equal(expected, actual); } [Fact] public void InvalidXmlOnPartialTypes() { var source = @" /// <invalid partial class C { } /// <valid/> partial class C { } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp); var expected = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <!-- Badly formed XML comment ignored for member ""T:C"" --> </members> </doc> ").Trim(); Assert.Equal(expected, actual); } [Fact] public void InvalidXmlOnPartialMethods() { var source = @" partial class C { /// <invalid1 partial void M1(); /// <valid1/> partial void M2(); } partial class C { /// <valid2/> partial void M1() { } /// <invalid2 partial void M2() { } } "; // NOTE: separate error comment for each part. var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp); var expected = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""M:C.M1""> <valid2/> </member> <!-- Badly formed XML comment ignored for member ""M:C.M1"" --> <!-- Badly formed XML comment ignored for member ""M:C.M2"" --> </members> </doc> ").Trim(); Assert.Equal(expected, actual); } [ConditionalFact(typeof(ClrOnly), typeof(DesktopOnly))] [WorkItem(637435, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/637435")] [WorkItem(18610, "https://github.com/dotnet/roslyn/issues/18610")] public void NonXmlWhitespace() { var ch = '\u1680'; Assert.True(char.IsWhiteSpace(ch)); Assert.True(SyntaxFacts.IsWhitespace(ch)); Assert.False(XmlCharType.IsWhiteSpace(ch)); var xml = "<see\u1680cref='C'/>"; Assert.Throws<XmlException>(() => XElement.Parse(xml)); var sourceTemplate = @" /// {0} class C {{ }} "; var source = string.Format(sourceTemplate, xml); // NOTE: separate error comment for each part. var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp, // (2,4): warning CS1570: XML comment has badly formed XML -- 'The '\u1680' character, hexadecimal value 0x1680, cannot be included in a name.' // /// <see cref='C'/> Diagnostic(ErrorCode.WRN_XMLParseError, "").WithArguments("The '\u1680' character, hexadecimal value 0x1680, cannot be included in a name.")); var expected = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <!-- Badly formed XML comment ignored for member ""T:C"" --> </members> </doc> ").Trim(); Assert.Equal(expected, actual); } [ConditionalFact(typeof(ClrOnly), typeof(DesktopOnly))] [WorkItem(637435, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/637435")] [WorkItem(18610, "https://github.com/dotnet/roslyn/issues/18610")] public void Repro637435() { var sourceTemplate = @" // 1) Both Roslyn and Dev11 report an error. ///<see ///{0}cref='C1'/> class C1 {{ }} // 2) Both Roslyn and Dev11 report an error. /// <see /// {0}cref='C2'/> class C2 {{ }} // 3) Both Roslyn and Dev11 report an error. ///<see /// {0}cref='C3'/> class C3 {{ }} // 4) Dev11 reports an error, but Roslyn does not. /// <see ///{0}cref='C4'/> class C4 {{ }} "; var source = string.Format(sourceTemplate, '\u1680'); CreateCompilationUtil(source).GetDiagnostics().VerifyWithFallbackToErrorCodeOnlyForNonEnglish( // (4,4): warning CS1570: XML comment has badly formed XML -- 'Name cannot begin with the '\u1680' character, hexadecimal value 0x1680.' // ///<see Diagnostic(ErrorCode.WRN_XMLParseError, "").WithArguments("Name cannot begin with the '\u1680' character, hexadecimal value 0x1680."), // (11,4): warning CS1570: XML comment has badly formed XML -- 'Name cannot begin with the '\u1680' character, hexadecimal value 0x1680.' // /// <see Diagnostic(ErrorCode.WRN_XMLParseError, "").WithArguments("Name cannot begin with the '\u1680' character, hexadecimal value 0x1680."), // (18,4): warning CS1570: XML comment has badly formed XML -- 'Name cannot begin with the '\u1680' character, hexadecimal value 0x1680.' // ///<see Diagnostic(ErrorCode.WRN_XMLParseError, "").WithArguments("Name cannot begin with the '\u1680' character, hexadecimal value 0x1680.")); } #endregion Invalid XML #region Include [Fact] public void IncludeNone() { var xml = @" <root/> "; var xmlFile = Temp.CreateFile(extension: ".xml").WriteAllText(xml); string xmlFilePath = xmlFile.Path; var sourceTemplate = @" /// <include file='{0}' path='//target'/> class C {{ }} "; var comp = CreateCompilationUtil(string.Format(sourceTemplate, xmlFilePath)); var actual = GetDocumentationCommentText(comp); var expectedTemplate = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <!-- No matching elements were found for the following include tag --><include file=""{0}"" path=""//target"" /> </member> </members> </doc> ").Trim(); Assert.Equal(string.Format(expectedTemplate, xmlFilePath), actual); } [Fact] public void IncludeOne() { var xml = @" <root> <target stuff=""things"" /> </root> "; var xmlFile = Temp.CreateFile(extension: ".xml").WriteAllText(xml); string xmlFilePath = xmlFile.Path; var sourceTemplate = @" /// <include file='{0}' path='//target'/> class C {{ }} "; var comp = CreateCompilationUtil(string.Format(sourceTemplate, xmlFilePath)); var actual = GetDocumentationCommentText(comp); var expectedTemplate = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <target stuff=""things"" /> </member> </members> </doc> ").Trim(); Assert.Equal(string.Format(expectedTemplate, xmlFilePath), actual); } [Fact] public void IncludeMultiple() { var xml = @" <root> <target stuff=""things"" /> <parent> <target stuff=""garbage"" /> </parent> </root> "; var xmlFile = Temp.CreateFile(extension: ".xml").WriteAllText(xml); string xmlFilePath = xmlFile.Path; var sourceTemplate = @" /// <include file='{0}' path='//target'/> class C {{ }} "; var comp = CreateCompilationUtil(string.Format(sourceTemplate, xmlFilePath)); var actual = GetDocumentationCommentText(comp); var expectedTemplate = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <target stuff=""things"" /><target stuff=""garbage"" /> </member> </members> </doc> ").Trim(); Assert.Equal(string.Format(expectedTemplate, xmlFilePath), actual); } [Fact] public void IncludeWithChildren_Success() { var xml = @" <root> <target stuff=""things"" /> </root> "; var xmlFile = Temp.CreateFile(extension: ".xml").WriteAllText(xml); string xmlFilePath = xmlFile.Path; var sourceTemplate = @" /// <include file='{0}' path='//target'> /// <child /> /// </include> class C {{ }} "; var comp = CreateCompilationUtil(string.Format(sourceTemplate, xmlFilePath)); var actual = GetDocumentationCommentText(comp); var expectedTemplate = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <target stuff=""things"" /> </member> </members> </doc> ").Trim(); Assert.Equal(string.Format(expectedTemplate, xmlFilePath), actual); } [Fact] public void IncludeWithChildren_Failure() { var xml = @" <root> </root> "; var xmlFile = Temp.CreateFile(extension: ".xml").WriteAllText(xml); string xmlFilePath = xmlFile.Path; var sourceTemplate = @" /// <include file='{0}' path='//target'> /// <child /> /// </include> class C {{ }} "; var comp = CreateCompilationUtil(string.Format(sourceTemplate, xmlFilePath)); var actual = GetDocumentationCommentText(comp); var expectedTemplate = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <!-- No matching elements were found for the following include tag --><include file=""{0}"" path=""//target""> <child /> </include> </member> </members> </doc> ").Trim(); Assert.Equal(string.Format(expectedTemplate, xmlFilePath), actual); } [ConditionalFact(typeof(ClrOnly), typeof(DesktopOnly))] [WorkItem(18610, "https://github.com/dotnet/roslyn/issues/18610")] public void IncludeFileResolution() { var xml1 = @" <root> <include file=""test.xml"" path=""//element""/> <!--relative to d1 --> <include file=""d2/test.xml"" path=""//include""/> <!-- relative to root --> <element value=""1""/> </root> "; var xml2 = @" <root> <include file=""test.xml"" path=""//element""/> <!--relative to d2 --> <include file=""d3/test.xml"" path=""//include""/> <!-- relative to root --> <element value=""2""/> </root> "; var xml3 = @" <root> <include file=""test.xml"" path=""//element""/> <!--relative to d3 --> <element value=""3""/> </root> "; var rootDir = Temp.CreateDirectory(); var dir1 = rootDir.CreateDirectory("d1"); var dir1XmlFile = dir1.CreateFile("test.xml").WriteAllText(xml1); var dir2 = rootDir.CreateDirectory("d2"); var dir2XmlFile = dir2.CreateFile("test.xml").WriteAllText(xml2); var dir3 = rootDir.CreateDirectory("d3"); var dir3XmlFile = dir3.CreateFile("test.xml").WriteAllText(xml3); var source = @" /// <include file='d1\test.xml' path='//include' /> class C { } "; var tree = Parse(source, options: TestOptions.RegularWithDocumentationComments); var resolver = new XmlFileResolver(rootDir.Path); var comp = CSharpCompilation.Create("Test", new[] { tree }, new[] { MscorlibRef }, TestOptions.ReleaseDll.WithXmlReferenceResolver(resolver)); var actual = GetDocumentationCommentText(comp); var expected = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <element value=""1"" /><element value=""2"" /><element value=""3"" /> </member> </members> </doc> ").Trim(); Assert.Equal(expected, actual); } [Fact] public void WRN_InvalidInclude_Source() { var source = @" /// <include/> /// <include other='stuff'/> /// <include path='path'/> /// <include file='file'/> class C { } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp, // (2,5): warning CS1590: Invalid XML include element -- Missing file attribute // /// <include/> Diagnostic(ErrorCode.WRN_InvalidInclude, "<include/>").WithArguments("Missing file attribute"), // (3,5): warning CS1590: Invalid XML include element -- Missing file attribute // /// <include other='stuff'/> Diagnostic(ErrorCode.WRN_InvalidInclude, "<include other='stuff'/>").WithArguments("Missing file attribute"), // (4,5): warning CS1590: Invalid XML include element -- Missing file attribute // /// <include path='path'/> Diagnostic(ErrorCode.WRN_InvalidInclude, "<include path='path'/>").WithArguments("Missing file attribute"), // (5,5): warning CS1590: Invalid XML include element -- Missing path attribute // /// <include file='file'/> Diagnostic(ErrorCode.WRN_InvalidInclude, "<include file='file'/>").WithArguments("Missing path attribute")); var expected = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <!-- Include tag is invalid --><include /> <!-- Include tag is invalid --><include other=""stuff"" /> <!-- Include tag is invalid --><include path=""path"" /> <!-- Include tag is invalid --><include file=""file"" /> </member> </members> </doc> ").Trim(); Assert.Equal(expected, actual); } [Fact] public void WRN_InvalidInclude_Xml() { var xml = @" <root> <include/> <include other='stuff'/> <include path='path'/> <include file='file'/> </root> "; var xmlFile = Temp.CreateFile(extension: ".xml").WriteAllText(xml); var sourceTemplate = @" /// <include file='{0}' path='//include'/> class C {{ }} "; var comp = CreateCompilationUtil(string.Format(sourceTemplate, xmlFile.Path)); var actual = GetDocumentationCommentText(comp, // warning CS1590: Invalid XML include element -- Missing file attribute Diagnostic(ErrorCode.WRN_InvalidInclude).WithArguments("Missing file attribute"), // warning CS1590: Invalid XML include element -- Missing file attribute Diagnostic(ErrorCode.WRN_InvalidInclude).WithArguments("Missing file attribute"), // warning CS1590: Invalid XML include element -- Missing file attribute Diagnostic(ErrorCode.WRN_InvalidInclude).WithArguments("Missing file attribute"), // warning CS1590: Invalid XML include element -- Missing path attribute Diagnostic(ErrorCode.WRN_InvalidInclude).WithArguments("Missing path attribute")); // NOTE: the whitespace is external to the selected nodes, so it's not included. var expected = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <include /><include other=""stuff"" /><include path=""path"" /><include file=""file"" /> </member> </members> </doc> ").Trim(); Assert.Equal(expected, actual); } [Fact] public void WRN_FailedInclude_NonExistent_Source() { var source = @" /// <include file='file' path='path'/> class C { } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp, // (2,5): warning CS1589: Unable to include XML fragment 'path' of file 'file' -- File not found. // /// <include file='file' path='path'/> Diagnostic(ErrorCode.WRN_FailedInclude, "<include file='file' path='path'/>").WithArguments("file", "path", "File not found.")); var expected = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <!-- Failed to insert some or all of included XML --><include file=""file"" path=""path"" /> </member> </members> </doc> ").Trim(); Assert.Equal(expected, actual); } [Fact] public void WRN_FailedInclude_NonExistent_Xml() { var xml = @" <root> <include file='file' path='path'/> </root> "; var xmlFile = Temp.CreateFile(extension: ".xml").WriteAllText(xml); var sourceTemplate = @" /// <include file='{0}' path='//include'/> class C {{ }} "; var comp = CreateCompilationUtil(string.Format(sourceTemplate, xmlFile.Path)); var actual = GetDocumentationCommentText(comp, // 56e57d80-44fc-4e2c-b839-0bf3d9c830b7.xml(3,6): warning CS1589: Unable to include XML fragment 'path' of file 'file' -- File not found. Diagnostic(ErrorCode.WRN_FailedInclude).WithArguments("file", "path", "File not found.")); // NOTE: the whitespace is external to the selected nodes, so it's not included. var expected = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <include file=""file"" path=""path"" /> </member> </members> </doc> ").Trim(); Assert.Equal(expected, actual); } [ClrOnlyFact(ClrOnlyReason.Unknown)] public void WRN_FailedInclude_Locked_Source() { var xmlFile = Temp.CreateFile(extension: ".xml"); var xmlFilePath = xmlFile.Path; var includeTemplate = "<include file='{0}' path='path'/>"; var includeElement = string.Format(includeTemplate, xmlFilePath); var sourceTemplate = @" /// {0} class C {{ }} "; using (File.Open(xmlFilePath, FileMode.Open, FileAccess.Write, FileShare.None)) { var comp = CreateCompilationUtil(string.Format(sourceTemplate, includeElement)); var actual = GetDocumentationCommentText(comp, // (2,5): warning CS1589: Unable to include XML fragment 'path' of file 'c3af0dc5a3cf.xml' -- The process cannot access the file 'c3af0dc5a3cf.xml' because it is being used by another process. // /// <include file='c3af0dc5a3cf.xml' path='path'/> Diagnostic(ErrorCode.WRN_FailedInclude, includeElement).WithArguments(xmlFilePath, "path", string.Format("The process cannot access the file '{0}' because it is being used by another process.", xmlFilePath))); var expectedTemplate = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <!-- Failed to insert some or all of included XML --><include file=""{0}"" path=""path"" /> </member> </members> </doc> ").Trim(); Assert.Equal(string.Format(expectedTemplate, xmlFilePath), actual); } } [ClrOnlyFact(ClrOnlyReason.Unknown)] public void WRN_FailedInclude_Locked_Xml() { var xmlFile1 = Temp.CreateFile(extension: ".xml"); var xmlFilePath1 = xmlFile1.Path; var xmlFile2 = Temp.CreateFile(extension: ".xml").WriteAllText(string.Format("<include file='{0}' path='path'/>", xmlFilePath1)); var xmlFilePath2 = xmlFile2.Path; var sourceTemplate = @" /// <include file='{0}' path='//include'/> class C {{ }} "; using (File.Open(xmlFilePath1, FileMode.Open, FileAccess.Write, FileShare.None)) { var comp = CreateCompilationUtil(string.Format(sourceTemplate, xmlFilePath2)); var actual = GetDocumentationCommentText(comp, // 3fba660141b6.xml(1,2): warning CS1589: Unable to include XML fragment 'path' of file 'd4241d125755.xml' -- The process cannot access the file 'd4241d125755.xml' because it is being used by another process. Diagnostic(ErrorCode.WRN_FailedInclude).WithArguments(xmlFilePath1, "path", string.Format("The process cannot access the file '{0}' because it is being used by another process.", xmlFilePath1))); var expectedTemplate = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <include file=""{0}"" path=""path"" /> </member> </members> </doc> ").Trim(); Assert.Equal(string.Format(expectedTemplate, xmlFilePath1), actual); } } [Fact] public void WRN_FailedInclude_XPath_Source() { var xmlFile = Temp.CreateFile(extension: ".xml").WriteAllText("<element/>"); var xmlFilePath = xmlFile.Path; var includeTemplate = "<include file='{0}' path=':'/>"; var includeElement = string.Format(includeTemplate, xmlFilePath); var sourceTemplate = @" /// {0} class C {{ }} "; var comp = CreateCompilationUtil(string.Format(sourceTemplate, includeElement)); var actual = GetDocumentationCommentText(comp, // (2,5): warning CS1589: Unable to include XML fragment 'path' of file 'c3af0dc5a3cf.xml' -- The process cannot access the file 'c3af0dc5a3cf.xml' because it is being used by another process. // /// <include file='c3af0dc5a3cf.xml' path='path'/> Diagnostic(ErrorCode.WRN_FailedInclude, includeElement).WithArguments(xmlFilePath, ":", "':' has an invalid token.")); var expectedTemplate = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <!-- Failed to insert some or all of included XML --><include file=""{0}"" path="":"" /> </member> </members> </doc> ").Trim(); Assert.Equal(string.Format(expectedTemplate, xmlFilePath), actual); } [Fact] public void WRN_FailedInclude_XPath_Xml() { var xmlFile1 = Temp.CreateFile(extension: ".xml").WriteAllText("<element/>"); var xmlFilePath1 = xmlFile1.Path; var xmlFile2 = Temp.CreateFile(extension: ".xml").WriteAllText(string.Format("<include file='{0}' path=':'/>", xmlFilePath1)); var xmlFilePath2 = xmlFile2.Path; var sourceTemplate = @" /// <include file='{0}' path='//include'/> class C {{ }} "; var comp = CreateCompilationUtil(string.Format(sourceTemplate, xmlFilePath2)); var actual = GetDocumentationCommentText(comp, // 3fba660141b6.xml(1,2): warning CS1589: Unable to include XML fragment 'path' of file 'd4241d125755.xml' -- The process cannot access the file 'd4241d125755.xml' because it is being used by another process. Diagnostic(ErrorCode.WRN_FailedInclude).WithArguments(xmlFilePath1, ":", "':' has an invalid token.")); var expectedTemplate = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <include file=""{0}"" path="":"" /> </member> </members> </doc> ").Trim(); Assert.Equal(string.Format(expectedTemplate, xmlFilePath1), actual); } [ClrOnlyFact(ClrOnlyReason.DocumentationComment, Skip = "https://github.com/dotnet/roslyn/issues/8807")] public void WRN_XMLParseIncludeError_Source() { var xmlFile = Temp.CreateFile(extension: ".xml").WriteAllText("<OpenWithoutClose>"); var xmlFilePath = xmlFile.Path; var includeTemplate = "<include file='{0}' path='path'/>"; var includeElement = string.Format(includeTemplate, xmlFilePath); var sourceTemplate = @" /// {0} class C {{ }} "; var comp = CreateCompilationUtil(string.Format(sourceTemplate, includeElement)); var actual = GetDocumentationCommentText(comp, // 327697461814.xml(1,19): warning CS1592: Badly formed XML in included comments file -- 'Unexpected end of file has occurred. The following elements are not closed: OpenWithoutClose.' Diagnostic(ErrorCode.WRN_XMLParseIncludeError).WithArguments("Unexpected end of file has occurred. The following elements are not closed: OpenWithoutClose.")); var expectedTemplate = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <!-- Badly formed XML file ""{0}"" cannot be included --> </member> </members> </doc> ").Trim(); Assert.Equal(string.Format(expectedTemplate, TestHelpers.AsXmlCommentText(xmlFilePath)), actual); } [ConditionalFact(typeof(ClrOnly), typeof(DesktopOnly))] [WorkItem(18610, "https://github.com/dotnet/roslyn/issues/18610")] public void WRN_XMLParseIncludeError_Xml() { var xmlFile1 = Temp.CreateFile(extension: ".xml").WriteAllText("<OpenWithoutClose>"); var xmlFilePath1 = xmlFile1.Path; var xmlFile2 = Temp.CreateFile(extension: ".xml").WriteAllText(string.Format("<include file='{0}' path='path'/>", xmlFilePath1)); var xmlFilePath2 = xmlFile2.Path; var sourceTemplate = @" /// <include file='{0}' path='//include'/> class C {{ }} "; var comp = CreateCompilationUtil(string.Format(sourceTemplate, xmlFilePath2)); var actual = GetDocumentationCommentText(comp, // 408eee49f410.xml(1,19): warning CS1592: Badly formed XML in included comments file -- 'Unexpected end of file has occurred. The following elements are not closed: OpenWithoutClose.' Diagnostic(ErrorCode.WRN_XMLParseIncludeError).WithArguments("Unexpected end of file has occurred. The following elements are not closed: OpenWithoutClose.")); var expectedTemplate = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <!-- No matching elements were found for the following include tag --><include file=""{0}"" path=""//include"" /> </member> </members> </doc> ").Trim(); Assert.Equal(string.Format(expectedTemplate, xmlFilePath2), actual); } [Fact] public void IncludeCycle_Simple() { var xmlFile = Temp.CreateFile(extension: ".xml"); var xmlFilePath = xmlFile.Path; xmlFile.WriteAllText(string.Format(@"<include file=""{0}"" path=""//include""/>", xmlFilePath)); //Includes itself. var sourceTemplate = @" /// <include file='{0}' path='//include'/> class C {{ }} "; var comp = CreateCompilationUtil(string.Format(sourceTemplate, xmlFilePath)); var actual = GetDocumentationCommentText(comp, // 3fba660141b6.xml(1,2): warning CS1589: Unable to include XML fragment 'path' of file 'd4241d125755.xml' -- The process cannot access the file 'd4241d125755.xml' because it is being used by another process. Diagnostic(ErrorCode.WRN_FailedInclude).WithArguments(xmlFilePath, "//include", "Operation caused a stack overflow.")); var expectedTemplate = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <!-- No matching elements were found for the following include tag --><include file=""{0}"" path=""//include"" /> </member> </members> </doc> ").Trim(); Assert.Equal(string.Format(expectedTemplate, xmlFilePath), actual); } [Fact] public void IncludeCycle_Containment() { var xmlFile = Temp.CreateFile(extension: ".xml"); var xmlFilePath = xmlFile.Path; xmlFile.WriteAllText(string.Format(@"<parent><include file=""{0}"" path=""//parent""/></parent>", xmlFilePath)); //Includes its parent. var sourceTemplate = @" /// <include file='{0}' path='//include'/> class C {{ }} "; var comp = CreateCompilationUtil(string.Format(sourceTemplate, xmlFilePath)); // CONSIDER: differs from dev11, but this is a reasonable recovery. var actual = GetDocumentationCommentText(comp, // 3fba660141b6.xml(1,2): warning CS1589: Unable to include XML fragment 'path' of file 'd4241d125755.xml' -- The process cannot access the file 'd4241d125755.xml' because it is being used by another process. Diagnostic(ErrorCode.WRN_FailedInclude).WithArguments(xmlFilePath, "//parent", "Operation caused a stack overflow.")); var expectedTemplate = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <parent><!-- No matching elements were found for the following include tag --><include file=""{0}"" path=""//parent"" /></parent> </member> </members> </doc> ").Trim(); Assert.Equal(string.Format(expectedTemplate, xmlFilePath), actual); } [Fact] public void IncludeCycle_Nesting() { var xmlFile = Temp.CreateFile(extension: ".xml"); var xmlFilePath = xmlFile.Path; xmlFile.WriteAllText(string.Format(@" <include file=""{0}"" path=""//include""> <include file=""{0}"" path=""//include"" /> </include>", xmlFilePath)); //Everything includes everything, includes within includes. var sourceTemplate = @" /// <include file='{0}' path='//include'/> class C {{ }} "; var comp = CreateCompilationUtil(string.Format(sourceTemplate, xmlFilePath)); // CONSIDER: not checked against dev11 - just don't blow up. var actual = GetDocumentationCommentText(comp, // 1dc0fa5fb526.xml(2,2): warning CS1589: Unable to include XML fragment '//include' of file '1dc0fa5fb526.xml' -- Operation caused a stack overflow. Diagnostic(ErrorCode.WRN_FailedInclude).WithArguments(xmlFilePath, "//include", "Operation caused a stack overflow."), // 1dc0fa5fb526.xml(2,2): warning CS1589: Unable to include XML fragment '//include' of file '1dc0fa5fb526.xml' -- Operation caused a stack overflow. Diagnostic(ErrorCode.WRN_FailedInclude).WithArguments(xmlFilePath, "//include", "Operation caused a stack overflow."), // 1dc0fa5fb526.xml(2,2): warning CS1589: Unable to include XML fragment '//include' of file '1dc0fa5fb526.xml' -- Operation caused a stack overflow. Diagnostic(ErrorCode.WRN_FailedInclude).WithArguments(xmlFilePath, "//include", "Operation caused a stack overflow."), // 1dc0fa5fb526.xml(3,6): warning CS1589: Unable to include XML fragment '//include' of file '1dc0fa5fb526.xml' -- Operation caused a stack overflow. Diagnostic(ErrorCode.WRN_FailedInclude).WithArguments(xmlFilePath, "//include", "Operation caused a stack overflow."), // 1dc0fa5fb526.xml(3,6): warning CS1589: Unable to include XML fragment '//include' of file '1dc0fa5fb526.xml' -- Operation caused a stack overflow. Diagnostic(ErrorCode.WRN_FailedInclude).WithArguments(xmlFilePath, "//include", "Operation caused a stack overflow."), // 1dc0fa5fb526.xml(3,6): warning CS1589: Unable to include XML fragment '//include' of file '1dc0fa5fb526.xml' -- Operation caused a stack overflow. Diagnostic(ErrorCode.WRN_FailedInclude).WithArguments(xmlFilePath, "//include", "Operation caused a stack overflow.")); var expectedTemplate = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <!-- No matching elements were found for the following include tag --><include file=""{0}"" path=""//include""> <include file=""{0}"" path=""//include"" /> </include><!-- No matching elements were found for the following include tag --><include file=""{0}"" path=""//include""> <include file=""{0}"" path=""//include"" /> </include><!-- No matching elements were found for the following include tag --><include file=""{0}"" path=""//include"" /><!-- No matching elements were found for the following include tag --><include file=""{0}"" path=""//include""> <include file=""{0}"" path=""//include"" /> </include><!-- No matching elements were found for the following include tag --><include file=""{0}"" path=""//include"" /><!-- No matching elements were found for the following include tag --><include file=""{0}"" path=""//include"" /> </member> </members> </doc> ").Trim(); Assert.Equal(string.Format(expectedTemplate, xmlFilePath), actual); } // It should be legal to include the same acyclic element along multiple paths - that isn't a cycle. [Fact] public void IncludeAlongMultiplePaths() { var xmlFile = Temp.CreateFile(extension: ".xml"); var xmlFilePath = xmlFile.Path; string xmlTemplate = @" <root> <include file=""{0}"" path=""//stuff""/> <stuff/> </root>"; xmlFile.WriteAllText(string.Format(xmlTemplate, xmlFilePath)); var sourceTemplate = @" /// <include file='{0}' path='//include'/> /// <include file='{0}' path='//include'/> class C {{ }} "; var comp = CreateCompilationUtil(string.Format(sourceTemplate, xmlFilePath)); var actual = GetDocumentationCommentText(comp); var expected = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <stuff /> <stuff /> </member> </members> </doc> ").Trim(); Assert.Equal(expected, actual); } // As in dev11, the xpath is evaluated *before* includes are expanded. [Fact] public void XPathAssumesExpandedInclude() { var xmlFile1 = Temp.CreateFile(extension: ".xml"); var xmlFilePath1 = xmlFile1.Path; var xmlFile2 = Temp.CreateFile(extension: ".xml"); var xmlFilePath2 = xmlFile2.Path; string xmlTemplate1 = @"<include file=""{0}"" path=""//stuff""/>"; string xml2 = @"<stuff/>"; xmlFile1.WriteAllText(string.Format(xmlTemplate1, xmlFilePath2)); xmlFile2.WriteAllText(xml2); var sourceTemplate = @" /// <include file='{0}' path='//stuff'/> class C {{ }} "; var comp = CreateCompilationUtil(string.Format(sourceTemplate, xmlFilePath1)); var actual = GetDocumentationCommentText(comp); var expectedTemplate = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <!-- No matching elements were found for the following include tag --><include file=""{0}"" path=""//stuff"" /> </member> </members> </doc> ").Trim(); Assert.Equal(string.Format(expectedTemplate, xmlFilePath1), actual); } [WorkItem(554196, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/554196")] [Fact] public void XPathDocumentRoot() { var xmlFile = Temp.CreateFile(extension: ".xml"); var xmlFilePath = xmlFile.Path; xmlFile.WriteAllText(@"<?xml version=""1.0""?> <doc> <assembly> <name>Roslyn.Utilities</name> </assembly> <members> </members> </doc>"); var sourceTemplate = @" /// <include file=""{0}"" path=""/""/> enum A {{ }} /// <include file=""{0}"" path="".""/> enum B {{ }} /// <include file=""{0}"" path=""doc""/> enum C {{ }} /// <include file=""{0}"" path=""/doc""/> enum D {{ }} "; var comp = CreateCompilationUtil(string.Format(sourceTemplate, xmlFilePath)); var actual = GetDocumentationCommentText(comp, // (2,5): warning CS1589: Unable to include XML fragment '/' of file '012bf028d62c.xml' -- The XPath expression evaluated to unexpected type System.Xml.Linq.XDocument. // /// <include file="012bf028d62c.xml" path="/"/> Diagnostic(ErrorCode.WRN_FailedInclude, string.Format(@"<include file=""{0}"" path=""/""/>", xmlFilePath)).WithArguments(xmlFilePath, "/", "The XPath expression evaluated to unexpected type System.Xml.Linq.XDocument."), // (5,5): warning CS1589: Unable to include XML fragment '.' of file '012bf028d62c.xml' -- The XPath expression evaluated to unexpected type System.Xml.Linq.XDocument. // /// <include file="012bf028d62c.xml" path="."/> Diagnostic(ErrorCode.WRN_FailedInclude, string.Format(@"<include file=""{0}"" path="".""/>", xmlFilePath)).WithArguments(xmlFilePath, ".", "The XPath expression evaluated to unexpected type System.Xml.Linq.XDocument.")); var expected = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:A""> <!-- Failed to insert some or all of included XML --> </member> <member name=""T:B""> <!-- Failed to insert some or all of included XML --> </member> <member name=""T:C""> <doc> <assembly> <name>Roslyn.Utilities</name> </assembly> <members> </members> </doc> </member> <member name=""T:D""> <doc> <assembly> <name>Roslyn.Utilities</name> </assembly> <members> </members> </doc> </member> </members> </doc> ").Trim(); Assert.Equal(expected, actual); } #region Included crefs [Fact] public void IncludedCref_Valid() { var xmlFile = Temp.CreateFile(extension: ".xml").WriteAllText(@"<see cref=""Main""/>"); var xmlFilePath = xmlFile.Path; var includeElementTemplate = @"<include file='{0}' path='//see'/>"; var includeElement = string.Format(includeElementTemplate, xmlFilePath); var sourceTemplate = @" /// {0} class C {{ static void Main() {{ }} }} "; var comp = CreateCompilationUtil(string.Format(sourceTemplate, includeElement)); var actual = GetDocumentationCommentText(comp); var expected = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <see cref=""M:C.Main"" /> </member> </members> </doc> ").Trim(); Assert.Equal(expected, actual); } [Fact] public void IncludedCref_Verbatim() { var xmlFile = Temp.CreateFile(extension: ".xml").WriteAllText(@"<see cref=""M:Verbatim""/>"); var xmlFilePath = xmlFile.Path; var includeElementTemplate = @"<include file='{0}' path='//see'/>"; var includeElement = string.Format(includeElementTemplate, xmlFilePath); var sourceTemplate = @" /// {0} class C {{ static void Main() {{ }} }} "; var comp = CreateCompilationUtil(string.Format(sourceTemplate, includeElement)); var actual = GetDocumentationCommentText(comp); var expected = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <see cref=""M:Verbatim"" /> </member> </members> </doc> ").Trim(); Assert.Equal(expected, actual); } [Fact] public void IncludedCref_MultipleSyntaxTrees() { var xmlFile = Temp.CreateFile(extension: ".xml").WriteAllText(@"<see cref=""Int32""/>"); var xmlFilePath = xmlFile.Path; var includeElementTemplate = @"<include file='{0}' path='//see'/>"; var includeElement = string.Format(includeElementTemplate, xmlFilePath); var sourceTemplate = @" namespace N {{ /// {0} class C {{ }} }} namespace N {{ using System; /// {0} class C {{ }} }} "; var comp = CreateCompilationUtil(string.Format(sourceTemplate, includeElement)); // Error for the first include, but not for the second. var actual = GetDocumentationCommentText(comp, // (4,9): warning CS1574: XML comment has cref attribute 'Int32' that could not be resolved Diagnostic(ErrorCode.WRN_BadXMLRef, includeElement).WithArguments("Int32")); var expected = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:N.C""> <see cref=""!:Int32"" /> <see cref=""T:System.Int32"" /> </member> </members> </doc> ").Trim(); Assert.Equal(expected, actual); } [Fact] public void IncludedCref_SyntaxError() { var xmlFile = Temp.CreateFile(extension: ".xml").WriteAllText(@"<see cref=""#""/>"); var xmlFilePath = xmlFile.Path; var includeElementTemplate = @"<include file='{0}' path='//see'/>"; var includeElement = string.Format(includeElementTemplate, xmlFilePath); var sourceTemplate = @" /// {0} class C {{ }} "; var comp = CreateCompilationUtil(string.Format(sourceTemplate, includeElement)); var actual = GetDocumentationCommentText(comp, // (2,5): warning CS1584: XML comment has syntactically incorrect cref attribute '#' // /// <include file='aa671ee8adcd.xml' path='//see'/> Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, includeElement).WithArguments("#"), // (2,5): warning CS1658: Identifier expected. See also error CS1001. // /// <include file='aa671ee8adcd.xml' path='//see'/> Diagnostic(ErrorCode.WRN_ErrorOverride, includeElement).WithArguments("Identifier expected", "1001"), // (2,5): warning CS1658: Unexpected character '#'. See also error CS1056. // /// <include file='aa671ee8adcd.xml' path='//see'/> Diagnostic(ErrorCode.WRN_ErrorOverride, includeElement).WithArguments("Unexpected character '#'", "1056")); var expected = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <see cref=""!:#"" /> </member> </members> </doc> ").Trim(); Assert.Equal(expected, actual); } [Fact] public void IncludedCref_SemanticError() { var xmlFile = Temp.CreateFile(extension: ".xml").WriteAllText(@"<see cref=""Invalid""/>"); var xmlFilePath = xmlFile.Path; var includeElementTemplate = @"<include file='{0}' path='//see'/>"; var includeElement = string.Format(includeElementTemplate, xmlFilePath); var sourceTemplate = @" /// {0} class C {{ }} "; var comp = CreateCompilationUtil(string.Format(sourceTemplate, includeElement)); var actual = GetDocumentationCommentText(comp, // (2,5): warning CS1574: XML comment has cref attribute 'Invalid' that could not be resolved // /// <include file='f76ef125d03d.xml' path='//see'/> Diagnostic(ErrorCode.WRN_BadXMLRef, includeElement).WithArguments("Invalid")); var expected = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <see cref=""!:Invalid"" /> </member> </members> </doc> ").Trim(); Assert.Equal(expected, actual); } [WorkItem(552495, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552495")] [Fact] public void IncludeMismatchedQuotationMarks() { var source = @" /// <summary> /// <include file='C:\file.xml"" path=""/""/> /// </summary> class C { } "; // This is mode typically used by the IDE. var tree = Parse(source, options: TestOptions.Regular.WithDocumentationMode(DocumentationMode.Parse)); var compilation = CreateCompilation(tree); compilation.VerifyDiagnostics(); } [WorkItem(598371, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/598371")] [Fact] public void CrefParameterOrReturnTypeLookup1() { var seeElement = @"<see cref=""Y.implicit operator Y.Y""/>"; var xmlFile = Temp.CreateFile(extension: ".xml").WriteAllText(seeElement); var xmlFilePath = xmlFile.Path; var includeElementTemplate = @"<include file='{0}' path='//see'/>"; var includeElement = string.Format(includeElementTemplate, xmlFilePath); var sourceTemplate = @" class X {{ /// {0} /// {1} public class Y : X {{ public static implicit operator Y(int x) {{ return null; }} }} }} "; var comp = CreateCompilationUtil(string.Format(sourceTemplate, seeElement, includeElement)); var actual = GetDocumentationCommentText(comp); var expected = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:X.Y""> <see cref=""M:X.Y.op_Implicit(System.Int32)~X.Y"" /> <see cref=""M:X.Y.op_Implicit(System.Int32)~X.Y"" /> </member> </members> </doc> ").Trim(); Assert.Equal(expected, actual); } [WorkItem(586815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/586815")] [Fact] public void CrefParameterOrReturnTypeLookup2() { var seeElement = @"<see cref=""Foo(B)""/>"; var xmlFile = Temp.CreateFile(extension: ".xml").WriteAllText(seeElement); var xmlFilePath = xmlFile.Path; var includeElementTemplate = @"<include file='{0}' path='//see'/>"; var includeElement = string.Format(includeElementTemplate, xmlFilePath); var sourceTemplate = @" class A<T> {{ class B : A<B> {{ /// {0} /// {1} void Foo(B x) {{ }} }} }} "; var comp = CreateCompilationUtil(string.Format(sourceTemplate, seeElement, includeElement)); var actual = GetDocumentationCommentText(comp); var expected = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""M:A`1.B.Foo(A{A{`0}.B}.B)""> <see cref=""M:A`1.B.Foo(A{A{`0}.B}.B)"" /> <see cref=""M:A`1.B.Foo(A{A{`0}.B}.B)"" /> </member> </members> </doc> ").Trim(); Assert.Equal(expected, actual); } #endregion Included crefs #region Included names [Fact] public void IncludedName_Success() { var xml = @" <root> <member0> <summary> <typeparam name=""T"">Text</typeparam> <typeparamref name=""T"">Text</typeparamref> </summary> </member0> <member1> <summary> <param name=""x"">Text</param> <paramref name=""x"">Text</paramref> </summary> </member1> <member2> <summary> <param name=""u"">Text</param> <paramref name=""u"">Text</paramref> <typeparam name=""U"">Text</typeparam> <typeparamref name=""U"">Text</typeparamref> </summary> </member2> <member3> <summary> <param name=""v"">Text</param> <paramref name=""v"">Text</paramref> <typeparam name=""V"">Text</typeparam> <typeparamref name=""V"">Text</typeparamref> </summary> </member3> </root> "; var xmlFile = Temp.CreateFile(extension: ".xml").WriteAllText(xml); var xmlFilePath = xmlFile.Path; var includeElementTemplate = @"<include file='{0}' path='root/member{1}/summary'/>"; string[] includeElements = Enumerable.Range(0, 4).Select(i => string.Format(includeElementTemplate, xmlFilePath, i)).ToArray(); var sourceTemplate = @" /// {0} class C<T> {{ /// {1} int this[int x] {{ get {{ return 0; }} set {{ }} }} /// {2} void M<U>(U u) {{ }} /// {3} delegate void D<V>(V v) {{ }} }} "; var comp = CreateCompilationUtil(string.Format(sourceTemplate, includeElements)); var actual = GetDocumentationCommentText(comp); var expected = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C`1""> <summary> <typeparam name=""T"">Text</typeparam> <typeparamref name=""T"">Text</typeparamref> </summary> </member> <member name=""P:C`1.Item(System.Int32)""> <summary> <param name=""x"">Text</param> <paramref name=""x"">Text</paramref> </summary> </member> <member name=""M:C`1.M``1(``0)""> <summary> <param name=""u"">Text</param> <paramref name=""u"">Text</paramref> <typeparam name=""U"">Text</typeparam> <typeparamref name=""U"">Text</typeparamref> </summary> </member> <member name=""T:C`1.D`1""> <summary> <param name=""v"">Text</param> <paramref name=""v"">Text</paramref> <typeparam name=""V"">Text</typeparam> <typeparamref name=""V"">Text</typeparamref> </summary> </member> </members> </doc> ").Trim(); Assert.Equal(expected, actual); } [Fact] public void IncludedName_OverlappedWithSource() { var xml = @" <root> <param name=""u"">Text</param> <param name=""v"">Text</param> <paramref name=""u"">Text</paramref> <paramref name=""v"">Text</paramref> <typeparam name=""U"">Text</typeparam> <typeparam name=""V"">Text</typeparam> <typeparamref name=""U"">Text</typeparamref> <typeparamref name=""V"">Text</typeparamref> </root> "; var xmlFile = Temp.CreateFile(extension: ".xml").WriteAllText(xml); var xmlFilePath = xmlFile.Path; var includeElementTemplate = @"<include file='{0}' path='root/*'/>"; string includeElement = string.Format(includeElementTemplate, xmlFilePath); var sourceTemplate = @" /// <param name=""u"">Text</param> /// <param name=""v"">Text</param> /// <paramref name=""u"">Text</paramref> /// <paramref name=""v"">Text</paramref> /// <typeparam name=""U"">Text</typeparam> /// <typeparam name=""V"">Text</typeparam> /// <typeparamref name=""U"">Text</typeparamref> /// <typeparamref name=""V"">Text</typeparamref> /// {0} delegate void D<U, V>(U u, V v); "; var comp = CreateCompilationUtil(string.Format(sourceTemplate, includeElement)); var actual = GetDocumentationCommentText(comp, // (10,5): warning CS1571: XML comment has a duplicate param tag for 'u' // /// <include file='f59a2ef50b4d.xml' path='root/*'/> Diagnostic(ErrorCode.WRN_DuplicateParamTag, includeElement).WithArguments("u"), // (10,5): warning CS1571: XML comment has a duplicate param tag for 'v' // /// <include file='f59a2ef50b4d.xml' path='root/*'/> Diagnostic(ErrorCode.WRN_DuplicateParamTag, includeElement).WithArguments("v"), // (10,5): warning CS1710: XML comment has a duplicate typeparam tag for 'U' // /// <include file='f59a2ef50b4d.xml' path='root/*'/> Diagnostic(ErrorCode.WRN_DuplicateTypeParamTag, includeElement).WithArguments("U"), // (10,5): warning CS1710: XML comment has a duplicate typeparam tag for 'V' // /// <include file='f59a2ef50b4d.xml' path='root/*'/> Diagnostic(ErrorCode.WRN_DuplicateTypeParamTag, includeElement).WithArguments("V")); var expected = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:D`2""> <param name=""u"">Text</param> <param name=""v"">Text</param> <paramref name=""u"">Text</paramref> <paramref name=""v"">Text</paramref> <typeparam name=""U"">Text</typeparam> <typeparam name=""V"">Text</typeparam> <typeparamref name=""U"">Text</typeparamref> <typeparamref name=""V"">Text</typeparamref> <param name=""u"">Text</param><param name=""v"">Text</param><paramref name=""u"">Text</paramref><paramref name=""v"">Text</paramref><typeparam name=""U"">Text</typeparam><typeparam name=""V"">Text</typeparam><typeparamref name=""U"">Text</typeparamref><typeparamref name=""V"">Text</typeparamref> </member> </members> </doc> ").Trim(); Assert.Equal(expected, actual); } [Fact] public void IncludedName_MixedWithSource() { var xml = @" <root> <param name=""v"">Text</param> <paramref name=""u"">Text</paramref> <paramref name=""v"">Text</paramref> <typeparam name=""V"">Text</typeparam> <typeparamref name=""U"">Text</typeparamref> <typeparamref name=""V"">Text</typeparamref> </root> "; var xmlFile = Temp.CreateFile(extension: ".xml").WriteAllText(xml); var xmlFilePath = xmlFile.Path; var includeElementTemplate = @"<include file='{0}' path='root/*'/>"; string includeElement = string.Format(includeElementTemplate, xmlFilePath); var sourceTemplate = @" /// <param name=""u"">Text</param> /// <paramref name=""u"">Text</paramref> /// <paramref name=""v"">Text</paramref> /// <typeparam name=""U"">Text</typeparam> /// <typeparamref name=""U"">Text</typeparamref> /// <typeparamref name=""V"">Text</typeparamref> /// {0} delegate void D<U, V>(U u, V v); "; var comp = CreateCompilationUtil(string.Format(sourceTemplate, includeElement)); var actual = GetDocumentationCommentText(comp); var expected = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:D`2""> <param name=""u"">Text</param> <paramref name=""u"">Text</paramref> <paramref name=""v"">Text</paramref> <typeparam name=""U"">Text</typeparam> <typeparamref name=""U"">Text</typeparamref> <typeparamref name=""V"">Text</typeparamref> <param name=""v"">Text</param><paramref name=""u"">Text</paramref><paramref name=""v"">Text</paramref><typeparam name=""V"">Text</typeparam><typeparamref name=""U"">Text</typeparamref><typeparamref name=""V"">Text</typeparamref> </member> </members> </doc> ").Trim(); Assert.Equal(expected, actual); } [Fact] public void IncludedName_SyntacticError() { var xmlFile = Temp.CreateFile(extension: ".xml").WriteAllText(@"<typeparam name=""#""/>"); var xmlFilePath = xmlFile.Path; var includeElementTemplate = @"<include file='{0}' path='//typeparam'/>"; var includeElement = string.Format(includeElementTemplate, xmlFilePath); var sourceTemplate = @" /// {0} class C<T> {{ }} "; var comp = CreateCompilationUtil(string.Format(sourceTemplate, includeElement)); var actual = GetDocumentationCommentText(comp, // (2,5): warning CS1658: Unexpected character '#'. See also error CS1056. // /// <include file='3d2052d10358.xml' path='//typeparam'/> Diagnostic(ErrorCode.WRN_ErrorOverride, includeElement).WithArguments("Unexpected character '#'", "1056"), // (3,9): warning CS1712: Type parameter 'T' has no matching typeparam tag in the XML comment on 'C<T>' (but other type parameters do) // class C<T> { } Diagnostic(ErrorCode.WRN_MissingTypeParamTag, "T").WithArguments("T", "C<T>")); var expected = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C`1""> <typeparam name=""#"" /> </member> </members> </doc> ").Trim(); Assert.Equal(expected, actual); } [Fact] public void IncludedName_SemanticError() { var xmlFile = Temp.CreateFile(extension: ".xml").WriteAllText(@"<param name=""Q""/>"); var xmlFilePath = xmlFile.Path; var includeElementTemplate = @"<include file='{0}' path='//param'/>"; var includeElement = string.Format(includeElementTemplate, xmlFilePath); var sourceTemplate = @" class C {{ /// {0} void M(int x) {{ }} }} "; var comp = CreateCompilationUtil(string.Format(sourceTemplate, includeElement)); var actual = GetDocumentationCommentText(comp, // (4,9): warning CS1572: XML comment has a param tag for 'Q', but there is no parameter by that name // /// <include file='4f57d3a0db53.xml' path='//param'/> Diagnostic(ErrorCode.WRN_UnmatchedParamTag, includeElement).WithArguments("Q"), // (5,16): warning CS1573: Parameter 'x' has no matching param tag in the XML comment for 'C.M(int)' (but other parameters do) // void M(int x) { } Diagnostic(ErrorCode.WRN_MissingParamTag, "x").WithArguments("x", "C.M(int)")); var expected = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""M:C.M(System.Int32)""> <param name=""Q"" /> </member> </members> </doc> ").Trim(); Assert.Equal(expected, actual); } [Fact] public void IncludedName_DuplicateParameterName() { var xmlFile = Temp.CreateFile(extension: ".xml").WriteAllText(@"<param name=""x""/>"); var xmlFilePath = xmlFile.Path; var includeElementTemplate = @"<include file='{0}' path='//param'/>"; var includeElement = string.Format(includeElementTemplate, xmlFilePath); var sourceTemplate = @" class C {{ /// {0} void M(int x, int x) {{ }} }} "; var comp = CreateCompilationUtil(string.Format(sourceTemplate, includeElement)); // NOTE: no *xml* diagnostics, not no diagnostics. var actual = GetDocumentationCommentText(comp); var expected = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""M:C.M(System.Int32,System.Int32)""> <param name=""x"" /> </member> </members> </doc> ").Trim(); Assert.Equal(expected, actual); } [ClrOnlyFact(ClrOnlyReason.DocumentationComment, Skip = "https://github.com/dotnet/roslyn/issues/8807")] public void IncludedName_DuplicateNameAttribute() { var xmlFile = Temp.CreateFile(extension: ".xml").WriteAllText(@"<param name=""x"" name=""y""/>"); var xmlFilePath = xmlFile.Path; var includeElementTemplate = @"<include file='{0}' path='//param'/>"; var includeElement = string.Format(includeElementTemplate, xmlFilePath); var sourceTemplate = @" class C {{ /// {0} void M(int x, int y) {{ }} }} "; var comp = CreateCompilationUtil(string.Format(sourceTemplate, includeElement)); var actual = GetDocumentationCommentText(comp, // df33b60df5a9.xml(1,17): warning CS1592: Badly formed XML in included comments file -- ''name' is a duplicate attribute name.' Diagnostic(ErrorCode.WRN_XMLParseIncludeError).WithArguments("'name' is a duplicate attribute name.")); var expectedTemplate = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""M:C.M(System.Int32,System.Int32)""> <!-- Badly formed XML file ""{0}"" cannot be included --> </member> </members> </doc> ").Trim(); Assert.Equal(string.Format(expectedTemplate, TestHelpers.AsXmlCommentText(xmlFilePath)), actual); } [Fact] public void IncludedName_PartialMethod() { string xml = @" <root> <param name=""x""/> <param name=""y""/> </root>"; var xmlFile = Temp.CreateFile(extension: ".xml").WriteAllText(xml); var xmlFilePath = xmlFile.Path; var includeElementTemplate = @"<include file='{0}' path='//param'/>"; var includeElement = string.Format(includeElementTemplate, xmlFilePath); var sourceTemplate = @" partial class C {{ /// Part 1. /// {0} partial void M(int x, int y); }} partial class C {{ /// Part 2. /// {0} partial void M(int x, int y) {{ }} }} "; var comp = CreateCompilationUtil(string.Format(sourceTemplate, includeElement)); var actual = GetDocumentationCommentText(comp); var expectedTemplate = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""M:C.M(System.Int32,System.Int32)""> Part 2. <param name=""x"" /><param name=""y"" /> </member> </members> </doc> ").Trim(); Assert.Equal(string.Format(expectedTemplate, TestHelpers.AsXmlCommentText(xmlFilePath)), actual); } [Fact] [WorkItem(21348, "https://github.com/dotnet/roslyn/issues/21348")] public void IncludedName_TypeParamAndTypeParamRefHandling() { var xml = @" <root> <target> Included section <summary> See <typeparam/>. See <typeparam name=""X""/>. See <typeparam name=""Y""/>. See <typeparam name=""XY""/>. </summary> <remarks></remarks> </target> <target> Included section <summary> See <typeparamref/>. See <typeparamref name=""X""/>. See <typeparamref name=""Y""/>. See <typeparamref name=""XY""/>. </summary> <remarks></remarks> </target> </root> "; var xmlFile = Temp.CreateFile(extension: ".xml").WriteAllText(xml); var xmlFilePath = xmlFile.Path; var includeElementTemplate = @"<include file='{0}' path='//target'/>"; string includeElement = string.Format(includeElementTemplate, xmlFilePath); var sourceTemplate = @" /// {0} class OuterClass<X> {{ /// {0} class InnerClass<Y> {{ /// {0} public void Foo() {{}} }} }} "; var comp = CreateCompilationUtil(string.Format(sourceTemplate, includeElement)); var actual = GetDocumentationCommentText(comp, expectedDiagnostics: new[] { // (3,5): warning CS1711: XML comment has a typeparam tag for 'Y', but there is no type parameter by that name // /// <include file='b16c2dc7f738.xml' path='//target'/> Diagnostic(ErrorCode.WRN_UnmatchedTypeParamTag, includeElement).WithArguments("Y").WithLocation(3, 5), // (3,5): warning CS1711: XML comment has a typeparam tag for 'XY', but there is no type parameter by that name // /// <include file='b16c2dc7f738.xml' path='//target'/> Diagnostic(ErrorCode.WRN_UnmatchedTypeParamTag, includeElement).WithArguments("XY").WithLocation(3, 5), // (3,5): warning CS1735: XML comment on 'OuterClass<X>' has a typeparamref tag for 'Y', but there is no type parameter by that name // /// <include file='b16c2dc7f738.xml' path='//target'/> Diagnostic(ErrorCode.WRN_UnmatchedTypeParamRefTag, includeElement).WithArguments("Y", "OuterClass<X>").WithLocation(3, 5), // (3,5): warning CS1735: XML comment on 'OuterClass<X>' has a typeparamref tag for 'XY', but there is no type parameter by that name // /// <include file='b16c2dc7f738.xml' path='//target'/> Diagnostic(ErrorCode.WRN_UnmatchedTypeParamRefTag, includeElement).WithArguments("XY", "OuterClass<X>").WithLocation(3, 5), // (6,9): warning CS1711: XML comment has a typeparam tag for 'X', but there is no type parameter by that name // /// <include file='b16c2dc7f738.xml' path='//target'/> Diagnostic(ErrorCode.WRN_UnmatchedTypeParamTag, includeElement).WithArguments("X").WithLocation(6, 9), // (6,9): warning CS1711: XML comment has a typeparam tag for 'XY', but there is no type parameter by that name // /// <include file='b16c2dc7f738.xml' path='//target'/> Diagnostic(ErrorCode.WRN_UnmatchedTypeParamTag, includeElement).WithArguments("XY").WithLocation(6, 9), // (6,9): warning CS1735: XML comment on 'OuterClass<X>.InnerClass<Y>' has a typeparamref tag for 'XY', but there is no type parameter by that name // /// <include file='b16c2dc7f738.xml' path='//target'/> Diagnostic(ErrorCode.WRN_UnmatchedTypeParamRefTag, includeElement).WithArguments("XY", "OuterClass<X>.InnerClass<Y>").WithLocation(6, 9), // (9,13): warning CS1711: XML comment has a typeparam tag for 'X', but there is no type parameter by that name // /// <include file='b16c2dc7f738.xml' path='//target'/> Diagnostic(ErrorCode.WRN_UnmatchedTypeParamTag, includeElement).WithArguments("X").WithLocation(9, 13), // (9,13): warning CS1711: XML comment has a typeparam tag for 'Y', but there is no type parameter by that name // /// <include file='b16c2dc7f738.xml' path='//target'/> Diagnostic(ErrorCode.WRN_UnmatchedTypeParamTag, includeElement).WithArguments("Y").WithLocation(9, 13), // (9,13): warning CS1711: XML comment has a typeparam tag for 'XY', but there is no type parameter by that name // /// <include file='b16c2dc7f738.xml' path='//target'/> Diagnostic(ErrorCode.WRN_UnmatchedTypeParamTag, includeElement).WithArguments("XY").WithLocation(9, 13), // (9,13): warning CS1735: XML comment on 'OuterClass<X>.InnerClass<Y>.Foo()' has a typeparamref tag for 'XY', but there is no type parameter by that name // /// <include file='b16c2dc7f738.xml' path='//target'/> Diagnostic(ErrorCode.WRN_UnmatchedTypeParamRefTag, includeElement).WithArguments("XY", "OuterClass<X>.InnerClass<Y>.Foo()").WithLocation(9, 13) }); var expected = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:OuterClass`1""> <target> Included section <summary> See <typeparam />. See <typeparam name=""X"" />. See <typeparam name=""Y"" />. See <typeparam name=""XY"" />. </summary> <remarks /> </target><target> Included section <summary> See <typeparamref />. See <typeparamref name=""X"" />. See <typeparamref name=""Y"" />. See <typeparamref name=""XY"" />. </summary> <remarks /> </target> </member> <member name=""T:OuterClass`1.InnerClass`1""> <target> Included section <summary> See <typeparam />. See <typeparam name=""X"" />. See <typeparam name=""Y"" />. See <typeparam name=""XY"" />. </summary> <remarks /> </target><target> Included section <summary> See <typeparamref />. See <typeparamref name=""X"" />. See <typeparamref name=""Y"" />. See <typeparamref name=""XY"" />. </summary> <remarks /> </target> </member> <member name=""M:OuterClass`1.InnerClass`1.Foo""> <target> Included section <summary> See <typeparam />. See <typeparam name=""X"" />. See <typeparam name=""Y"" />. See <typeparam name=""XY"" />. </summary> <remarks /> </target><target> Included section <summary> See <typeparamref />. See <typeparamref name=""X"" />. See <typeparamref name=""Y"" />. See <typeparamref name=""XY"" />. </summary> <remarks /> </target> </member> </members> </doc> ").Trim(); Assert.Equal(expected, actual); } #endregion Included names #endregion Include #region For single symbol [Fact] public void ForSingleType() { var source = @" /// <summary> /// A /// B /// C /// </summary> class C { } "; var compilation = CreateCompilationUtil(source); var type = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var actualText = DocumentationCommentCompiler.GetDocumentationCommentXml(type, processIncludes: true, cancellationToken: default(CancellationToken)); var expectedText = @"<member name=""T:C""> <summary> A B C </summary> </member> "; Assert.Equal(expectedText, actualText); } [Fact] public void ForSingleTypeWithInclude() { var xmlFile = Temp.CreateFile(extension: ".xml").WriteAllText("<stuff />"); var xmlFilePath = xmlFile.Path; var sourceTemplate = @" /// <summary> /// A /// <include file='{0}' path='stuff'/> /// C /// </summary> class C {{ /// Shouldn't appear in doc comment for C. void M(){{}} }} "; var source = string.Format(sourceTemplate, xmlFilePath); var compilation = CreateCompilationUtil(source); var type = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); // Expand includes. { var actualText = DocumentationCommentCompiler.GetDocumentationCommentXml(type, processIncludes: true, cancellationToken: default(CancellationToken)); var expectedText = @"<member name=""T:C""> <summary> A <stuff /> C </summary> </member> "; Assert.Equal(expectedText, actualText); } // Do not expand includes. { var actualText = DocumentationCommentCompiler.GetDocumentationCommentXml(type, processIncludes: false, cancellationToken: default(CancellationToken)); var expectedTextTemplate = @"<member name=""T:C""> <summary> A <include file='{0}' path='stuff'/> C </summary> </member> "; Assert.Equal(string.Format(expectedTextTemplate, xmlFilePath), actualText); } } #endregion #region Misc [Fact] public void FilterTree() { var source1 = @" partial class C { /// <see cref=""Bogus1""/> void M1() { } } "; var source2 = @" partial class C { /// <see cref=""Bogus2""/> void M2() { } } "; var tree1 = SyntaxFactory.ParseSyntaxTree(source1, options: TestOptions.RegularWithDocumentationComments); var tree2 = SyntaxFactory.ParseSyntaxTree(source2, options: TestOptions.RegularWithDocumentationComments); // Files passed in order. var comp = CreateCompilation(new[] { tree1, tree2 }, assemblyName: "Test"); var actual1 = GetDocumentationCommentText(comp, null, filterTree: tree1, expectedDiagnostics: new[] { // (4,20): warning CS1574: XML comment has cref attribute 'Bogus1' that could not be resolved // /// <see cref="Bogus1"/> Diagnostic(ErrorCode.WRN_BadXMLRef, "Bogus1").WithArguments("Bogus1") }); var expected1 = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""M:C.M1""> <see cref=""!:Bogus1""/> </member> </members> </doc> ".Trim(); Assert.Equal(expected1, actual1); var actual2 = GetDocumentationCommentText(comp, null, filterTree: tree2, expectedDiagnostics: new[] { // (4,20): warning CS1574: XML comment has cref attribute 'Bogus2' that could not be resolved // /// <see cref="Bogus2"/> Diagnostic(ErrorCode.WRN_BadXMLRef, "Bogus2").WithArguments("Bogus2")}); var expected2 = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""M:C.M2""> <see cref=""!:Bogus2""/> </member> </members> </doc> ".Trim(); Assert.Equal(expected2, actual2); } [Fact] public void Utf8() { // NOTE: This character is interesting because it has a three-byte utf-8 representation. var source = "///\u20ac" + @" public class C { static void Main() {} } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp, "OutputName"); var expected = (@" <?xml version=""1.0""?> <doc> <assembly> <name>OutputName</name> </assembly> <members> <member name=""T:C""> " + "\u20ac" + @" </member> </members> </doc> ").Trim(); Assert.Equal(expected, actual); } [Fact, WorkItem(921838, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/921838")] public void InaccessibleMembers() { var source = @"/// <summary> /// See <see cref=""C.M""/>. /// </summary> class A { } class C { private void M() { } }"; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp, "OutputName"); var expected = (@" <?xml version=""1.0""?> <doc> <assembly> <name>OutputName</name> </assembly> <members> <member name=""T:A""> <summary> See <see cref=""M:C.M""/>. </summary> </member> </members> </doc>").Trim(); Assert.Equal(expected, actual); } [WorkItem(531144, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531144")] [Fact] public void NamespaceCref() { var source = @" /// <see cref=""System""/> public class C { static void Main() {} } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp); var expected = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <see cref=""N:System""/> </member> </members> </doc> ").Trim(); Assert.Equal(expected, actual); } [WorkItem(531144, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531144")] [Fact] public void SymbolKinds() { var source = @" using AliasN = System; using AliasT = System.String; class Generic<T> { /// <summary> /// Namespace alias <see cref=""AliasN""/> /// Type alias <see cref=""AliasT""/> /// Array type <see cref=""C[]""/> -- warning /// There's no way to get a cref to bind to an assembly. /// Dynamic type <see cref=""dynamic""/> -- warning /// Error type <see cref=""C{T}""/> -- warning /// Event <see cref=""E""/> /// Field <see cref=""f""/> /// There's no way to get a cref to bind to a label. /// There's no way to get a cref to bind to a local. /// Method <see cref=""M""/> /// There's no way to get a cref to bind to a net module. /// Named type <see cref=""C""/> /// Namespace <see cref=""System""/> /// There's no way to get a cref to bind to a parameter. /// Pointer type <see cref=""C*""/> -- warning /// Property <see cref=""P""/> /// There's no way to get a cref to bind to a range variable. /// Type parameter <see cref=""T""/> -- warning /// </summary> public class C { int f; event System.Action E; int P { get; set; } void M() {} } } "; var comp = CreateCompilationUtil(source); comp.VerifyDiagnostics( // Cref parse warnings. // (10,31): warning CS1584: XML comment has syntactically incorrect cref attribute 'C[]' // /// Array type <see cref="C[]"/> -- warning Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "C").WithArguments("C[]"), // (23,33): warning CS1584: XML comment has syntactically incorrect cref attribute 'C*' // /// Pointer type <see cref="C*"/> -- warning Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "C").WithArguments("C*"), // Boring warnings. // (31,29): warning CS0067: The event 'Generic<T>.C.E' is never used // event System.Action E; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("Generic<T>.C.E"), // (30,13): warning CS0169: The field 'Generic<T>.C.f' is never used // int f; Diagnostic(ErrorCode.WRN_UnreferencedField, "f").WithArguments("Generic<T>.C.f"), // Cref binding warnings. // (12,33): warning CS1574: XML comment has cref attribute 'dynamic' that could not be resolved // /// Dynamic type <see cref="dynamic"/> -- warning Diagnostic(ErrorCode.WRN_BadXMLRef, "dynamic").WithArguments("dynamic"), // (13,31): warning CS1574: XML comment has cref attribute 'C{T}' that could not be resolved // /// Error type <see cref="C{T}"/> -- warning Diagnostic(ErrorCode.WRN_BadXMLRef, "C{T}").WithArguments("C{T}"), // (26,35): warning CS1723: XML comment has cref attribute 'T' that refers to a type parameter // /// Type parameter <see cref="T"/> -- warning Diagnostic(ErrorCode.WRN_BadXMLRefTypeVar, "T").WithArguments("T")); var actual = GetDocumentationCommentText(comp, // (12,33): warning CS1574: XML comment has cref attribute 'dynamic' that could not be resolved // /// Dynamic type <see cref="dynamic"/> -- warning Diagnostic(ErrorCode.WRN_BadXMLRef, "dynamic").WithArguments("dynamic"), // (13,31): warning CS1574: XML comment has cref attribute 'C{T}' that could not be resolved // /// Error type <see cref="C{T}"/> -- warning Diagnostic(ErrorCode.WRN_BadXMLRef, "C{T}").WithArguments("C{T}"), // (26,35): warning CS1723: XML comment has cref attribute 'T' that refers to a type parameter // /// Type parameter <see cref="T"/> -- warning Diagnostic(ErrorCode.WRN_BadXMLRefTypeVar, "T").WithArguments("T")); var expected = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:Generic`1.C""> <summary> Namespace alias <see cref=""N:System""/> Type alias <see cref=""T:System.String""/> Array type <see cref=""!:C[]""/> -- warning There's no way to get a cref to bind to an assembly. Dynamic type <see cref=""!:dynamic""/> -- warning Error type <see cref=""!:C&lt;T&gt;""/> -- warning Event <see cref=""E:Generic`1.C.E""/> Field <see cref=""F:Generic`1.C.f""/> There's no way to get a cref to bind to a label. There's no way to get a cref to bind to a local. Method <see cref=""M:Generic`1.C.M""/> There's no way to get a cref to bind to a net module. Named type <see cref=""T:Generic`1.C""/> Namespace <see cref=""N:System""/> There's no way to get a cref to bind to a parameter. Pointer type <see cref=""!:C*""/> -- warning Property <see cref=""P:Generic`1.C.P""/> There's no way to get a cref to bind to a range variable. Type parameter <see cref=""!:T""/> -- warning </summary> </member> </members> </doc> ").Trim(); Assert.Equal(expected, actual); } [WorkItem(530695, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530695")] [Fact] public void FieldDocComment() { var source = @" class C { /// 1 int f; /// 2 int g, h; /// 3 event System.Action p; /// 4 event System.Action q, r; } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp); var expected = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""F:C.f""> 1 </member> <member name=""F:C.g""> 2 </member> <member name=""F:C.h""> 2 </member> <member name=""E:C.p""> 3 </member> <member name=""E:C.q""> 4 </member> <member name=""E:C.r""> 4 </member> </members> </doc> ").Trim(); Assert.Equal(expected, actual); } [WorkItem(530695, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530695")] [Fact] public void FieldDocCommentDiagnostics() { var source = @" class C { /// <see cref=""fake1""/> int f; /// <see cref=""fake2""/> int g, h; /// <see cref=""fake3""/> event System.Action p; /// <see cref=""fake4""/> event System.Action q, r; } "; // Duplicate diagnostics, as in dev11. var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp, // (4,20): warning CS1574: XML comment has cref attribute 'fake1' that could not be resolved // /// <see cref="fake1"/> Diagnostic(ErrorCode.WRN_BadXMLRef, "fake1").WithArguments("fake1"), // (6,20): warning CS1574: XML comment has cref attribute 'fake2' that could not be resolved // /// <see cref="fake2"/> Diagnostic(ErrorCode.WRN_BadXMLRef, "fake2").WithArguments("fake2"), // (6,20): warning CS1574: XML comment has cref attribute 'fake2' that could not be resolved // /// <see cref="fake2"/> Diagnostic(ErrorCode.WRN_BadXMLRef, "fake2").WithArguments("fake2"), // (9,20): warning CS1574: XML comment has cref attribute 'fake3' that could not be resolved // /// <see cref="fake3"/> Diagnostic(ErrorCode.WRN_BadXMLRef, "fake3").WithArguments("fake3"), // (11,20): warning CS1574: XML comment has cref attribute 'fake4' that could not be resolved // /// <see cref="fake4"/> Diagnostic(ErrorCode.WRN_BadXMLRef, "fake4").WithArguments("fake4"), // (11,20): warning CS1574: XML comment has cref attribute 'fake4' that could not be resolved // /// <see cref="fake4"/> Diagnostic(ErrorCode.WRN_BadXMLRef, "fake4").WithArguments("fake4")); var expected = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""F:C.f""> <see cref=""!:fake1""/> </member> <member name=""F:C.g""> <see cref=""!:fake2""/> </member> <member name=""F:C.h""> <see cref=""!:fake2""/> </member> <member name=""E:C.p""> <see cref=""!:fake3""/> </member> <member name=""E:C.q""> <see cref=""!:fake4""/> </member> <member name=""E:C.r""> <see cref=""!:fake4""/> </member> </members> </doc> ").Trim(); Assert.Equal(expected, actual); } [WorkItem(531187, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531187")] [Fact] public void DelegateDocComments() { var source = @" /// <param name=""t""/> /// <param name=""q""/> /// <paramref name=""t""/> /// <paramref name=""q""/> /// <typeparam name=""T""/> /// <typeparam name=""Q""/> /// <typeparamref name=""T""/> /// <typeparamref name=""Q""/> delegate void D<T, U>(T t, U u); "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp, // (3,18): warning CS1572: XML comment has a param tag for 'q', but there is no parameter by that name // /// <param name="q"/> Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "q").WithArguments("q"), // (5,21): warning CS1734: XML comment on 'D<T, U>' has a paramref tag for 'q', but there is no parameter by that name // /// <paramref name="q"/> Diagnostic(ErrorCode.WRN_UnmatchedParamRefTag, "q").WithArguments("q", "D<T, U>"), // (7,22): warning CS1711: XML comment has a typeparam tag for 'Q', but there is no type parameter by that name // /// <typeparam name="Q"/> Diagnostic(ErrorCode.WRN_UnmatchedTypeParamTag, "Q").WithArguments("Q"), // (9,25): warning CS1735: XML comment on 'D<T, U>' has a typeparamref tag for 'Q', but there is no type parameter by that name // /// <typeparamref name="Q"/> Diagnostic(ErrorCode.WRN_UnmatchedTypeParamRefTag, "Q").WithArguments("Q", "D<T, U>"), // (10,30): warning CS1573: Parameter 'u' has no matching param tag in the XML comment for 'D<T, U>' (but other parameters do) // delegate void D<T, U>(T t, U u); Diagnostic(ErrorCode.WRN_MissingParamTag, "u").WithArguments("u", "D<T, U>"), // (10,20): warning CS1712: Type parameter 'U' has no matching typeparam tag in the XML comment on 'D<T, U>' (but other type parameters do) // delegate void D<T, U>(T t, U u); Diagnostic(ErrorCode.WRN_MissingTypeParamTag, "U").WithArguments("U", "D<T, U>")); var expected = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:D`2""> <param name=""t""/> <param name=""q""/> <paramref name=""t""/> <paramref name=""q""/> <typeparam name=""T""/> <typeparam name=""Q""/> <typeparamref name=""T""/> <typeparamref name=""Q""/> </member> </members> </doc> ").Trim(); Assert.Equal(expected, actual); } [Fact] public void NoWarn1591() { var source = @" public class C { } "; var tree = Parse(source, options: TestOptions.RegularWithDocumentationComments); var warnDict = new Dictionary<string, ReportDiagnostic> { { MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_MissingXMLComment), ReportDiagnostic.Suppress } }; var comp = CreateCompilation(tree, options: TestOptions.ReleaseDll.WithSpecificDiagnosticOptions(warnDict), assemblyName: "Test"); comp.VerifyDiagnostics(); //NOTE: no WRN_MissingXMLComment var actual = GetDocumentationCommentText(comp, // (2,14): warning CS1591: Missing XML comment for publicly visible type or member 'C' // public class C { } Diagnostic(ErrorCode.WRN_MissingXMLComment, "C").WithArguments("C")); //Filtering happens later. var expected = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> </members> </doc> ").Trim(); Assert.Equal(expected, actual); } [WorkItem(531233, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531233")] [Fact] public void CrefAttributeInOtherElement() { var source = @" class C { /// <other cref=""C""/> void M() { } } "; var comp = CreateCompilationUtil(source); comp.VerifyDiagnostics(); var actual = GetDocumentationCommentText(comp); var expected = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""M:C.M""> <other cref=""T:C""/> </member> </members> </doc> ").Trim(); Assert.Equal(expected, actual); } [WorkItem(531233, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531233")] [Fact] public void NameAttributeInOtherElement() { var source = @" class C { /// <other name=""X""/> void M() { } } "; var comp = CreateCompilationUtil(source); comp.VerifyDiagnostics(); var actual = GetDocumentationCommentText(comp); var expected = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""M:C.M""> <other name=""X""/> </member> </members> </doc> ").Trim(); Assert.Equal(expected, actual); } [Fact] public void GetParseDiagnostics() { var source = @" class Program { /// <summary> /// static void Main(string[] args) { } }"; var comp = CreateCompilationUtil(source); Assert.NotEmpty(comp.GetParseDiagnostics()); Assert.Empty(comp.GetDeclarationDiagnostics()); Assert.Empty(comp.GetMethodBodyDiagnostics()); Assert.NotEmpty(comp.GetDiagnostics()); } [WorkItem(531349, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531349")] [Fact] public void GetDeclarationDiagnostics() { var source = @" class Program { /// <summary> /// /// </summary> /// <param name=""a""></param> static void Main(string[] args) { } }"; var comp = CreateCompilationUtil(source); Assert.Empty(comp.GetParseDiagnostics()); Assert.Empty(comp.GetDeclarationDiagnostics()); Assert.Equal(2, comp.GetMethodBodyDiagnostics().Count()); Assert.Equal(2, comp.GetDiagnostics().Count()); } [WorkItem(531409, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531409")] [Fact] public void ExplicitInterfaceImplementation() { var source = @" interface I<T> { void M(); } class C<T> : I<T> { /// <see cref=""object""/> void I<T>.M() { } } "; var comp = CreateCompilationUtil(source); comp.VerifyDiagnostics(); var actual = GetDocumentationCommentText(comp); var expected = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""M:C`1.I{T}#M""> <see cref=""T:System.Object""/> </member> </members> </doc> ").Trim(); Assert.Equal(expected, actual); } [Fact] public void ArrayRankSpecifierOrder() { var source = @" class C { /// <see cref=""M""/> int[][,] M(int[,][] x) { return null; } } "; var comp = CreateCompilationUtil(source); comp.VerifyDiagnostics(); var actual = GetDocumentationCommentText(comp); var expected = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""M:C.M(System.Int32[][0:,0:])""> <see cref=""M:C.M(System.Int32[][0:,0:])""/> </member> </members> </doc> ").Trim(); Assert.Equal(expected, actual); } // As in dev11, the pragma has no effect. [ClrOnlyFact(ClrOnlyReason.DocumentationComment, Skip = "https://github.com/dotnet/roslyn/issues/8807")] public void PragmaDisableWarningInXmlFile() { var xmlFile = Temp.CreateFile(extension: ".xml").WriteAllText("&"); var sourceTemplate = @" #pragma warning disable 1592 /// <include file='{0}' path='element'/> class C {{ }} "; var comp = CreateCompilationUtil(string.Format(sourceTemplate, xmlFile.Path)); var actual = GetDocumentationCommentText(comp, // 054c2dcb7959.xml(1,1): warning CS1592: Badly formed XML in included comments file -- 'Data at the root level is invalid.' Diagnostic(ErrorCode.WRN_XMLParseIncludeError).WithArguments("Data at the root level is invalid.")); var expectedTemplate = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <!-- Badly formed XML file ""{0}"" cannot be included --> </member> </members> </doc> ").Trim(); Assert.Equal(string.Format(expectedTemplate, TestHelpers.AsXmlCommentText(xmlFile.Path)), actual); } [Fact] public void DynamicInParameters() { // BREAK: Dev11 drops candidates with "dynamic" anywhere in their parameter lists. // As a result, it does not match the first two or last two crefs. var source = @" /// <see cref=""M1(dynamic)""/> /// <see cref=""M1(C{dynamic})""/> /// <see cref=""M2(object)""/> /// <see cref=""M2(C{object})""/> /// /// <see cref=""M1(object)""/> /// <see cref=""M1(C{object})""/> /// <see cref=""M2(dynamic)""/> /// <see cref=""M2(C{dynamic})""/> class C<T> { void M1(dynamic p) { } void M1(C<dynamic> p) { } void M2(object p) { } void M2(C<object> p) { } } "; SyntaxTree tree = Parse(source, options: TestOptions.RegularWithDocumentationComments); var comp = CreateCompilationWithMscorlib40AndSystemCore(new[] { tree }, assemblyName: "Test"); var actualText = GetDocumentationCommentText(comp); var expectedText = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C`1""> <see cref=""M:C`1.M1(System.Object)""/> <see cref=""M:C`1.M1(C{System.Object})""/> <see cref=""M:C`1.M2(System.Object)""/> <see cref=""M:C`1.M2(C{System.Object})""/> <see cref=""M:C`1.M1(System.Object)""/> <see cref=""M:C`1.M1(C{System.Object})""/> <see cref=""M:C`1.M2(System.Object)""/> <see cref=""M:C`1.M2(C{System.Object})""/> </member> </members> </doc>".Trim(); Assert.Equal(expectedText, actualText); } [WorkItem(546989, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546989")] [Fact] public void GenericMethodWithoutTypeParameters1() { var source = @" /// <see cref=""M""/> /// <see cref=""M(int)""/> /// <see cref=""M{T}""/> /// <see cref=""M{T}(int)""/> /// /// <see cref=""C.M""/> /// <see cref=""C.M(int)""/> /// <see cref=""C.M{T}""/> /// <see cref=""C.M{T}(int)""/> class C { void M(int x) { } void M(string x) { } void M<T>(int x) { } void M<T>(string x) { } } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp, // (2,16): warning CS0419: Ambiguous reference in cref attribute: 'M'. Assuming 'C.M(int)', but could have also matched other overloads including 'C.M(string)'. // /// <see cref="M"/> Diagnostic(ErrorCode.WRN_AmbiguousXMLReference, "M").WithArguments("M", "C.M(int)", "C.M(string)"), // (4,16): warning CS0419: Ambiguous reference in cref attribute: 'M{T}'. Assuming 'C.M<T>(int)', but could have also matched other overloads including 'C.M<T>(string)'. // /// <see cref="M{T}"/> Diagnostic(ErrorCode.WRN_AmbiguousXMLReference, "M{T}").WithArguments("M{T}", "C.M<T>(int)", "C.M<T>(string)"), // (7,16): warning CS0419: Ambiguous reference in cref attribute: 'C.M'. Assuming 'C.M(int)', but could have also matched other overloads including 'C.M(string)'. // /// <see cref="C.M"/> Diagnostic(ErrorCode.WRN_AmbiguousXMLReference, "C.M").WithArguments("C.M", "C.M(int)", "C.M(string)"), // (9,16): warning CS0419: Ambiguous reference in cref attribute: 'C.M{T}'. Assuming 'C.M<T>(int)', but could have also matched other overloads including 'C.M<T>(string)'. // /// <see cref="C.M{T}"/> Diagnostic(ErrorCode.WRN_AmbiguousXMLReference, "C.M{T}").WithArguments("C.M{T}", "C.M<T>(int)", "C.M<T>(string)")); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <see cref=""M:C.M(System.Int32)""/> <see cref=""M:C.M(System.Int32)""/> <see cref=""M:C.M``1(System.Int32)""/> <see cref=""M:C.M``1(System.Int32)""/> <see cref=""M:C.M(System.Int32)""/> <see cref=""M:C.M(System.Int32)""/> <see cref=""M:C.M``1(System.Int32)""/> <see cref=""M:C.M``1(System.Int32)""/> </member> </members> </doc>".Trim(); Assert.Equal(expected, actual); } [WorkItem(546989, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546989")] [Fact] public void GenericMethodWithoutTypeParameters2() { var source = @" /// <see cref=""M""/> /// <see cref=""M(int)""/> /// <see cref=""M{T}""/> /// <see cref=""M{T}(int)""/> /// /// <see cref=""C.M""/> /// <see cref=""C.M(int)""/> /// <see cref=""C.M{T}""/> /// <see cref=""C.M{T}(int)""/> class C { void M<T>(int x) { } void M<T>(string x) { } void M<T, U>(int x) { } void M<T, U>(string x) { } } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp, // (2,16): warning CS0419: Ambiguous reference in cref attribute: 'M'. Assuming 'C.M<T>(int)', but could have also matched other overloads including 'C.M<T>(string)'. // /// <see cref="M"/> Diagnostic(ErrorCode.WRN_AmbiguousXMLReference, "M").WithArguments("M", "C.M<T>(int)", "C.M<T>(string)"), // (3,16): warning CS0419: Ambiguous reference in cref attribute: 'M(int)'. Assuming 'C.M<T>(int)', but could have also matched other overloads including 'C.M<T, U>(int)'. // /// <see cref="M(int)"/> Diagnostic(ErrorCode.WRN_AmbiguousXMLReference, "M(int)").WithArguments("M(int)", "C.M<T>(int)", "C.M<T, U>(int)"), // (4,16): warning CS0419: Ambiguous reference in cref attribute: 'M{T}'. Assuming 'C.M<T>(int)', but could have also matched other overloads including 'C.M<T>(string)'. // /// <see cref="M{T}"/> Diagnostic(ErrorCode.WRN_AmbiguousXMLReference, "M{T}").WithArguments("M{T}", "C.M<T>(int)", "C.M<T>(string)"), // (7,16): warning CS0419: Ambiguous reference in cref attribute: 'C.M'. Assuming 'C.M<T>(int)', but could have also matched other overloads including 'C.M<T>(string)'. // /// <see cref="C.M"/> Diagnostic(ErrorCode.WRN_AmbiguousXMLReference, "C.M").WithArguments("C.M", "C.M<T>(int)", "C.M<T>(string)"), // (8,16): warning CS0419: Ambiguous reference in cref attribute: 'C.M(int)'. Assuming 'C.M<T>(int)', but could have also matched other overloads including 'C.M<T, U>(int)'. // /// <see cref="C.M(int)"/> Diagnostic(ErrorCode.WRN_AmbiguousXMLReference, "C.M(int)").WithArguments("C.M(int)", "C.M<T>(int)", "C.M<T, U>(int)"), // (9,16): warning CS0419: Ambiguous reference in cref attribute: 'C.M{T}'. Assuming 'C.M<T>(int)', but could have also matched other overloads including 'C.M<T>(string)'. // /// <see cref="C.M{T}"/> Diagnostic(ErrorCode.WRN_AmbiguousXMLReference, "C.M{T}").WithArguments("C.M{T}", "C.M<T>(int)", "C.M<T>(string)")); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <see cref=""M:C.M``1(System.Int32)""/> <see cref=""M:C.M``1(System.Int32)""/> <see cref=""M:C.M``1(System.Int32)""/> <see cref=""M:C.M``1(System.Int32)""/> <see cref=""M:C.M``1(System.Int32)""/> <see cref=""M:C.M``1(System.Int32)""/> <see cref=""M:C.M``1(System.Int32)""/> <see cref=""M:C.M``1(System.Int32)""/> </member> </members> </doc>".Trim(); Assert.Equal(expected, actual); } [WorkItem(546989, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546989")] [Fact] public void GenericMethodWithoutTypeParameters3() { var source = @" /// <see cref=""M""/> /// <see cref=""M(int)""/> /// /// <see cref=""N""/> /// <see cref=""N(int)""/> class C { void M<T, U>(int x) { } void M<T>(int x) { } void M(int x) { } void N<T>(int x) { } void N(int x) { } void N(string x) { } } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp, // (5,16): warning CS0419: Ambiguous reference in cref attribute: 'N'. Assuming 'C.N(int)', but could have also matched other overloads including 'C.N(string)'. // /// <see cref="N"/> Diagnostic(ErrorCode.WRN_AmbiguousXMLReference, "N").WithArguments("N", "C.N(int)", "C.N(string)")); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <see cref=""M:C.M(System.Int32)""/> <see cref=""M:C.M(System.Int32)""/> <see cref=""M:C.N(System.Int32)""/> <see cref=""M:C.N(System.Int32)""/> </member> </members> </doc>".Trim(); Assert.Equal(expected, actual); } [WorkItem(547163, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547163")] [Fact] public void NestedGenericTypes() { var source = @" class A<TA1, TA2> { class B<TB1, TB2> { class C<TC1, TC2> { /// Comment void M<TM1, TM2>(TA1 a1, TA2 a2, TB1 b1, TB2 b2, TC1 c1, TC2 c2, TM1 m1, TM2 m2) { } } } } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""M:A`2.B`2.C`2.M``2(`0,`1,`2,`3,`4,`5,``0,``1)""> Comment </member> </members> </doc>".Trim(); Assert.Equal(expected, actual); } [Fact] public void WhitespaceAroundCref() { var source = @" /// <see cref="" A ""/> class A { } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:A""> <see cref=""T:A""/> </member> </members> </doc>".Trim(); Assert.Equal(expected, actual); } [Fact] public void TypeParamRef_ContainingType() { var source = @" class A<T> { class B { class C<U> { class D { /// <typeparamref name=""T"" /> /// <typeparamref name=""U"" /> /// <typeparamref name=""V"" /> class E<V> { } /// <typeparamref name=""T"" /> /// <typeparamref name=""U"" /> /// <typeparamref name=""V"" /> void M<V>() { } /// <typeparamref name=""T"" /> /// <typeparamref name=""U"" /> int P { get; set; } } } } } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:A`1.B.C`1.D.E`1""> <typeparamref name=""T"" /> <typeparamref name=""U"" /> <typeparamref name=""V"" /> </member> <member name=""M:A`1.B.C`1.D.M``1""> <typeparamref name=""T"" /> <typeparamref name=""U"" /> <typeparamref name=""V"" /> </member> <member name=""P:A`1.B.C`1.D.P""> <typeparamref name=""T"" /> <typeparamref name=""U"" /> </member> </members> </doc>".Trim(); Assert.Equal(expected, actual); } [WorkItem(527260, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527260")] [Fact] public void IllegalXmlCharacter() { var source = @" /// <" + "\u037F" + @"/> class A { } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <!-- Badly formed XML comment ignored for member ""T:A"" --> </members> </doc>".Trim(); Assert.Equal(expected, actual); } [WorkItem(547311, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547311")] [ConditionalFact(typeof(ClrOnly), typeof(DesktopOnly))] [WorkItem(18610, "https://github.com/dotnet/roslyn/issues/18610")] public void UndeclaredXmlNamespace() { var source = @" /// <summary> /// Implement of the bindable radio button /// /// Usage: /// Bind your source property to the Control property Value, and set the CheckValue to your expected value. /// /// Sample: /// /// public enum Shapes /// { /// Square, Circle, Rectangle, Ellipse /// } /// /// class MyControl /// { /// public Shapes Shape { get; set; } /// } /// /// <WpfUtils:BindableRadioButton Value=""{Binding Shape}"" CheckedValue=""Square"">Square</WpfUtils:BindableRadioButton> /// <WpfUtils:BindableRadioButton Value=""{Binding Shape}"" CheckedValue=""Circle"">Circle</WpfUtils:BindableRadioButton> /// <WpfUtils:BindableRadioButton Value=""{Binding Shape}"" CheckedValue=""Ellipse"">Ellipse</WpfUtils:BindableRadioButton> /// /// </summary> class A { } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp, // (2,4): warning CS1570: XML comment has badly formed XML -- ''WpfUtils' is an undeclared prefix.' // /// <summary> Diagnostic(ErrorCode.WRN_XMLParseError, "").WithArguments("'WpfUtils' is an undeclared prefix.")); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <!-- Badly formed XML comment ignored for member ""T:A"" --> </members> </doc>".Trim(); Assert.Equal(expected, actual); } [WorkItem(551323, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/551323")] [Fact] public void MultiLine_OneLinePlusEnding() { var source = @" /** Stuff */ class C { } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> Stuff </member> </members> </doc>".Trim(); Assert.Equal(expected, actual); } [WorkItem(577385, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/577385")] [Fact] public void FormatBeforeFinalParse() { var source = @" /// <summary> /// Get the syntax node(s) where this symbol was declared in source. Some symbols (for /// example, partial classes) may be defined in more than one location. This property should /// return one or more syntax nodes only if the symbol was declared in source code and also /// was not implicitly declared (see the IsImplicitlyDeclared property). /// /// Note that for namespace symbol, the declaring syntax might be declaring a nested /// namespace. For example, the declaring syntax node for N1 in ""namespace N1.N2 {...}"" is /// the entire NamespaceDeclarationSyntax for N1.N2. For the global namespace, the declaring /// syntax will be the CompilationUnitSyntax. /// </summary> /// <returns> /// The syntax node(s) that declared the symbol. If the symbol was declared in metadata or /// was implicitly declared, returns an empty read-only array. /// </returns> /// <remarks> /// To go the opposite direction (from syntax node to symbol), see <see /// cref=""SemanticModel.GetDeclaredSymbol(MemberDeclarationSyntax, CancellationToken)""/>. /// </remarks> class C { } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp, // (19,11): warning CS1574: XML comment has cref attribute 'SemanticModel.GetDeclaredSymbol(MemberDeclarationSyntax, CancellationToken)' that could not be resolved // /// cref="SemanticModel.GetDeclaredSymbol(MemberDeclarationSyntax, CancellationToken)"/>. Diagnostic(ErrorCode.WRN_BadXMLRef, "SemanticModel.GetDeclaredSymbol(MemberDeclarationSyntax, CancellationToken)").WithArguments("GetDeclaredSymbol(MemberDeclarationSyntax, CancellationToken)")); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <summary> Get the syntax node(s) where this symbol was declared in source. Some symbols (for example, partial classes) may be defined in more than one location. This property should return one or more syntax nodes only if the symbol was declared in source code and also was not implicitly declared (see the IsImplicitlyDeclared property). Note that for namespace symbol, the declaring syntax might be declaring a nested namespace. For example, the declaring syntax node for N1 in ""namespace N1.N2 {...}"" is the entire NamespaceDeclarationSyntax for N1.N2. For the global namespace, the declaring syntax will be the CompilationUnitSyntax. </summary> <returns> The syntax node(s) that declared the symbol. If the symbol was declared in metadata or was implicitly declared, returns an empty read-only array. </returns> <remarks> To go the opposite direction (from syntax node to symbol), see <see cref=""!:SemanticModel.GetDeclaredSymbol(MemberDeclarationSyntax, CancellationToken)""/>. </remarks> </member> </members> </doc>".Trim(); Assert.Equal(expected, actual); } [WorkItem(587126, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/587126")] [Fact] public void DeclaringGenericTypeInReturnType() { var source = @" /// <see cref='System.Nullable{T}.op_Implicit'/> class C { } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <see cref='M:System.Nullable`1.op_Implicit(`0)~System.Nullable{`0}'/> </member> </members> </doc>".Trim(); Assert.Equal(expected, actual); } [WorkItem(587126, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/587126")] [Fact] public void DeclaringGenericTypeInParameterType1() { var source = @" /// <see cref=""C{T}.M""/> /// <see cref=""M""/> class C<T> { void M(T t, C<T> c, C<C<T>> cc) { } } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C`1""> <see cref=""M:C`1.M(`0,C{`0},C{C{`0}})""/> <see cref=""M:C`1.M(`0,C{`0},C{C{`0}})""/> </member> </members> </doc>".Trim(); Assert.Equal(expected, actual); } [WorkItem(587126, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/587126")] [Fact] public void DeclaringGenericTypeInParameterType2() { var source = @" class B<U> { /// <see cref=""M1""/> /// <see cref=""M2""/> /// <see cref=""M3""/> /// <see cref=""M4""/> class C<T> { void M1(T t, C<T> c, C<C<T>> cc) { } void M2(U u, C<U> c, C<C<U>> cc) { } void M3(T t, B<T> b, B<B<T>> bb) { } void M4(U u, B<U> b, B<B<U>> bb) { } } } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:B`1.C`1""> <see cref=""M:B`1.C`1.M1(`1,B{`0}.C{`1},B{`0}.C{B{`0}.C{`1}})""/> <see cref=""M:B`1.C`1.M2(`0,B{`0}.C{`0},B{`0}.C{B{`0}.C{`0}})""/> <see cref=""M:B`1.C`1.M3(`1,B{`1},B{B{`1}})""/> <see cref=""M:B`1.C`1.M4(`0,B{`0},B{B{`0}})""/> </member> </members> </doc>".Trim(); Assert.Equal(expected, actual); } [WorkItem(552379, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552379")] [Fact] public void MultipleDocComments() { var source = @" /** Multiline 1. */ /** Multiline 2. */ public class A { } /** Multiline 1. */ /// Single line 1. /** Multiline 2. */ /// Single line 2. public class B { } /** Multiline 1. */ /// Single line 1. public partial class C { } /** Multiline 2. */ /// Single line 2. public partial class C { } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:A""> Multiline 1. Multiline 2. </member> <member name=""T:B""> Multiline 1. Single line 1. Multiline 2. Single line 2. </member> <member name=""T:C""> Multiline 1. Single line 1. Multiline 2. Single line 2. </member> </members> </doc>".Trim(); Assert.Equal(expected, actual); } [WorkItem(552379, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552379")] [Fact] public void MultipleDocComments_Separated() { var source = @" /** Multiline 1. */ // Normal single-line comment. /** Multiline 2. */ public class A { } /** Multiline 1. */ /* Normal multiline comment. */ /** Multiline 2. */ public class B { } /** Multiline 1. */ public partial class C { } // Normal single-line comment. /** Multiline 2. */ public partial class C { } /** Multiline 1. */ #region /** Multiline 2. */ public class D { } /** Multiline 1. */ #endregion /** Multiline 2. */ public class E { } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp, // (2,1): warning CS1587: XML comment is not placed on a valid language element // /** Multiline 1. */ Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (7,1): warning CS1587: XML comment is not placed on a valid language element // /** Multiline 1. */ Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (19,1): warning CS1587: XML comment is not placed on a valid language element // /** Multiline 1. */ Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (24,1): warning CS1587: XML comment is not placed on a valid language element // /** Multiline 1. */ Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/")); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:A""> Multiline 2. </member> <member name=""T:B""> Multiline 2. </member> <member name=""T:C""> Multiline 1. Multiline 2. </member> <member name=""T:D""> Multiline 2. </member> <member name=""T:E""> Multiline 2. </member> </members> </doc>".Trim(); Assert.Equal(expected, actual); } [WorkItem(552379, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552379")] [Fact] public void MultipleDocComments_SplitXml() { var source = @" /** <tag> */ /** </tag> */ public class A { } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp); // NOTE: Dev11 allows this but Roslyn does not. There's no way for // us to build sensible structured trivia for the XML in this scenario. var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <!-- Badly formed XML comment ignored for member ""T:A"" --> </members> </doc>".Trim(); Assert.Equal(expected, actual); } [WorkItem(689497, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/689497")] [Fact] public void TriviaBetweenDocCommentAndDeclaration() { var source = @" /// <summary/> // Single-line comment. /* Multi-line comment. */ #if true #endif #if false #endif #region #endregion public class A { } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:A""> <summary/> </member> </members> </doc>".Trim(); Assert.Equal(expected, actual); } [WorkItem(703368, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/703368")] [Fact] public void NonGenericBeatsGeneric() { var source = @" /// <see cref='M(string)'/> public class C { void M(string s) { } void M<T>(string s) { } } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <see cref='M:C.M(System.String)'/> </member> </members> </doc>".Trim(); Assert.Equal(expected, actual); } [WorkItem(703587, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/703587")] [Fact] public void ObjectMemberViaInterface() { var source = @" using System; /// Comment public class C : IEquatable<C> { /// Implements <see cref=""IEquatable{T}.Equals""/>. /// Implements <see cref=""IEquatable{T}.GetHashCode""/>. bool IEquatable<C>.Equals(C c) { throw null; } } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp, // (7,31): warning CS1574: XML comment has cref attribute 'IEquatable{T}.GetHashCode' that could not be resolved // /// Implements <see cref="IEquatable{T}.GetHashCode"/>. Diagnostic(ErrorCode.WRN_BadXMLRef, "IEquatable{T}.GetHashCode").WithArguments("GetHashCode")); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> Comment </member> <member name=""M:C.System#IEquatable{C}#Equals(C)""> Implements <see cref=""M:System.IEquatable`1.Equals(`0)""/>. Implements <see cref=""!:IEquatable&lt;T&gt;.GetHashCode""/>. </member> </members> </doc>".Trim(); Assert.Equal(expected, actual); } [WorkItem(531505, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531505")] [ClrOnlyFact] public void Pia() { var source = @" /// <see cref='FooStruct'/> /// <see cref='FooStruct.NET'/> public class C { } "; var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <see cref='T:FooStruct'/> <see cref='F:FooStruct.NET'/> </member> </members> </doc>".Trim(); Action<ModuleSymbol> validator = module => { ((PEModuleSymbol)module).Module.PretendThereArentNoPiaLocalTypes(); // No reference added. AssertEx.None(module.GetReferencedAssemblies(), id => id.Name.Contains("GeneralPia")); // No type embedded. Assert.Equal(0, module.GlobalNamespace.GetMembers("FooStruct").Length); }; // Don't embed. { var reference = TestReferences.SymbolsTests.NoPia.GeneralPia.WithEmbedInteropTypes(false); var comp = CreateCompilationUtil(source, new[] { reference }); var actual = GetDocumentationCommentText(comp); Assert.Equal(expected, actual); CompileAndVerify(comp, symbolValidator: validator); } // Do embed. { var reference = TestReferences.SymbolsTests.NoPia.GeneralPia.WithEmbedInteropTypes(true); var comp = CreateCompilationUtil(source, new[] { reference }); var actual = GetDocumentationCommentText(comp); Assert.Equal(expected, actual); CompileAndVerify(comp, symbolValidator: validator); } } [WorkItem(757110, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/757110")] [Fact] public void NoAssemblyElementForNetModule() { var source = @" /// <summary>Text</summary> public class C { } "; var comp = CreateCompilationUtil(source, options: TestOptions.ReleaseModule); var actual = GetDocumentationCommentText(comp); var expected = @" <?xml version=""1.0""?> <doc> <members> <member name=""T:C""> <summary>Text</summary> </member> </members> </doc> ".Trim(); Assert.Equal(expected, actual); } [WorkItem(743425, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/743425")] [Fact] public void WRN_UnqualifiedNestedTypeInCref() { var source = @" class C<T> { class Inner { } void M(Inner i) { } /// <see cref=""M""/> /// <see cref=""C{T}.M""/> /// <see cref=""C{Q}.M""/> /// <see cref=""C{Q}.M(C{Q}.Inner)""/> /// <see cref=""C{Q}.M(Inner)""/> void N() { } } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp, // (12,27): warning CS8018: Within cref attributes, nested types of generic types should be qualified. // /// <see cref="C{Q}.M(Inner)"/> Diagnostic(ErrorCode.WRN_UnqualifiedNestedTypeInCref, "Inner"), // (12,20): warning CS1574: XML comment has cref attribute 'C{Q}.M(Inner)' that could not be resolved // /// <see cref="C{Q}.M(Inner)"/> Diagnostic(ErrorCode.WRN_BadXMLRef, "C{Q}.M(Inner)").WithArguments("M(Inner)")); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""M:C`1.N""> <see cref=""M:C`1.M(C{`0}.Inner)""/> <see cref=""M:C`1.M(C{`0}.Inner)""/> <see cref=""M:C`1.M(C{`0}.Inner)""/> <see cref=""M:C`1.M(C{`0}.Inner)""/> <see cref=""!:C&lt;Q&gt;.M(Inner)""/> </member> </members> </doc> ".Trim(); Assert.Equal(expected, actual); } [WorkItem(743425, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/743425")] [Fact] public void WRN_UnqualifiedNestedTypeInCref_Buried() { var source = @" class C<T> { class Inner { } void M(C<Inner[]> i) { } /// <see cref=""C{Q}.M(C{Inner[]})""/> /// <see cref=""C{Q}.M(C{C{Q}.Inner[]})""/> void N() { } } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp, // (8,27): warning CS8018: Within cref attributes, nested types of generic types should be qualified. // /// <see cref="C{Q}.M(C{Inner[]})"/> Diagnostic(ErrorCode.WRN_UnqualifiedNestedTypeInCref, "C{Inner[]}"), // (8,20): warning CS1574: XML comment has cref attribute 'C{Q}.M(C{Inner[]})' that could not be resolved // /// <see cref="C{Q}.M(C{Inner[]})"/> Diagnostic(ErrorCode.WRN_BadXMLRef, "C{Q}.M(C{Inner[]})").WithArguments("M(C{Inner[]})")); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""M:C`1.N""> <see cref=""!:C&lt;Q&gt;.M(C&lt;Inner[]&gt;)""/> <see cref=""M:C`1.M(C{C{`0}.Inner[]})""/> </member> </members> </doc> ".Trim(); Assert.Equal(expected, actual); } [WorkItem(743425, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/743425")] [Fact] public void WRN_UnqualifiedNestedTypeInCref_Generic() { var source = @" class C<T> { class Inner<U> { } void M(Inner<int> i) { } /// <see cref=""C{Q}.M(C{Q}.Inner{int})""/> /// <see cref=""C{Q}.M(Inner{int})""/> void N() { } } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp, // (9,27): warning CS8018: Within cref attributes, nested types of generic types should be qualified. // /// <see cref="C{Q}.M(Inner{int})"/> Diagnostic(ErrorCode.WRN_UnqualifiedNestedTypeInCref, "Inner{int}"), // (9,20): warning CS1574: XML comment has cref attribute 'C{Q}.M(Inner{int})' that could not be resolved // /// <see cref="C{Q}.M(Inner{int})"/> Diagnostic(ErrorCode.WRN_BadXMLRef, "C{Q}.M(Inner{int})").WithArguments("M(Inner{int})")); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""M:C`1.N""> <see cref=""M:C`1.M(C{`0}.Inner{System.Int32})""/> <see cref=""!:C&lt;Q&gt;.M(Inner&lt;int&gt;)""/> </member> </members> </doc> ".Trim(); Assert.Equal(expected, actual); } #endregion Misc #region Dev11 bugs [Fact] public void Dev11_422418() { // Warn-as-error var source = @" public class C {} // CS1587 "; var tree = Parse(source, options: TestOptions.RegularWithDocumentationComments); var compOptions = TestOptions.ReleaseDll.WithGeneralDiagnosticOption(ReportDiagnostic.Error); CreateCompilation(tree, options: compOptions).VerifyDiagnostics( // (2,14): error CS1591: Warning as Error: Missing XML comment for publicly visible type or member 'C' // public class C {} // CS1587 Diagnostic(ErrorCode.WRN_MissingXMLComment, "C").WithArguments("C").WithWarningAsError(true)); } [ConditionalFact(typeof(ClrOnly), typeof(DesktopOnly))] [WorkItem(18610, "https://github.com/dotnet/roslyn/issues/18610")] public void Dev11_303769() { // XML processing instructions var source = @" /// <summary> /// <?xml:a ?> /// </summary> class C { } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp, // (2,4): warning CS1570: XML comment has badly formed XML -- 'The ':' character, hexadecimal value 0x3A, cannot be included in a name.' // /// <summary> Diagnostic(ErrorCode.WRN_XMLParseError, "").WithArguments("The ':' character, hexadecimal value 0x3A, cannot be included in a name.")); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <!-- Badly formed XML comment ignored for member ""T:C"" --> </members> </doc> ".Trim(); Assert.Equal(expected, actual); } [Fact] public void Dev11_275507() { // Array rank specifier order var source = @" class Program { /** * <param name=""x1""></param> * <param name=""x2""></param> * <returns></returns> */ public void M2(int[] x1, long[][, ,] x2) { } public static void main() { } } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""M:Program.M2(System.Int32[],System.Int64[0:,0:,0:][])""> <param name=""x1""></param> <param name=""x2""></param> <returns></returns> </member> </members> </doc> ".Trim(); Assert.Equal(expected, actual); } [Fact] public void Dev11_274116() { // Included element order. var xml = @" <?xml version=""1.0"" encoding=""utf-8"" ?> <Docs> <Class1> <Remarks name=""Part1""> <para>EXAMPLE 1</para> </Remarks> <Remarks name=""Part2""> <para>EXAMPLE 2</para> </Remarks> </Class1> </Docs> ".Trim(); var xmlFile = Temp.CreateFile(extension: ".xml").WriteAllText(xml); var xmlFilePath = xmlFile.Path; var sourceTemplate = @" /// <summary> /// ... /// </summary> /// <remarks> /// <para>One</para> /// <include file=""{0}"" path=""Docs/Class1/Remarks[@name='Part1']/*"" /> /// <para>Two</para> /// <include file=""{0}"" path=""Docs/Class1/Remarks[@name='Part2']/*"" /> /// <para>Three</para> /// </remarks> public class C {{ }} "; var comp = CreateCompilationUtil(string.Format(sourceTemplate, xmlFilePath)); var actual = GetDocumentationCommentText(comp); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <summary> ... </summary> <remarks> <para>One</para> <para>EXAMPLE 1</para> <para>Two</para> <para>EXAMPLE 2</para> <para>Three</para> </remarks> </member> </members> </doc> ".Trim(); Assert.Equal(expected, actual); } [Fact] public void Dev11_209994() { // Array rank specifier order // NOTE: the remark on the method is copied directly from the bug - // it does not correctly indicate the doc comment ID of the method. var source = @" namespace Demo { public class Example { /// <remarks>M:Demo.Example.M(double[0:,0:,0:][])</remarks> public static void M(double[][, , ,] value) { } } } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp, // (4,18): warning CS1591: Missing XML comment for publicly visible type or member 'Demo.Example' // public class Example Diagnostic(ErrorCode.WRN_MissingXMLComment, "Example").WithArguments("Demo.Example")); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""M:Demo.Example.M(System.Double[0:,0:,0:,0:][])""> <remarks>M:Demo.Example.M(double[0:,0:,0:][])</remarks> </member> </members> </doc> ".Trim(); Assert.Equal(expected, actual); } [ConditionalFact(typeof(ClrOnly), typeof(DesktopOnly))] [WorkItem(18610, "https://github.com/dotnet/roslyn/issues/18610")] public void Dev11_142553() { // Need to cache XML files. var xmlFile = Temp.CreateFile(extension: ".xml").WriteAllText("<hello/>"); string fullPath = xmlFile.Path; string fileName = Path.GetFileName(fullPath); string dirPath = Path.GetDirectoryName(fullPath); var source = @" /// <include file='" + fullPath + @"' path='hello'/> /// <include file='" + fullPath + @"' path='hello'/> /// <include file='" + Path.Combine(dirPath, "a/..", fileName) + @"' path='hello'/> /// <include file='" + Path.Combine(dirPath, @"a\b/../..", fileName) + @"' path='hello'/> class C { } "; CreateCompilationUtil(source).VerifyDiagnostics(); Assert.InRange(DocumentationCommentIncludeCache.CacheMissCount, 1, 2); //Not none, not all. } [Fact] public void UriNotAllowed() { // Need to cache XML files. var xmlFile = Temp.CreateFile(extension: ".xml").WriteAllText("<hello/>"); var source = @" /// <include file='file://" + xmlFile.Path + @"' path='hello'/> class C { } "; CreateCompilationUtil(source).VerifyDiagnostics( // (2,5): warning CS1589: Unable to include XML fragment 'hello' of file '' -- Unable to find the specified file. Diagnostic(ErrorCode.WRN_FailedInclude, @"<include file='file://" + xmlFile.Path + @"' path='hello'/>"). WithArguments("file://" + xmlFile.Path, "hello", "File not found.").WithLocation(2, 5)); } [Fact] public void FileDirective() { // Line directive not considered. var xmlFile = Temp.CreateFile(extension: ".xml").WriteAllText("<hello/>"); string xmlFilePath = Path.GetFileName(xmlFile.Path); string dirPath = Path.GetDirectoryName(xmlFile.Path); string sourcePath = Path.Combine(dirPath, "test.cs"); var source = @" #line 200 ""C:\path\that\doesnt\exist.cs"" /// <include file='" + xmlFilePath + @"' path='hello'/> class C { } "; var comp = CreateCompilation( Parse(source, options: TestOptions.RegularWithDocumentationComments, filename: sourcePath), options: TestOptions.ReleaseDll.WithSourceReferenceResolver(SourceFileResolver.Default).WithXmlReferenceResolver(XmlFileResolver.Default), assemblyName: "Test"); var actual = GetDocumentationCommentText(comp); var expected = @"<?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <hello /> </member> </members> </doc>"; Assert.Equal(expected, actual); } [ConditionalFact(typeof(ClrOnly), typeof(DesktopOnly))] [WorkItem(18610, "https://github.com/dotnet/roslyn/issues/18610")] public void DtdDenialOfService() { var xmlFile = Temp.CreateFile(extension: ".xml").WriteAllText( @"<?xml version=""1.0""?> <!DOCTYPE root [ <!ENTITY expand ""expand""> <!ENTITY expand2 ""&expand;&expand;&expand;&expand;&expand;&expand;&expand;&expand;&expand;&expand;""> <!ENTITY expand3 ""&expand2;&expand2;&expand2;&expand2;&expand2;&expand2;&expand2;&expand2;&expand2;&expand2;""> <!ENTITY expand4 ""&expand3;&expand3;&expand3;&expand3;&expand3;&expand3;&expand3;&expand3;&expand3;&expand3;""> <!ENTITY expand5 ""&expand4;&expand4;&expand4;&expand4;&expand4;&expand4;&expand4;&expand4;&expand4;&expand4;""> <!ENTITY expand6 ""&expand5;&expand5;&expand5;&expand5;&expand5;&expand5;&expand5;&expand5;&expand5;&expand5;""> <!ENTITY expand7 ""&expand6;&expand6;&expand6;&expand6;&expand6;&expand6;&expand6;&expand6;&expand6;&expand6;""> <!ENTITY expand8 ""&expand7;&expand7;&expand7;&expand7;&expand7;&expand7;&expand7;&expand7;&expand7;&expand7;""> <!ENTITY expand9 ""&expand8;&expand8;&expand8;&expand8;&expand8;&expand8;&expand8;&expand8;&expand8;&expand8;""> ]> <root>&expand9;</root> "); var source = @" /// <include file='" + xmlFile.Path + @"' path='hello'/> class C { } "; CreateCompilationUtil(source).GetDiagnostics().VerifyWithFallbackToErrorCodeOnlyForNonEnglish( Diagnostic(ErrorCode.WRN_XMLParseIncludeError).WithArguments("For security reasons DTD is prohibited in this XML document. To enable DTD processing set the DtdProcessing property on XmlReaderSettings to Parse and pass the settings into XmlReader.Create method.").WithLocation(1, 1)); } #endregion Dev11 bugs #region Dev10 bugs [Fact] public void Dev10_898556() { // Somehow, this was causing an infinite loop (even though there's no cycle?). // Delete some irrelevant sections to save space. var xmlTemplate = @" <?xml version=""1.0"" encoding=""utf-8"" ?> <docs> <doc name=""ArrayExtensions.BinarySearchCore""> <overloads>Searches a sorted array for a value using a binary search algorithm.</overloads> <typeparam name=""T"">The type of items in the array.</typeparam> <typeparam name=""TComparator"">The type of comparator used to compare items during the search operation.</typeparam> <param name=""array"">The sorted array to search.</param> <param name=""value"">The object to search for.</param> <returns>If found, the index of the specified value in the given array. Otherwise, if not found, and the value is less than one or more items in the array, a negative number which is the bitwise complement of the index of the first item that is larger than the given value. If the value is not found and it is greater than any of the items in the array, a negative number which is the bitwise complement of (the index of the last item plus 1).</returns> </doc> <doc name=""ArrayExtensions.BinarySearch(ArrayType,T)""> <include file=""{0}"" path=""docs/doc[@name='ArrayExtensions.BinarySearchCore']/*"" /> </doc> <doc name=""ArrayExtensions.BinarySearch(ArrayType,T,TComparator)""> <include file=""{0}"" path=""docs/doc[@name='ArrayExtensions.BinarySearchCore']/*"" /> <param name=""comp"">The comparator used to evaluate the order of items.</param> </doc> <doc name=""ArrayExtensions.BinarySearch(ArrayType,int,int,T)""> <include file=""{0}"" path=""docs/doc[@name='ArrayExtensions.BinarySearchCore']/*"" /> <param name=""index"">The index of the first item in the range.</param> <param name=""count"">The total number of items in the range.</param> </doc> <doc name=""ArrayExtensions.BinarySearch(ArrayType,int,int,T,TComparator)""> <include file=""{0}"" path=""docs/doc[@name='ArrayExtensions.BinarySearch(ArrayType,int,int,T)']/*"" /> <param name=""comp"">The comparator used to evaluate the order of items.</param> </doc> </docs> ".Trim(); var xmlFile = Temp.CreateFile(extension: ".xml"); var xmlFilePath = xmlFile.Path; xmlFile.WriteAllText(string.Format(xmlTemplate, xmlFilePath)); var includeElementTemplate = @"<include file=""{0}"" path=""docs/doc[@name=&quot;ArrayExtensions.BinarySearch(ArrayType,T)&quot;]/*""/>"; var includeElement = string.Format(includeElementTemplate, xmlFilePath); var sourceTemplate = @" /// {0} class C {{ static void Main() {{ }} }} "; var comp = CreateCompilationUtil(string.Format(sourceTemplate, includeElement)); var actual = GetDocumentationCommentText(comp, // (2,5): warning CS1711: XML comment has a typeparam tag for 'T', but there is no type parameter by that name // /// <include file="52f50b557f3d.xml" path="docs/doc[@name=&quot;ArrayExtensions.BinarySearch(ArrayType,T)&quot;]/*"/> Diagnostic(ErrorCode.WRN_UnmatchedTypeParamTag, includeElement).WithArguments("T"), // (2,5): warning CS1711: XML comment has a typeparam tag for 'TComparator', but there is no type parameter by that name // /// <include file="52f50b557f3d.xml" path="docs/doc[@name=&quot;ArrayExtensions.BinarySearch(ArrayType,T)&quot;]/*"/> Diagnostic(ErrorCode.WRN_UnmatchedTypeParamTag, includeElement).WithArguments("TComparator"), // (2,5): warning CS1572: XML comment has a param tag for 'array', but there is no parameter by that name // /// <include file="52f50b557f3d.xml" path="docs/doc[@name=&quot;ArrayExtensions.BinarySearch(ArrayType,T)&quot;]/*"/> Diagnostic(ErrorCode.WRN_UnmatchedParamTag, includeElement).WithArguments("array"), // (2,5): warning CS1572: XML comment has a param tag for 'value', but there is no parameter by that name // /// <include file="52f50b557f3d.xml" path="docs/doc[@name=&quot;ArrayExtensions.BinarySearch(ArrayType,T)&quot;]/*"/> Diagnostic(ErrorCode.WRN_UnmatchedParamTag, includeElement).WithArguments("value")); var expected = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <overloads>Searches a sorted array for a value using a binary search algorithm.</overloads><typeparam name=""T"">" + @"The type of items in the array.</typeparam><typeparam name=""TComparator"">The type of comparator used to compare " + @"items during the search operation.</typeparam><param name=""array"">The sorted array to search.</param><param name=""value"">" + @"The object to search for.</param><returns>If found, the index of the specified value in the given array. Otherwise, if not " + @"found, and the value is less than one or more items in the array, a negative number which is the bitwise complement of the " + @"index of the first item that is larger than the given value. If the value is not found and it is greater than any of the items " + @"in the array, a negative number which is the bitwise complement of (the index of the last item plus 1).</returns> </member> </members> </doc> ").Trim(); Assert.Equal(expected, actual); } [Fact] public void Dev10_785160() { // Someone suggested preferring the more public member in case of ambiguity, but it was not implemented. var source = @" /// <see cref='M'/> class C { private void M(char c) { } public void M(int x) { } } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp, // (2,16): warning CS0419: Ambiguous reference in cref attribute: 'M'. Assuming 'C.M(char)', but could have also matched other overloads including 'C.M(int)'. // /// <see cref='M'/> Diagnostic(ErrorCode.WRN_AmbiguousXMLReference, "M").WithArguments("M", "C.M(char)", "C.M(int)")); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <see cref='M:C.M(System.Char)'/> </member> </members> </doc> ".Trim(); Assert.Equal(expected, actual); } [Fact] public void Dev10_747421() { // Bad XML. var source = @" class Module1 { ///<summary> /// ///</summary> ///<remarks><</remarks> public static void Main() { } } "; var comp = CreateCompilationUtil(source); comp.VerifyDiagnostics( // (7,18): warning CS1570: XML comment has badly formed XML -- 'An identifier was expected.' // ///<remarks><</remarks> Diagnostic(ErrorCode.WRN_XMLParseError, "")); var actual = GetDocumentationCommentText(comp); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <!-- Badly formed XML comment ignored for member ""M:Module1.Main"" --> </members> </doc> ".Trim(); Assert.Equal(expected, actual); } #endregion Dev10 bugs [ClrOnlyFact] [WorkItem(1115058, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1115058")] public void UnterminatedElement() { var source = @" class Module1 { ///<summary> /// Something ///<summary> static void Main() { System.Console.WriteLine(""Here""); } }"; var comp = CreateCompilationUtil(source, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "Here").VerifyDiagnostics( // (7,1): warning CS1570: XML comment has badly formed XML -- 'Expected an end tag for element 'summary'.' // static void Main() Diagnostic(ErrorCode.WRN_XMLParseError, "").WithArguments("summary").WithLocation(7, 1), // (7,1): warning CS1570: XML comment has badly formed XML -- 'Expected an end tag for element 'summary'.' // static void Main() Diagnostic(ErrorCode.WRN_XMLParseError, "").WithArguments("summary").WithLocation(7, 1) ); } /// <summary> /// "--" is not valid within an XML comment. /// </summary> [WorkItem(8807, "https://github.com/dotnet/roslyn/issues/8807")] [ConditionalFact(typeof(ClrOnly), typeof(DesktopOnly))] [WorkItem(18610, "https://github.com/dotnet/roslyn/issues/18610")] public void IncludeErrorDashDashInName() { var dir = Temp.CreateDirectory(); var path = dir.Path; var xmlFile = dir.CreateFile("---.xml").WriteAllText(@"<summary attrib="""" attrib=""""/>"); var source = $@"/// <include file='{Path.Combine(path, "---.xml")}' path='//summary'/> class C {{ }}"; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp, // warning CS1592: Badly formed XML in included comments file -- ''attrib' is a duplicate attribute name.' Diagnostic(ErrorCode.WRN_XMLParseIncludeError).WithArguments("'attrib' is a duplicate attribute name.").WithLocation(1, 1)); var expected = $@"<?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <!-- Badly formed XML file ""{Path.Combine(TestHelpers.AsXmlCommentText(path), "- - -.xml")}"" cannot be included --> </member> </members> </doc>"; Assert.Equal(expected, actual); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Threading; using System.Xml; using System.Xml.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class DocumentationCommentCompilerTests : CSharpTestBase { public static CSharpCompilation CreateCompilationUtil( CSharpTestSource source, IEnumerable<MetadataReference> references = null, CSharpCompilationOptions options = null, string assemblyName = "Test") => CreateCompilation( source, references, targetFramework: TargetFramework.Mscorlib40, options: (options ?? TestOptions.ReleaseDll).WithXmlReferenceResolver(XmlFileResolver.Default), parseOptions: TestOptions.RegularWithDocumentationComments, assemblyName: assemblyName); #region Single-line styleWRN_UnqualifiedNestedTypeInCref [Fact] public void SingleLine_OneLine() { var source = @" /// <summary>Text</summary> public class C { } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <summary>Text</summary> </member> </members> </doc> ".Trim(); Assert.Equal(expected, actual); } [Fact] public void SingleLine_MultipleLines() { var source = @" /// <summary> /// Text /// </summary> public class C { } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <summary> Text </summary> </member> </members> </doc> ".Trim(); Assert.Equal(expected, actual); } [Fact] public void SingleLine_EmptyOneLine() { var source = @" /// public class C { } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> </member> </members> </doc> ".Trim(); Assert.Equal(expected, actual); } [Fact] public void SingleLine_EmptyMultipleLines() { var source = @" /// /// /// public class C { } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> </member> </members> </doc> ".Trim(); Assert.Equal(expected, actual); } [Fact] public void SingleLine_NoLeadingSpaces() { var source = @" ///<summary> ///Text ///</summary> public class C { } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <summary> Text </summary> </member> </members> </doc> ".Trim(); Assert.Equal(expected, actual); } [Fact] public void SingleLine_SomeLeadingSpaces() { var source = @" ///<summary> /// Text /// </summary> public class C { } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <summary> Text </summary> </member> </members> </doc> ".Trim(); Assert.Equal(expected, actual); } [Fact] public void SingleLine_LeadingTab() { var source = @" /// <summary> /// Tabbed /// </summary> public class C { } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <summary> Tabbed </summary> </member> </members> </doc> ".Trim(); Assert.Equal(expected, actual); } [Fact] public void SingleLine_WhitespaceBefore() { var source = @" /// <summary> /// Text /// </summary> public class C { } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <summary> Text </summary> </member> </members> </doc> ".Trim(); Assert.Equal(expected, actual); } [Fact] public void SingleLine_BlankLines() { var source = @" /// /// <summary> /// Text /// </summary> /// public class C { } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <summary> Text </summary> </member> </members> </doc> ".Trim(); Assert.Equal(expected, actual); } #endregion Single-line style #region Multi-line style [Fact] public void MultiLine_OneLine() { var source = @" /** <summary>Text</summary> */ public class C { } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <summary>Text</summary> </member> </members> </doc> ".Trim(); Assert.Equal(expected, actual); } [Fact] public void MultiLine_EmptyOneLine() { var source = @" /** */ public class C { } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> </member> </members> </doc> ".Trim(); Assert.Equal(expected, actual); } [Fact] public void MultiLine_EmptyTwoLines() { var source = @" /** */ public class C { } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> </member> </members> </doc> ".Trim(); Assert.Equal(expected, actual); } [Fact] public void MultiLine_EmptyThreeLines() { var source = @" /** */ public class C { } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> </member> </members> </doc> ".Trim(); Assert.Equal(expected, actual); } [Fact] public void MultiLine_FirstLineSpace() { var source = @" /** <summary> * Text * </summary> */ public class C { } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <summary> Text </summary> </member> </members> </doc> ".Trim(); Assert.Equal(expected, actual); } [Fact] public void MultiLine_FirstLineNoSpace() { var source = @" /**<summary> * Text * </summary> */ public class C { } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <summary> Text </summary> </member> </members> </doc> ".Trim(); Assert.Equal(expected, actual); } [Fact] public void MultiLine_StarsPattern() { var source = @" /** * <summary> * Text * </summary> */ public class C { } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <summary> Text </summary> </member> </members> </doc> ".Trim(); Assert.Equal(expected, actual); } [Fact] public void MultiLine_StarsNoPattern() { var source = @" /** * <summary> * Text * </summary> */ public class C { } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> * <summary> * Text * </summary> </member> </members> </doc> ".Trim(); Assert.Equal(expected, actual); } [Fact] public void MultiLine_WhitespacePattern() { var source = @" /** <summary> Text </summary> */ public class C { } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <summary> Text </summary> </member> </members> </doc> ".Trim(); Assert.Equal(expected, actual); } [Fact] public void MultiLine_WhitespaceNoPattern() { var source = @" /** <summary> Text </summary> */ public class C { } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <summary> Text </summary> </member> </members> </doc> ".Trim(); Assert.Equal(expected, actual); } [Fact] public void MultiLine_LegacyTests() { var source = @" class A { /** * <summary> * /** * * * </summary> */ public void foo1(){} /** * /// * /// * /** */ public void foo2(){} /** /// <summary> /// /// </summary> */ public void foo3(){} // Test: // should not be xml comment /** // <summary> // // </summary> */ public void foo4(){} } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""M:A.foo1""> <summary> /** </summary> </member> <member name=""M:A.foo2""> /// /// /** </member> <member name=""M:A.foo3""> /// <summary> /// /// </summary> </member> <member name=""M:A.foo4""> // <summary> // // </summary> </member> </members> </doc> ".Trim(); Assert.Equal(expected, actual); } [WorkItem(547164, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547164")] [Fact] public void MultiLine_PatternShorterOnSubsequentLine() { var source = @" //repro.cs public class Point { /** * <summary>Instance variable in the * Point Class.</summary> */ private int x; /** * <summary>This is the entry point of the Point class testing * program.</summary> */ public static void Main() { } } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp, // (3,14): warning CS1591: Missing XML comment for publicly visible type or member 'Point' // public class Point Diagnostic(ErrorCode.WRN_MissingXMLComment, "Point").WithArguments("Point")); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""F:Point.x""> <summary>Instance variable in the Point Class.</summary> </member> <member name=""M:Point.Main""> <summary>This is the entry point of the Point class testing program.</summary> </member> </members> </doc> ".Trim(); Assert.Equal(expected, actual); } #endregion Multi-line style #region Partial types [Fact] public void PartialTypes_OneFile() { var source = @" /// <summary>Summary 1</summary> public partial class C { } /// <summary>Summary 2</summary> public partial class C { } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <summary>Summary 1</summary> <summary>Summary 2</summary> </member> </members> </doc> ".Trim(); Assert.Equal(expected, actual); } [Fact] public void PartialTypes_MultipleFiles() { var source1 = @" /// <summary>Summary 1</summary> public partial class C { } "; var source2 = @" /// <summary>Summary 2</summary> public partial class C { } "; var tree1 = SyntaxFactory.ParseSyntaxTree(source1, options: TestOptions.RegularWithDocumentationComments); var tree2 = SyntaxFactory.ParseSyntaxTree(source2, options: TestOptions.RegularWithDocumentationComments); // Files passed in order. var compA = CreateCompilation(new[] { tree1, tree2 }, assemblyName: "Test"); var actualA = GetDocumentationCommentText(compA); var expectedA = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <summary>Summary 1</summary> <summary>Summary 2</summary> </member> </members> </doc> ".Trim(); Assert.Equal(expectedA, actualA); // Files passed in reverse order. var compB = CreateCompilation(new[] { tree2, tree1 }, assemblyName: "Test"); var actualB = GetDocumentationCommentText(compB); var expectedB = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <summary>Summary 2</summary> <summary>Summary 1</summary> </member> </members> </doc> ".Trim(); Assert.Equal(expectedB, actualB); } [Fact] public void PartialTypes_MultipleStyles() { var source = @" /// <summary>Summary 1</summary> public partial class C { } /** <summary>Summary 2</summary> */ public partial class C { } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <summary>Summary 1</summary> <summary>Summary 2</summary> </member> </members> </doc> ".Trim(); Assert.Equal(expected, actual); } #endregion Partial types #region Partial methods [Fact] public void PartialMethods_OneFile() { var source = @" partial class C { /// <summary>Summary 1</summary> partial void M(); } partial class C { /// <summary>Summary 2</summary> partial void M() { } } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""M:C.M""> <summary>Summary 2</summary> </member> </members> </doc> ".Trim(); Assert.Equal(expected, actual); } [Fact] public void PartialMethods_MultipleFiles() { var source1 = @" partial class C { /** <summary>Summary 1</summary>*/ partial void M() { } } "; var source2 = @" partial class C { /** <summary>Summary 2</summary>*/ partial void M(); } "; var tree1 = SyntaxFactory.ParseSyntaxTree(source1, options: TestOptions.RegularWithDocumentationComments); var tree2 = SyntaxFactory.ParseSyntaxTree(source2, options: TestOptions.RegularWithDocumentationComments); // Files passed in order. var compA = CreateCompilation(new[] { tree1, tree2 }, assemblyName: "Test"); var actualA = GetDocumentationCommentText(compA); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""M:C.M""> <summary>Summary 1</summary> </member> </members> </doc> ".Trim(); Assert.Equal(expected, actualA); // Files passed in reverse order. var compB = CreateCompilation(new[] { tree2, tree1 }, assemblyName: "Test"); var actualB = GetDocumentationCommentText(compB); Assert.Equal(expected, actualB); } [Fact] public void PartialMethod_NoImplementation() { var source = @" partial class C { /** <summary>Summary 2</summary>*/ partial void M(); } "; var tree = SyntaxFactory.ParseSyntaxTree(source, options: TestOptions.RegularWithDocumentationComments); var comp = CreateCompilation(tree, assemblyName: "Test"); var actual = GetDocumentationCommentText(comp); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> </members> </doc> ".Trim(); Assert.Equal(expected, actual); } [Fact] public void ExtendedPartialMethods_MultipleFiles() { var source1 = @" /// <summary>Summary 0</summary> public partial class C { /** <summary>Summary 1</summary>*/ public partial int M() => 42; } "; var source2 = @" public partial class C { /** <summary>Summary 2</summary>*/ public partial int M(); } "; var tree1 = SyntaxFactory.ParseSyntaxTree(source1, options: TestOptions.RegularWithDocumentationComments); var tree2 = SyntaxFactory.ParseSyntaxTree(source2, options: TestOptions.RegularWithDocumentationComments); // Files passed in order. var compA = CreateCompilation(new[] { tree1, tree2 }, assemblyName: "Test"); var actualA = GetDocumentationCommentText(compA); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <summary>Summary 0</summary> </member> <member name=""M:C.M""> <summary>Summary 1</summary> </member> </members> </doc> ".Trim(); AssertEx.Equal(expected, actualA); // Files passed in reverse order. var compB = CreateCompilation(new[] { tree2, tree1 }, assemblyName: "Test"); var actualB = GetDocumentationCommentText(compB); Assert.Equal(expected, actualB); } [Fact] public void ExtendedPartialMethods_MultipleFiles_DefinitionComment() { var source1 = @" /// <summary>Summary 0</summary> public partial class C { public partial int M() => 42; } "; var source2 = @" public partial class C { /** <summary>Summary 2</summary>*/ public partial int M(); } "; var tree1 = SyntaxFactory.ParseSyntaxTree(source1, options: TestOptions.RegularWithDocumentationComments); var tree2 = SyntaxFactory.ParseSyntaxTree(source2, options: TestOptions.RegularWithDocumentationComments); // Files passed in order. var compA = CreateCompilation(new[] { tree1, tree2 }, assemblyName: "Test"); compA.VerifyDiagnostics(); var actualA = GetDocumentationCommentText(compA); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <summary>Summary 0</summary> </member> <member name=""M:C.M""> <summary>Summary 2</summary> </member> </members> </doc> ".Trim(); AssertEx.Equal(expected, actualA); // Files passed in reverse order. var compB = CreateCompilation(new[] { tree2, tree1 }, assemblyName: "Test"); compB.VerifyDiagnostics(); var actualB = GetDocumentationCommentText(compB); Assert.Equal(expected, actualB); } [Fact] public void ExtendedPartialMethods_MultipleFiles_ImplementationComment() { var source1 = @" /// <summary>Summary 0</summary> public partial class C { /** <summary>Summary 1</summary>*/ public partial int M() => 42; } "; var source2 = @" public partial class C { public partial int M(); } "; var tree1 = SyntaxFactory.ParseSyntaxTree(source1, options: TestOptions.RegularWithDocumentationComments); var tree2 = SyntaxFactory.ParseSyntaxTree(source2, options: TestOptions.RegularWithDocumentationComments); // Files passed in order. var compA = CreateCompilation(new[] { tree1, tree2 }, assemblyName: "Test"); compA.VerifyDiagnostics(); var actualA = GetDocumentationCommentText(compA); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <summary>Summary 0</summary> </member> <member name=""M:C.M""> <summary>Summary 1</summary> </member> </members> </doc> ".Trim(); AssertEx.Equal(expected, actualA); // Files passed in reverse order. var compB = CreateCompilation(new[] { tree2, tree1 }, assemblyName: "Test"); compB.VerifyDiagnostics(); var actualB = GetDocumentationCommentText(compB); Assert.Equal(expected, actualB); } [Fact] public void ExtendedPartialMethods_MultipleFiles_NoComment() { var source1 = @" /// <summary>Summary 0</summary> public partial class C { public partial int M() => 42; } "; var source2 = @" public partial class C { public partial int M(); } "; var tree1 = SyntaxFactory.ParseSyntaxTree(source1, options: TestOptions.RegularWithDocumentationComments); var tree2 = SyntaxFactory.ParseSyntaxTree(source2, options: TestOptions.RegularWithDocumentationComments); var expectedDiagnostics = new[] { // (4,24): warning CS1591: Missing XML comment for publicly visible type or member 'C.M()' // public partial int M(); Diagnostic(ErrorCode.WRN_MissingXMLComment, "M").WithArguments("C.M()").WithLocation(4, 24) }; // Files passed in order. var compA = CreateCompilation(new[] { tree1, tree2 }, assemblyName: "Test"); compA.VerifyDiagnostics(expectedDiagnostics); var actualA = GetDocumentationCommentText(compA, expectedDiagnostics); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <summary>Summary 0</summary> </member> </members> </doc> ".Trim(); AssertEx.Equal(expected, actualA); // Files passed in reverse order. var compB = CreateCompilation(new[] { tree2, tree1 }, assemblyName: "Test"); compB.VerifyDiagnostics(expectedDiagnostics); var actualB = GetDocumentationCommentText(compB, expectedDiagnostics); Assert.Equal(expected, actualB); } [Fact] public void ExtendedPartialMethods_MultipleFiles_Overlap() { var source1 = @" partial class C { /** <remarks>Remarks 1</remarks> */ public partial int M() => 42; } "; var source2 = @" partial class C { /** <summary>Summary 2</summary>*/ public partial int M(); } "; var tree1 = SyntaxFactory.ParseSyntaxTree(source1, options: TestOptions.RegularWithDocumentationComments); var tree2 = SyntaxFactory.ParseSyntaxTree(source2, options: TestOptions.RegularWithDocumentationComments); // Files passed in order. var compA = CreateCompilation(new[] { tree1, tree2 }, assemblyName: "Test"); compA.VerifyDiagnostics(); var actualA = GetDocumentationCommentText(compA); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""M:C.M""> <remarks>Remarks 1</remarks> </member> </members> </doc> ".Trim(); AssertEx.Equal(expected, actualA); // Files passed in reverse order. var compB = CreateCompilation(new[] { tree2, tree1 }, assemblyName: "Test"); compB.VerifyDiagnostics(); var actualB = GetDocumentationCommentText(compB); Assert.Equal(expected, actualB); } [Fact] public void ExtendedPartialMethods_MultipleFiles_ImplComment_Invalid() { var source1 = @" partial class C { /// <summary></a></summary> public partial int M() => 42; } "; var source2 = @" partial class C { /** <summary>Summary 2</summary>*/ public partial int M(); } "; var tree1 = SyntaxFactory.ParseSyntaxTree(source1, options: TestOptions.RegularWithDocumentationComments); var tree2 = SyntaxFactory.ParseSyntaxTree(source2, options: TestOptions.RegularWithDocumentationComments); var expectedDiagnostics = new[] { // (4,20): warning CS1570: XML comment has badly formed XML -- 'End tag 'a' does not match the start tag 'summary'.' // /// <summary></a></summary> Diagnostic(ErrorCode.WRN_XMLParseError, "a").WithArguments("a", "summary").WithLocation(4, 20), // (4,22): warning CS1570: XML comment has badly formed XML -- 'End tag was not expected at this location.' // /// <summary></a></summary> Diagnostic(ErrorCode.WRN_XMLParseError, "<").WithLocation(4, 22) }; // Files passed in order. var compA = CreateCompilation(new[] { tree1, tree2 }, assemblyName: "Test"); compA.VerifyDiagnostics(expectedDiagnostics); var actualA = GetDocumentationCommentText(compA); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <!-- Badly formed XML comment ignored for member ""M:C.M"" --> </members> </doc> ".Trim(); AssertEx.Equal(expected, actualA); // Files passed in reverse order. var compB = CreateCompilation(new[] { tree2, tree1 }, assemblyName: "Test"); compB.VerifyDiagnostics(expectedDiagnostics); var actualB = GetDocumentationCommentText(compB); Assert.Equal(expected, actualB); } [Fact] public void PartialMethod_Paramref_01() { var source1 = @" partial class C { /** <summary>Accepts <paramref name=""p1""/>.</summary> */ public partial int M(int p1) => 42; } "; var source2 = @" partial class C { public partial int M(int p2); } "; var tree1 = SyntaxFactory.ParseSyntaxTree(source1, options: TestOptions.RegularWithDocumentationComments); var tree2 = SyntaxFactory.ParseSyntaxTree(source2, options: TestOptions.RegularWithDocumentationComments); // Files passed in order. verify(new[] { tree1, tree2 }); // Files passed in reverse order. verify(new[] { tree2, tree1 }); void verify(CSharpTestSource source) { var compilation = CreateCompilation(source, assemblyName: "Test"); var verifier = CompileAndVerify(compilation, symbolValidator: module => { var method = module.GlobalNamespace.GetMember<MethodSymbol>("C.M"); Assert.Equal("p2", method.Parameters.Single().Name); }); verifier.VerifyDiagnostics( // (5,24): warning CS8826: Partial method declarations 'int C.M(int p2)' and 'int C.M(int p1)' have signature differences. // public partial int M(int p1) => 42; Diagnostic(ErrorCode.WRN_PartialMethodTypeDifference, "M").WithArguments("int C.M(int p2)", "int C.M(int p1)").WithLocation(5, 24)); var actual = GetDocumentationCommentText(compilation); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""M:C.M(System.Int32)""> <summary>Accepts <paramref name=""p1""/>.</summary> </member> </members> </doc> ".Trim(); AssertEx.Equal(expected, actual); } } [Fact] public void PartialMethod_Paramref_02() { var source1 = @" partial class C { /** <summary>Accepts <paramref name=""p2""/>.</summary> */ public partial int M(int p1) => 42; } "; var source2 = @" partial class C { public partial int M(int p2); } "; var tree1 = SyntaxFactory.ParseSyntaxTree(source1, options: TestOptions.RegularWithDocumentationComments); var tree2 = SyntaxFactory.ParseSyntaxTree(source2, options: TestOptions.RegularWithDocumentationComments); // Files passed in order. verify(new[] { tree1, tree2 }); // Files passed in reverse order. verify(new[] { tree2, tree1 }); void verify(CSharpTestSource source) { var compilation = CreateCompilation(source, assemblyName: "Test"); var verifier = CompileAndVerify(compilation, symbolValidator: module => { var method = module.GlobalNamespace.GetMember<MethodSymbol>("C.M"); Assert.Equal("p2", method.Parameters.Single().Name); }); verifier.VerifyDiagnostics( // (4,42): warning CS1734: XML comment on 'C.M(int)' has a paramref tag for 'p2', but there is no parameter by that name // /** <summary>Accepts <paramref name="p2"/>.</summary> */ Diagnostic(ErrorCode.WRN_UnmatchedParamRefTag, "p2").WithArguments("p2", "C.M(int)").WithLocation(4, 42), // (5,24): warning CS8826: Partial method declarations 'int C.M(int p2)' and 'int C.M(int p1)' have signature differences. // public partial int M(int p1) => 42; Diagnostic(ErrorCode.WRN_PartialMethodTypeDifference, "M").WithArguments("int C.M(int p2)", "int C.M(int p1)").WithLocation(5, 24)); var actual = GetDocumentationCommentText(compilation, // (4,42): warning CS1734: XML comment on 'C.M(int)' has a paramref tag for 'p2', but there is no parameter by that name // /** <summary>Accepts <paramref name="p2"/>.</summary> */ Diagnostic(ErrorCode.WRN_UnmatchedParamRefTag, "p2").WithArguments("p2", "C.M(int)").WithLocation(4, 42)); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""M:C.M(System.Int32)""> <summary>Accepts <paramref name=""p2""/>.</summary> </member> </members> </doc> ".Trim(); AssertEx.Equal(expected, actual); } } [Fact] public void PartialMethod_Paramref_03() { var source1 = @" partial class C { public partial int M(int p1) => 42; } "; var source2 = @" partial class C { /** <summary>Accepts <paramref name=""p1""/>.</summary> */ public partial int M(int p2); } "; var tree1 = SyntaxFactory.ParseSyntaxTree(source1, options: TestOptions.RegularWithDocumentationComments); var tree2 = SyntaxFactory.ParseSyntaxTree(source2, options: TestOptions.RegularWithDocumentationComments); // Files passed in order. verify(new[] { tree1, tree2 }); // Files passed in reverse order. verify(new[] { tree2, tree1 }); void verify(CSharpTestSource source) { var compilation = CreateCompilation(source, assemblyName: "Test"); var verifier = CompileAndVerify(compilation, symbolValidator: module => { var method = module.GlobalNamespace.GetMember<MethodSymbol>("C.M"); Assert.Equal("p2", method.Parameters.Single().Name); }); verifier.VerifyDiagnostics( // (4,24): warning CS8826: Partial method declarations 'int C.M(int p2)' and 'int C.M(int p1)' have signature differences. // public partial int M(int p1) => 42; Diagnostic(ErrorCode.WRN_PartialMethodTypeDifference, "M").WithArguments("int C.M(int p2)", "int C.M(int p1)").WithLocation(4, 24), // (4,42): warning CS1734: XML comment on 'C.M(int)' has a paramref tag for 'p1', but there is no parameter by that name // /** <summary>Accepts <paramref name="p1"/>.</summary> */ Diagnostic(ErrorCode.WRN_UnmatchedParamRefTag, "p1").WithArguments("p1", "C.M(int)").WithLocation(4, 42)); var actual = GetDocumentationCommentText(compilation, // (4,42): warning CS1734: XML comment on 'C.M(int)' has a paramref tag for 'p1', but there is no parameter by that name // /** <summary>Accepts <paramref name="p1"/>.</summary> */ Diagnostic(ErrorCode.WRN_UnmatchedParamRefTag, "p1").WithArguments("p1", "C.M(int)").WithLocation(4, 42)); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""M:C.M(System.Int32)""> <summary>Accepts <paramref name=""p1""/>.</summary> </member> </members> </doc> ".Trim(); AssertEx.Equal(expected, actual); } } [Fact] public void PartialMethod_Paramref_04() { var source1 = @" partial class C { public partial int M(int p1) => 42; } "; var source2 = @" partial class C { /** <summary>Accepts <paramref name=""p2""/>.</summary> */ public partial int M(int p2); } "; var tree1 = SyntaxFactory.ParseSyntaxTree(source1, options: TestOptions.RegularWithDocumentationComments); var tree2 = SyntaxFactory.ParseSyntaxTree(source2, options: TestOptions.RegularWithDocumentationComments); // Files passed in order. verify(new[] { tree1, tree2 }); // Files passed in reverse order. verify(new[] { tree2, tree1 }); void verify(CSharpTestSource source) { var compilation = CreateCompilation(source, assemblyName: "Test"); var verifier = CompileAndVerify(compilation, symbolValidator: module => { var method = module.GlobalNamespace.GetMember<MethodSymbol>("C.M"); Assert.Equal("p2", method.Parameters.Single().Name); }); verifier.VerifyDiagnostics( // (4,24): warning CS8826: Partial method declarations 'int C.M(int p2)' and 'int C.M(int p1)' have signature differences. // public partial int M(int p1) => 42; Diagnostic(ErrorCode.WRN_PartialMethodTypeDifference, "M").WithArguments("int C.M(int p2)", "int C.M(int p1)").WithLocation(4, 24)); var actual = GetDocumentationCommentText(compilation); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""M:C.M(System.Int32)""> <summary>Accepts <paramref name=""p2""/>.</summary> </member> </members> </doc> ".Trim(); AssertEx.Equal(expected, actual); } } #endregion Partial methods #region Crefs [Fact] public void ValidCrefs() { var source = @" /// <summary> /// A <see cref=""C""/> B /// <see cref=""object""/> C. /// </summary> public class C { } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <summary> A <see cref=""T:C""/> B <see cref=""T:System.Object""/> C. </summary> </member> </members> </doc> ".Trim(); Assert.Equal(expected, actual); } [Fact] public void InvalidCrefs() { var source = @" /// <summary> /// A <see cref=""Q""/>. /// </summary> public class C { } /// <summary> /// A <see cref=""R{S, T}""/>. /// </summary> public class D { } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp, // (3,18): warning CS1574: XML comment has cref attribute 'Q' that could not be resolved // /// A <see cref="Q"/>. Diagnostic(ErrorCode.WRN_BadXMLRef, "Q").WithArguments("Q"), // (8,18): warning CS1574: XML comment has cref attribute 'R{S, T}' that could not be resolved // /// A <see cref="R{S, T}"/>. Diagnostic(ErrorCode.WRN_BadXMLRef, "R{S, T}").WithArguments("R{S, T}")); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <summary> A <see cref=""!:Q""/>. </summary> </member> <member name=""T:D""> <summary> A <see cref=""!:R&lt;S, T&gt;""/>. </summary> </member> </members> </doc> ".Trim(); Assert.Equal(expected, actual); } #endregion Crefs #region Output name [Fact] public void AssemblyNameFromCompilationName() { var source = @" /// A <see cref=""Main""/>. public class C { static void Main() {} } "; var comp = CreateCompilationUtil(source, assemblyName: "CompilationName"); var actual = GetDocumentationCommentText(comp); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>CompilationName</name> </assembly> <members> <member name=""T:C""> A <see cref=""M:C.Main""/>. </member> </members> </doc> ".Trim(); Assert.Equal(expected, actual); } [Fact] public void AssemblyNameFromOutputName() { var source = @" /// A <see cref=""Main""/>. public class C { static void Main() {} } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp, "OutputName"); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>OutputName</name> </assembly> <members> <member name=""T:C""> A <see cref=""M:C.Main""/>. </member> </members> </doc> ".Trim(); Assert.Equal(expected, actual); } #endregion Output name #region WRN_UnprocessedXMLComment [Fact] public void UnprocessedXMLComment_Types() { var source = @" class C<T> : object where T : I { } struct S<T, U> where T : U { } interface I { } delegate void D<T, U>(T t, U u) where T : U; enum E : byte { } "; var revisedSource = new DocumentationCommentAdder().Visit(Parse(source).GetCompilationUnitRoot()).ToFullString(); // Manually verified that positions match dev11. CreateCompilationUtil(revisedSource).VerifyDiagnostics( // (2,15): warning CS1587: XML comment is not placed on a valid language element // /** 0 */class /** 1 */C/** 2 */</** 3 */T/** 4 */> /** 5 */: /** 6 */object /** 7 */where /** 8 */T /** 9 */: /** 10 */I Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (2,24): warning CS1587: XML comment is not placed on a valid language element // /** 0 */class /** 1 */C/** 2 */</** 3 */T/** 4 */> /** 5 */: /** 6 */object /** 7 */where /** 8 */T /** 9 */: /** 10 */I Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (2,33): warning CS1587: XML comment is not placed on a valid language element // /** 0 */class /** 1 */C/** 2 */</** 3 */T/** 4 */> /** 5 */: /** 6 */object /** 7 */where /** 8 */T /** 9 */: /** 10 */I Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (2,42): warning CS1587: XML comment is not placed on a valid language element // /** 0 */class /** 1 */C/** 2 */</** 3 */T/** 4 */> /** 5 */: /** 6 */object /** 7 */where /** 8 */T /** 9 */: /** 10 */I Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (2,52): warning CS1587: XML comment is not placed on a valid language element // /** 0 */class /** 1 */C/** 2 */</** 3 */T/** 4 */> /** 5 */: /** 6 */object /** 7 */where /** 8 */T /** 9 */: /** 10 */I Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (2,62): warning CS1587: XML comment is not placed on a valid language element // /** 0 */class /** 1 */C/** 2 */</** 3 */T/** 4 */> /** 5 */: /** 6 */object /** 7 */where /** 8 */T /** 9 */: /** 10 */I Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (2,77): warning CS1587: XML comment is not placed on a valid language element // /** 0 */class /** 1 */C/** 2 */</** 3 */T/** 4 */> /** 5 */: /** 6 */object /** 7 */where /** 8 */T /** 9 */: /** 10 */I Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (2,91): warning CS1587: XML comment is not placed on a valid language element // /** 0 */class /** 1 */C/** 2 */</** 3 */T/** 4 */> /** 5 */: /** 6 */object /** 7 */where /** 8 */T /** 9 */: /** 10 */I Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (2,101): warning CS1587: XML comment is not placed on a valid language element // /** 0 */class /** 1 */C/** 2 */</** 3 */T/** 4 */> /** 5 */: /** 6 */object /** 7 */where /** 8 */T /** 9 */: /** 10 */I Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (2,111): warning CS1587: XML comment is not placed on a valid language element // /** 0 */class /** 1 */C/** 2 */</** 3 */T/** 4 */> /** 5 */: /** 6 */object /** 7 */where /** 8 */T /** 9 */: /** 10 */I Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (3,1): warning CS1587: XML comment is not placed on a valid language element // /** 11 */{ Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (5,1): warning CS1587: XML comment is not placed on a valid language element // /** 12 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (7,17): warning CS1587: XML comment is not placed on a valid language element // /** 13 */struct /** 14 */S/** 15 */</** 16 */T/** 17 */, /** 18 */U/** 19 */> /** 20 */where /** 21 */T /** 22 */: /** 23 */U Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (7,27): warning CS1587: XML comment is not placed on a valid language element // /** 13 */struct /** 14 */S/** 15 */</** 16 */T/** 17 */, /** 18 */U/** 19 */> /** 20 */where /** 21 */T /** 22 */: /** 23 */U Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (7,37): warning CS1587: XML comment is not placed on a valid language element // /** 13 */struct /** 14 */S/** 15 */</** 16 */T/** 17 */, /** 18 */U/** 19 */> /** 20 */where /** 21 */T /** 22 */: /** 23 */U Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (7,47): warning CS1587: XML comment is not placed on a valid language element // /** 13 */struct /** 14 */S/** 15 */</** 16 */T/** 17 */, /** 18 */U/** 19 */> /** 20 */where /** 21 */T /** 22 */: /** 23 */U Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (7,58): warning CS1587: XML comment is not placed on a valid language element // /** 13 */struct /** 14 */S/** 15 */</** 16 */T/** 17 */, /** 18 */U/** 19 */> /** 20 */where /** 21 */T /** 22 */: /** 23 */U Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (7,68): warning CS1587: XML comment is not placed on a valid language element // /** 13 */struct /** 14 */S/** 15 */</** 16 */T/** 17 */, /** 18 */U/** 19 */> /** 20 */where /** 21 */T /** 22 */: /** 23 */U Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (7,79): warning CS1587: XML comment is not placed on a valid language element // /** 13 */struct /** 14 */S/** 15 */</** 16 */T/** 17 */, /** 18 */U/** 19 */> /** 20 */where /** 21 */T /** 22 */: /** 23 */U Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (7,94): warning CS1587: XML comment is not placed on a valid language element // /** 13 */struct /** 14 */S/** 15 */</** 16 */T/** 17 */, /** 18 */U/** 19 */> /** 20 */where /** 21 */T /** 22 */: /** 23 */U Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (7,105): warning CS1587: XML comment is not placed on a valid language element // /** 13 */struct /** 14 */S/** 15 */</** 16 */T/** 17 */, /** 18 */U/** 19 */> /** 20 */where /** 21 */T /** 22 */: /** 23 */U Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (7,116): warning CS1587: XML comment is not placed on a valid language element // /** 13 */struct /** 14 */S/** 15 */</** 16 */T/** 17 */, /** 18 */U/** 19 */> /** 20 */where /** 21 */T /** 22 */: /** 23 */U Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (8,1): warning CS1587: XML comment is not placed on a valid language element // /** 24 */{ Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (10,1): warning CS1587: XML comment is not placed on a valid language element // /** 25 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (12,20): warning CS1587: XML comment is not placed on a valid language element // /** 26 */interface /** 27 */I Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (13,1): warning CS1587: XML comment is not placed on a valid language element // /** 28 */{ Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (15,1): warning CS1587: XML comment is not placed on a valid language element // /** 29 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (17,19): warning CS1587: XML comment is not placed on a valid language element // /** 30 */delegate /** 31 */void /** 32 */D/** 33 */</** 34 */T/** 35 */, /** 36 */U/** 37 */>/** 38 */(/** 39 */T /** 40 */t/** 41 */, /** 42 */U /** 43 */u/** 44 */) /** 45 */where /** 46 */T /** 47 */: /** 48 */U/** 49 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (17,33): warning CS1587: XML comment is not placed on a valid language element // /** 30 */delegate /** 31 */void /** 32 */D/** 33 */</** 34 */T/** 35 */, /** 36 */U/** 37 */>/** 38 */(/** 39 */T /** 40 */t/** 41 */, /** 42 */U /** 43 */u/** 44 */) /** 45 */where /** 46 */T /** 47 */: /** 48 */U/** 49 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (17,43): warning CS1587: XML comment is not placed on a valid language element // /** 30 */delegate /** 31 */void /** 32 */D/** 33 */</** 34 */T/** 35 */, /** 36 */U/** 37 */>/** 38 */(/** 39 */T /** 40 */t/** 41 */, /** 42 */U /** 43 */u/** 44 */) /** 45 */where /** 46 */T /** 47 */: /** 48 */U/** 49 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (17,53): warning CS1587: XML comment is not placed on a valid language element // /** 30 */delegate /** 31 */void /** 32 */D/** 33 */</** 34 */T/** 35 */, /** 36 */U/** 37 */>/** 38 */(/** 39 */T /** 40 */t/** 41 */, /** 42 */U /** 43 */u/** 44 */) /** 45 */where /** 46 */T /** 47 */: /** 48 */U/** 49 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (17,63): warning CS1587: XML comment is not placed on a valid language element // /** 30 */delegate /** 31 */void /** 32 */D/** 33 */</** 34 */T/** 35 */, /** 36 */U/** 37 */>/** 38 */(/** 39 */T /** 40 */t/** 41 */, /** 42 */U /** 43 */u/** 44 */) /** 45 */where /** 46 */T /** 47 */: /** 48 */U/** 49 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (17,74): warning CS1587: XML comment is not placed on a valid language element // /** 30 */delegate /** 31 */void /** 32 */D/** 33 */</** 34 */T/** 35 */, /** 36 */U/** 37 */>/** 38 */(/** 39 */T /** 40 */t/** 41 */, /** 42 */U /** 43 */u/** 44 */) /** 45 */where /** 46 */T /** 47 */: /** 48 */U/** 49 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (17,84): warning CS1587: XML comment is not placed on a valid language element // /** 30 */delegate /** 31 */void /** 32 */D/** 33 */</** 34 */T/** 35 */, /** 36 */U/** 37 */>/** 38 */(/** 39 */T /** 40 */t/** 41 */, /** 42 */U /** 43 */u/** 44 */) /** 45 */where /** 46 */T /** 47 */: /** 48 */U/** 49 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (17,94): warning CS1587: XML comment is not placed on a valid language element // /** 30 */delegate /** 31 */void /** 32 */D/** 33 */</** 34 */T/** 35 */, /** 36 */U/** 37 */>/** 38 */(/** 39 */T /** 40 */t/** 41 */, /** 42 */U /** 43 */u/** 44 */) /** 45 */where /** 46 */T /** 47 */: /** 48 */U/** 49 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (17,104): warning CS1587: XML comment is not placed on a valid language element // /** 30 */delegate /** 31 */void /** 32 */D/** 33 */</** 34 */T/** 35 */, /** 36 */U/** 37 */>/** 38 */(/** 39 */T /** 40 */t/** 41 */, /** 42 */U /** 43 */u/** 44 */) /** 45 */where /** 46 */T /** 47 */: /** 48 */U/** 49 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (17,115): warning CS1587: XML comment is not placed on a valid language element // /** 30 */delegate /** 31 */void /** 32 */D/** 33 */</** 34 */T/** 35 */, /** 36 */U/** 37 */>/** 38 */(/** 39 */T /** 40 */t/** 41 */, /** 42 */U /** 43 */u/** 44 */) /** 45 */where /** 46 */T /** 47 */: /** 48 */U/** 49 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (17,125): warning CS1587: XML comment is not placed on a valid language element // /** 30 */delegate /** 31 */void /** 32 */D/** 33 */</** 34 */T/** 35 */, /** 36 */U/** 37 */>/** 38 */(/** 39 */T /** 40 */t/** 41 */, /** 42 */U /** 43 */u/** 44 */) /** 45 */where /** 46 */T /** 47 */: /** 48 */U/** 49 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (17,136): warning CS1587: XML comment is not placed on a valid language element // /** 30 */delegate /** 31 */void /** 32 */D/** 33 */</** 34 */T/** 35 */, /** 36 */U/** 37 */>/** 38 */(/** 39 */T /** 40 */t/** 41 */, /** 42 */U /** 43 */u/** 44 */) /** 45 */where /** 46 */T /** 47 */: /** 48 */U/** 49 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (17,147): warning CS1587: XML comment is not placed on a valid language element // /** 30 */delegate /** 31 */void /** 32 */D/** 33 */</** 34 */T/** 35 */, /** 36 */U/** 37 */>/** 38 */(/** 39 */T /** 40 */t/** 41 */, /** 42 */U /** 43 */u/** 44 */) /** 45 */where /** 46 */T /** 47 */: /** 48 */U/** 49 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (17,157): warning CS1587: XML comment is not placed on a valid language element // /** 30 */delegate /** 31 */void /** 32 */D/** 33 */</** 34 */T/** 35 */, /** 36 */U/** 37 */>/** 38 */(/** 39 */T /** 40 */t/** 41 */, /** 42 */U /** 43 */u/** 44 */) /** 45 */where /** 46 */T /** 47 */: /** 48 */U/** 49 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (17,168): warning CS1587: XML comment is not placed on a valid language element // /** 30 */delegate /** 31 */void /** 32 */D/** 33 */</** 34 */T/** 35 */, /** 36 */U/** 37 */>/** 38 */(/** 39 */T /** 40 */t/** 41 */, /** 42 */U /** 43 */u/** 44 */) /** 45 */where /** 46 */T /** 47 */: /** 48 */U/** 49 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (17,183): warning CS1587: XML comment is not placed on a valid language element // /** 30 */delegate /** 31 */void /** 32 */D/** 33 */</** 34 */T/** 35 */, /** 36 */U/** 37 */>/** 38 */(/** 39 */T /** 40 */t/** 41 */, /** 42 */U /** 43 */u/** 44 */) /** 45 */where /** 46 */T /** 47 */: /** 48 */U/** 49 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (17,194): warning CS1587: XML comment is not placed on a valid language element // /** 30 */delegate /** 31 */void /** 32 */D/** 33 */</** 34 */T/** 35 */, /** 36 */U/** 37 */>/** 38 */(/** 39 */T /** 40 */t/** 41 */, /** 42 */U /** 43 */u/** 44 */) /** 45 */where /** 46 */T /** 47 */: /** 48 */U/** 49 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (17,205): warning CS1587: XML comment is not placed on a valid language element // /** 30 */delegate /** 31 */void /** 32 */D/** 33 */</** 34 */T/** 35 */, /** 36 */U/** 37 */>/** 38 */(/** 39 */T /** 40 */t/** 41 */, /** 42 */U /** 43 */u/** 44 */) /** 45 */where /** 46 */T /** 47 */: /** 48 */U/** 49 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (17,215): warning CS1587: XML comment is not placed on a valid language element // /** 30 */delegate /** 31 */void /** 32 */D/** 33 */</** 34 */T/** 35 */, /** 36 */U/** 37 */>/** 38 */(/** 39 */T /** 40 */t/** 41 */, /** 42 */U /** 43 */u/** 44 */) /** 45 */where /** 46 */T /** 47 */: /** 48 */U/** 49 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (19,15): warning CS1587: XML comment is not placed on a valid language element // /** 50 */enum /** 51 */E /** 52 */: /** 53 */byte Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (19,26): warning CS1587: XML comment is not placed on a valid language element // /** 50 */enum /** 51 */E /** 52 */: /** 53 */byte Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (19,37): warning CS1587: XML comment is not placed on a valid language element // /** 50 */enum /** 51 */E /** 52 */: /** 53 */byte Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (20,1): warning CS1587: XML comment is not placed on a valid language element // /** 54 */{ Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (22,1): warning CS1587: XML comment is not placed on a valid language element // /** 55 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (23,1): warning CS1587: XML comment is not placed on a valid language element // /** 56 */ Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/")); } [Fact] public void UnprocessedXMLComment_Members() { var source = @" class C { private int field; private int Property { get; set; } private int this[int x] { get { return 0; } set { } } private event System.Action FieldLikeEvent; private event System.Action CustomEvent { add { } remove { } } private void Method<T, U>(T t, U u) where T : U { } public static int operator +(C c) { return 0; } public static explicit operator int(C c) { return 0; } private C(int x) : base() { } } enum E { A, } "; var revisedSource = new DocumentationCommentAdder().Visit(Parse(source).GetCompilationUnitRoot()).ToFullString(); // Manually verified that positions match dev11. CreateCompilationUtil(revisedSource).VerifyDiagnostics( // (4,41): warning CS0169: The field 'C.field' is never used // /** 3 */private /** 4 */int /** 5 */field/** 6 */; Diagnostic(ErrorCode.WRN_UnreferencedField, "field").WithArguments("C.field"), // (7,87): warning CS0067: The event 'C.FieldLikeEvent' is never used // /** 34 */private /** 35 */event /** 36 */System/** 37 */./** 38 */Action /** 39 */FieldLikeEvent/** 40 */; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "FieldLikeEvent").WithArguments("C.FieldLikeEvent"), // (2,15): warning CS1587: XML comment is not placed on a valid language element // /** 0 */class /** 1 */C Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (3,1): warning CS1587: XML comment is not placed on a valid language element // /** 2 */{ Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (4,21): warning CS1587: XML comment is not placed on a valid language element // /** 3 */private /** 4 */int /** 5 */field/** 6 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (4,33): warning CS1587: XML comment is not placed on a valid language element // /** 3 */private /** 4 */int /** 5 */field/** 6 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (4,46): warning CS1587: XML comment is not placed on a valid language element // /** 3 */private /** 4 */int /** 5 */field/** 6 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (5,21): warning CS1587: XML comment is not placed on a valid language element // /** 7 */private /** 8 */int /** 9 */Property /** 10 */{ /** 11 */get/** 12 */; /** 13 */set/** 14 */; /** 15 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (5,33): warning CS1587: XML comment is not placed on a valid language element // /** 7 */private /** 8 */int /** 9 */Property /** 10 */{ /** 11 */get/** 12 */; /** 13 */set/** 14 */; /** 15 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (5,50): warning CS1587: XML comment is not placed on a valid language element // /** 7 */private /** 8 */int /** 9 */Property /** 10 */{ /** 11 */get/** 12 */; /** 13 */set/** 14 */; /** 15 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (5,61): warning CS1587: XML comment is not placed on a valid language element // /** 7 */private /** 8 */int /** 9 */Property /** 10 */{ /** 11 */get/** 12 */; /** 13 */set/** 14 */; /** 15 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (5,73): warning CS1587: XML comment is not placed on a valid language element // /** 7 */private /** 8 */int /** 9 */Property /** 10 */{ /** 11 */get/** 12 */; /** 13 */set/** 14 */; /** 15 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (5,84): warning CS1587: XML comment is not placed on a valid language element // /** 7 */private /** 8 */int /** 9 */Property /** 10 */{ /** 11 */get/** 12 */; /** 13 */set/** 14 */; /** 15 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (5,96): warning CS1587: XML comment is not placed on a valid language element // /** 7 */private /** 8 */int /** 9 */Property /** 10 */{ /** 11 */get/** 12 */; /** 13 */set/** 14 */; /** 15 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (5,107): warning CS1587: XML comment is not placed on a valid language element // /** 7 */private /** 8 */int /** 9 */Property /** 10 */{ /** 11 */get/** 12 */; /** 13 */set/** 14 */; /** 15 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (6,22): warning CS1587: XML comment is not placed on a valid language element // /** 16 */private /** 17 */int /** 18 */this/** 19 */[/** 20 */int /** 21 */x/** 22 */] /** 23 */{ /** 24 */get /** 25 */{ /** 26 */return /** 27 */0/** 28 */; /** 29 */} /** 30 */set /** 31 */{ /** 32 */} /** 33 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (6,35): warning CS1587: XML comment is not placed on a valid language element // /** 16 */private /** 17 */int /** 18 */this/** 19 */[/** 20 */int /** 21 */x/** 22 */] /** 23 */{ /** 24 */get /** 25 */{ /** 26 */return /** 27 */0/** 28 */; /** 29 */} /** 30 */set /** 31 */{ /** 32 */} /** 33 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (6,48): warning CS1587: XML comment is not placed on a valid language element // /** 16 */private /** 17 */int /** 18 */this/** 19 */[/** 20 */int /** 21 */x/** 22 */] /** 23 */{ /** 24 */get /** 25 */{ /** 26 */return /** 27 */0/** 28 */; /** 29 */} /** 30 */set /** 31 */{ /** 32 */} /** 33 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (6,58): warning CS1587: XML comment is not placed on a valid language element // /** 16 */private /** 17 */int /** 18 */this/** 19 */[/** 20 */int /** 21 */x/** 22 */] /** 23 */{ /** 24 */get /** 25 */{ /** 26 */return /** 27 */0/** 28 */; /** 29 */} /** 30 */set /** 31 */{ /** 32 */} /** 33 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (6,71): warning CS1587: XML comment is not placed on a valid language element // /** 16 */private /** 17 */int /** 18 */this/** 19 */[/** 20 */int /** 21 */x/** 22 */] /** 23 */{ /** 24 */get /** 25 */{ /** 26 */return /** 27 */0/** 28 */; /** 29 */} /** 30 */set /** 31 */{ /** 32 */} /** 33 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (6,81): warning CS1587: XML comment is not placed on a valid language element // /** 16 */private /** 17 */int /** 18 */this/** 19 */[/** 20 */int /** 21 */x/** 22 */] /** 23 */{ /** 24 */get /** 25 */{ /** 26 */return /** 27 */0/** 28 */; /** 29 */} /** 30 */set /** 31 */{ /** 32 */} /** 33 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (6,92): warning CS1587: XML comment is not placed on a valid language element // /** 16 */private /** 17 */int /** 18 */this/** 19 */[/** 20 */int /** 21 */x/** 22 */] /** 23 */{ /** 24 */get /** 25 */{ /** 26 */return /** 27 */0/** 28 */; /** 29 */} /** 30 */set /** 31 */{ /** 32 */} /** 33 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (6,103): warning CS1587: XML comment is not placed on a valid language element // /** 16 */private /** 17 */int /** 18 */this/** 19 */[/** 20 */int /** 21 */x/** 22 */] /** 23 */{ /** 24 */get /** 25 */{ /** 26 */return /** 27 */0/** 28 */; /** 29 */} /** 30 */set /** 31 */{ /** 32 */} /** 33 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (6,116): warning CS1587: XML comment is not placed on a valid language element // /** 16 */private /** 17 */int /** 18 */this/** 19 */[/** 20 */int /** 21 */x/** 22 */] /** 23 */{ /** 24 */get /** 25 */{ /** 26 */return /** 27 */0/** 28 */; /** 29 */} /** 30 */set /** 31 */{ /** 32 */} /** 33 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (6,127): warning CS1587: XML comment is not placed on a valid language element // /** 16 */private /** 17 */int /** 18 */this/** 19 */[/** 20 */int /** 21 */x/** 22 */] /** 23 */{ /** 24 */get /** 25 */{ /** 26 */return /** 27 */0/** 28 */; /** 29 */} /** 30 */set /** 31 */{ /** 32 */} /** 33 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (6,143): warning CS1587: XML comment is not placed on a valid language element // /** 16 */private /** 17 */int /** 18 */this/** 19 */[/** 20 */int /** 21 */x/** 22 */] /** 23 */{ /** 24 */get /** 25 */{ /** 26 */return /** 27 */0/** 28 */; /** 29 */} /** 30 */set /** 31 */{ /** 32 */} /** 33 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (6,153): warning CS1587: XML comment is not placed on a valid language element // /** 16 */private /** 17 */int /** 18 */this/** 19 */[/** 20 */int /** 21 */x/** 22 */] /** 23 */{ /** 24 */get /** 25 */{ /** 26 */return /** 27 */0/** 28 */; /** 29 */} /** 30 */set /** 31 */{ /** 32 */} /** 33 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (6,164): warning CS1587: XML comment is not placed on a valid language element // /** 16 */private /** 17 */int /** 18 */this/** 19 */[/** 20 */int /** 21 */x/** 22 */] /** 23 */{ /** 24 */get /** 25 */{ /** 26 */return /** 27 */0/** 28 */; /** 29 */} /** 30 */set /** 31 */{ /** 32 */} /** 33 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (6,175): warning CS1587: XML comment is not placed on a valid language element // /** 16 */private /** 17 */int /** 18 */this/** 19 */[/** 20 */int /** 21 */x/** 22 */] /** 23 */{ /** 24 */get /** 25 */{ /** 26 */return /** 27 */0/** 28 */; /** 29 */} /** 30 */set /** 31 */{ /** 32 */} /** 33 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (6,188): warning CS1587: XML comment is not placed on a valid language element // /** 16 */private /** 17 */int /** 18 */this/** 19 */[/** 20 */int /** 21 */x/** 22 */] /** 23 */{ /** 24 */get /** 25 */{ /** 26 */return /** 27 */0/** 28 */; /** 29 */} /** 30 */set /** 31 */{ /** 32 */} /** 33 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (6,199): warning CS1587: XML comment is not placed on a valid language element // /** 16 */private /** 17 */int /** 18 */this/** 19 */[/** 20 */int /** 21 */x/** 22 */] /** 23 */{ /** 24 */get /** 25 */{ /** 26 */return /** 27 */0/** 28 */; /** 29 */} /** 30 */set /** 31 */{ /** 32 */} /** 33 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (6,210): warning CS1587: XML comment is not placed on a valid language element // /** 16 */private /** 17 */int /** 18 */this/** 19 */[/** 20 */int /** 21 */x/** 22 */] /** 23 */{ /** 24 */get /** 25 */{ /** 26 */return /** 27 */0/** 28 */; /** 29 */} /** 30 */set /** 31 */{ /** 32 */} /** 33 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (7,22): warning CS1587: XML comment is not placed on a valid language element // /** 34 */private /** 35 */event /** 36 */System/** 37 */./** 38 */Action /** 39 */FieldLikeEvent/** 40 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (7,37): warning CS1587: XML comment is not placed on a valid language element // /** 34 */private /** 35 */event /** 36 */System/** 37 */./** 38 */Action /** 39 */FieldLikeEvent/** 40 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (7,52): warning CS1587: XML comment is not placed on a valid language element // /** 34 */private /** 35 */event /** 36 */System/** 37 */./** 38 */Action /** 39 */FieldLikeEvent/** 40 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (7,62): warning CS1587: XML comment is not placed on a valid language element // /** 34 */private /** 35 */event /** 36 */System/** 37 */./** 38 */Action /** 39 */FieldLikeEvent/** 40 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (7,78): warning CS1587: XML comment is not placed on a valid language element // /** 34 */private /** 35 */event /** 36 */System/** 37 */./** 38 */Action /** 39 */FieldLikeEvent/** 40 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (7,101): warning CS1587: XML comment is not placed on a valid language element // /** 34 */private /** 35 */event /** 36 */System/** 37 */./** 38 */Action /** 39 */FieldLikeEvent/** 40 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (8,22): warning CS1587: XML comment is not placed on a valid language element // /** 41 */private /** 42 */event /** 43 */System/** 44 */./** 45 */Action /** 46 */CustomEvent /** 47 */{ /** 48 */add /** 49 */{ /** 50 */} /** 51 */remove /** 52 */{ /** 53 */} /** 54 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (8,37): warning CS1587: XML comment is not placed on a valid language element // /** 41 */private /** 42 */event /** 43 */System/** 44 */./** 45 */Action /** 46 */CustomEvent /** 47 */{ /** 48 */add /** 49 */{ /** 50 */} /** 51 */remove /** 52 */{ /** 53 */} /** 54 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (8,52): warning CS1587: XML comment is not placed on a valid language element // /** 41 */private /** 42 */event /** 43 */System/** 44 */./** 45 */Action /** 46 */CustomEvent /** 47 */{ /** 48 */add /** 49 */{ /** 50 */} /** 51 */remove /** 52 */{ /** 53 */} /** 54 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (8,62): warning CS1587: XML comment is not placed on a valid language element // /** 41 */private /** 42 */event /** 43 */System/** 44 */./** 45 */Action /** 46 */CustomEvent /** 47 */{ /** 48 */add /** 49 */{ /** 50 */} /** 51 */remove /** 52 */{ /** 53 */} /** 54 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (8,78): warning CS1587: XML comment is not placed on a valid language element // /** 41 */private /** 42 */event /** 43 */System/** 44 */./** 45 */Action /** 46 */CustomEvent /** 47 */{ /** 48 */add /** 49 */{ /** 50 */} /** 51 */remove /** 52 */{ /** 53 */} /** 54 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (8,99): warning CS1587: XML comment is not placed on a valid language element // /** 41 */private /** 42 */event /** 43 */System/** 44 */./** 45 */Action /** 46 */CustomEvent /** 47 */{ /** 48 */add /** 49 */{ /** 50 */} /** 51 */remove /** 52 */{ /** 53 */} /** 54 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (8,110): warning CS1587: XML comment is not placed on a valid language element // /** 41 */private /** 42 */event /** 43 */System/** 44 */./** 45 */Action /** 46 */CustomEvent /** 47 */{ /** 48 */add /** 49 */{ /** 50 */} /** 51 */remove /** 52 */{ /** 53 */} /** 54 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (8,123): warning CS1587: XML comment is not placed on a valid language element // /** 41 */private /** 42 */event /** 43 */System/** 44 */./** 45 */Action /** 46 */CustomEvent /** 47 */{ /** 48 */add /** 49 */{ /** 50 */} /** 51 */remove /** 52 */{ /** 53 */} /** 54 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (8,134): warning CS1587: XML comment is not placed on a valid language element // /** 41 */private /** 42 */event /** 43 */System/** 44 */./** 45 */Action /** 46 */CustomEvent /** 47 */{ /** 48 */add /** 49 */{ /** 50 */} /** 51 */remove /** 52 */{ /** 53 */} /** 54 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (8,145): warning CS1587: XML comment is not placed on a valid language element // /** 41 */private /** 42 */event /** 43 */System/** 44 */./** 45 */Action /** 46 */CustomEvent /** 47 */{ /** 48 */add /** 49 */{ /** 50 */} /** 51 */remove /** 52 */{ /** 53 */} /** 54 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (8,161): warning CS1587: XML comment is not placed on a valid language element // /** 41 */private /** 42 */event /** 43 */System/** 44 */./** 45 */Action /** 46 */CustomEvent /** 47 */{ /** 48 */add /** 49 */{ /** 50 */} /** 51 */remove /** 52 */{ /** 53 */} /** 54 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (8,172): warning CS1587: XML comment is not placed on a valid language element // /** 41 */private /** 42 */event /** 43 */System/** 44 */./** 45 */Action /** 46 */CustomEvent /** 47 */{ /** 48 */add /** 49 */{ /** 50 */} /** 51 */remove /** 52 */{ /** 53 */} /** 54 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (8,183): warning CS1587: XML comment is not placed on a valid language element // /** 41 */private /** 42 */event /** 43 */System/** 44 */./** 45 */Action /** 46 */CustomEvent /** 47 */{ /** 48 */add /** 49 */{ /** 50 */} /** 51 */remove /** 52 */{ /** 53 */} /** 54 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (9,22): warning CS1587: XML comment is not placed on a valid language element // /** 55 */private /** 56 */void /** 57 */Method/** 58 */</** 59 */T/** 60 */, /** 61 */U/** 62 */>/** 63 */(/** 64 */T /** 65 */t/** 66 */, /** 67 */U /** 68 */u/** 69 */) /** 70 */where /** 71 */T /** 72 */: /** 73 */U /** 74 */{ /** 75 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (9,36): warning CS1587: XML comment is not placed on a valid language element // /** 55 */private /** 56 */void /** 57 */Method/** 58 */</** 59 */T/** 60 */, /** 61 */U/** 62 */>/** 63 */(/** 64 */T /** 65 */t/** 66 */, /** 67 */U /** 68 */u/** 69 */) /** 70 */where /** 71 */T /** 72 */: /** 73 */U /** 74 */{ /** 75 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (9,51): warning CS1587: XML comment is not placed on a valid language element // /** 55 */private /** 56 */void /** 57 */Method/** 58 */</** 59 */T/** 60 */, /** 61 */U/** 62 */>/** 63 */(/** 64 */T /** 65 */t/** 66 */, /** 67 */U /** 68 */u/** 69 */) /** 70 */where /** 71 */T /** 72 */: /** 73 */U /** 74 */{ /** 75 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (9,61): warning CS1587: XML comment is not placed on a valid language element // /** 55 */private /** 56 */void /** 57 */Method/** 58 */</** 59 */T/** 60 */, /** 61 */U/** 62 */>/** 63 */(/** 64 */T /** 65 */t/** 66 */, /** 67 */U /** 68 */u/** 69 */) /** 70 */where /** 71 */T /** 72 */: /** 73 */U /** 74 */{ /** 75 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (9,71): warning CS1587: XML comment is not placed on a valid language element // /** 55 */private /** 56 */void /** 57 */Method/** 58 */</** 59 */T/** 60 */, /** 61 */U/** 62 */>/** 63 */(/** 64 */T /** 65 */t/** 66 */, /** 67 */U /** 68 */u/** 69 */) /** 70 */where /** 71 */T /** 72 */: /** 73 */U /** 74 */{ /** 75 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (9,82): warning CS1587: XML comment is not placed on a valid language element // /** 55 */private /** 56 */void /** 57 */Method/** 58 */</** 59 */T/** 60 */, /** 61 */U/** 62 */>/** 63 */(/** 64 */T /** 65 */t/** 66 */, /** 67 */U /** 68 */u/** 69 */) /** 70 */where /** 71 */T /** 72 */: /** 73 */U /** 74 */{ /** 75 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (9,92): warning CS1587: XML comment is not placed on a valid language element // /** 55 */private /** 56 */void /** 57 */Method/** 58 */</** 59 */T/** 60 */, /** 61 */U/** 62 */>/** 63 */(/** 64 */T /** 65 */t/** 66 */, /** 67 */U /** 68 */u/** 69 */) /** 70 */where /** 71 */T /** 72 */: /** 73 */U /** 74 */{ /** 75 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (9,102): warning CS1587: XML comment is not placed on a valid language element // /** 55 */private /** 56 */void /** 57 */Method/** 58 */</** 59 */T/** 60 */, /** 61 */U/** 62 */>/** 63 */(/** 64 */T /** 65 */t/** 66 */, /** 67 */U /** 68 */u/** 69 */) /** 70 */where /** 71 */T /** 72 */: /** 73 */U /** 74 */{ /** 75 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (9,112): warning CS1587: XML comment is not placed on a valid language element // /** 55 */private /** 56 */void /** 57 */Method/** 58 */</** 59 */T/** 60 */, /** 61 */U/** 62 */>/** 63 */(/** 64 */T /** 65 */t/** 66 */, /** 67 */U /** 68 */u/** 69 */) /** 70 */where /** 71 */T /** 72 */: /** 73 */U /** 74 */{ /** 75 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (9,123): warning CS1587: XML comment is not placed on a valid language element // /** 55 */private /** 56 */void /** 57 */Method/** 58 */</** 59 */T/** 60 */, /** 61 */U/** 62 */>/** 63 */(/** 64 */T /** 65 */t/** 66 */, /** 67 */U /** 68 */u/** 69 */) /** 70 */where /** 71 */T /** 72 */: /** 73 */U /** 74 */{ /** 75 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (9,133): warning CS1587: XML comment is not placed on a valid language element // /** 55 */private /** 56 */void /** 57 */Method/** 58 */</** 59 */T/** 60 */, /** 61 */U/** 62 */>/** 63 */(/** 64 */T /** 65 */t/** 66 */, /** 67 */U /** 68 */u/** 69 */) /** 70 */where /** 71 */T /** 72 */: /** 73 */U /** 74 */{ /** 75 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (9,144): warning CS1587: XML comment is not placed on a valid language element // /** 55 */private /** 56 */void /** 57 */Method/** 58 */</** 59 */T/** 60 */, /** 61 */U/** 62 */>/** 63 */(/** 64 */T /** 65 */t/** 66 */, /** 67 */U /** 68 */u/** 69 */) /** 70 */where /** 71 */T /** 72 */: /** 73 */U /** 74 */{ /** 75 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (9,155): warning CS1587: XML comment is not placed on a valid language element // /** 55 */private /** 56 */void /** 57 */Method/** 58 */</** 59 */T/** 60 */, /** 61 */U/** 62 */>/** 63 */(/** 64 */T /** 65 */t/** 66 */, /** 67 */U /** 68 */u/** 69 */) /** 70 */where /** 71 */T /** 72 */: /** 73 */U /** 74 */{ /** 75 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (9,165): warning CS1587: XML comment is not placed on a valid language element // /** 55 */private /** 56 */void /** 57 */Method/** 58 */</** 59 */T/** 60 */, /** 61 */U/** 62 */>/** 63 */(/** 64 */T /** 65 */t/** 66 */, /** 67 */U /** 68 */u/** 69 */) /** 70 */where /** 71 */T /** 72 */: /** 73 */U /** 74 */{ /** 75 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (9,176): warning CS1587: XML comment is not placed on a valid language element // /** 55 */private /** 56 */void /** 57 */Method/** 58 */</** 59 */T/** 60 */, /** 61 */U/** 62 */>/** 63 */(/** 64 */T /** 65 */t/** 66 */, /** 67 */U /** 68 */u/** 69 */) /** 70 */where /** 71 */T /** 72 */: /** 73 */U /** 74 */{ /** 75 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (9,191): warning CS1587: XML comment is not placed on a valid language element // /** 55 */private /** 56 */void /** 57 */Method/** 58 */</** 59 */T/** 60 */, /** 61 */U/** 62 */>/** 63 */(/** 64 */T /** 65 */t/** 66 */, /** 67 */U /** 68 */u/** 69 */) /** 70 */where /** 71 */T /** 72 */: /** 73 */U /** 74 */{ /** 75 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (9,202): warning CS1587: XML comment is not placed on a valid language element // /** 55 */private /** 56 */void /** 57 */Method/** 58 */</** 59 */T/** 60 */, /** 61 */U/** 62 */>/** 63 */(/** 64 */T /** 65 */t/** 66 */, /** 67 */U /** 68 */u/** 69 */) /** 70 */where /** 71 */T /** 72 */: /** 73 */U /** 74 */{ /** 75 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (9,213): warning CS1587: XML comment is not placed on a valid language element // /** 55 */private /** 56 */void /** 57 */Method/** 58 */</** 59 */T/** 60 */, /** 61 */U/** 62 */>/** 63 */(/** 64 */T /** 65 */t/** 66 */, /** 67 */U /** 68 */u/** 69 */) /** 70 */where /** 71 */T /** 72 */: /** 73 */U /** 74 */{ /** 75 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (9,224): warning CS1587: XML comment is not placed on a valid language element // /** 55 */private /** 56 */void /** 57 */Method/** 58 */</** 59 */T/** 60 */, /** 61 */U/** 62 */>/** 63 */(/** 64 */T /** 65 */t/** 66 */, /** 67 */U /** 68 */u/** 69 */) /** 70 */where /** 71 */T /** 72 */: /** 73 */U /** 74 */{ /** 75 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (9,235): warning CS1587: XML comment is not placed on a valid language element // /** 55 */private /** 56 */void /** 57 */Method/** 58 */</** 59 */T/** 60 */, /** 61 */U/** 62 */>/** 63 */(/** 64 */T /** 65 */t/** 66 */, /** 67 */U /** 68 */u/** 69 */) /** 70 */where /** 71 */T /** 72 */: /** 73 */U /** 74 */{ /** 75 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (10,21): warning CS1587: XML comment is not placed on a valid language element // /** 76 */public /** 77 */static /** 78 */int /** 79 */operator /** 80 */+/** 81 */(/** 82 */C /** 83 */c/** 84 */) /** 85 */{ /** 86 */return /** 87 */0/** 88 */; /** 89 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (10,37): warning CS1587: XML comment is not placed on a valid language element // /** 76 */public /** 77 */static /** 78 */int /** 79 */operator /** 80 */+/** 81 */(/** 82 */C /** 83 */c/** 84 */) /** 85 */{ /** 86 */return /** 87 */0/** 88 */; /** 89 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (10,50): warning CS1587: XML comment is not placed on a valid language element // /** 76 */public /** 77 */static /** 78 */int /** 79 */operator /** 80 */+/** 81 */(/** 82 */C /** 83 */c/** 84 */) /** 85 */{ /** 86 */return /** 87 */0/** 88 */; /** 89 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (10,68): warning CS1587: XML comment is not placed on a valid language element // /** 76 */public /** 77 */static /** 78 */int /** 79 */operator /** 80 */+/** 81 */(/** 82 */C /** 83 */c/** 84 */) /** 85 */{ /** 86 */return /** 87 */0/** 88 */; /** 89 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (10,78): warning CS1587: XML comment is not placed on a valid language element // /** 76 */public /** 77 */static /** 78 */int /** 79 */operator /** 80 */+/** 81 */(/** 82 */C /** 83 */c/** 84 */) /** 85 */{ /** 86 */return /** 87 */0/** 88 */; /** 89 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (10,88): warning CS1587: XML comment is not placed on a valid language element // /** 76 */public /** 77 */static /** 78 */int /** 79 */operator /** 80 */+/** 81 */(/** 82 */C /** 83 */c/** 84 */) /** 85 */{ /** 86 */return /** 87 */0/** 88 */; /** 89 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (10,99): warning CS1587: XML comment is not placed on a valid language element // /** 76 */public /** 77 */static /** 78 */int /** 79 */operator /** 80 */+/** 81 */(/** 82 */C /** 83 */c/** 84 */) /** 85 */{ /** 86 */return /** 87 */0/** 88 */; /** 89 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (10,109): warning CS1587: XML comment is not placed on a valid language element // /** 76 */public /** 77 */static /** 78 */int /** 79 */operator /** 80 */+/** 81 */(/** 82 */C /** 83 */c/** 84 */) /** 85 */{ /** 86 */return /** 87 */0/** 88 */; /** 89 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (10,120): warning CS1587: XML comment is not placed on a valid language element // /** 76 */public /** 77 */static /** 78 */int /** 79 */operator /** 80 */+/** 81 */(/** 82 */C /** 83 */c/** 84 */) /** 85 */{ /** 86 */return /** 87 */0/** 88 */; /** 89 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (10,131): warning CS1587: XML comment is not placed on a valid language element // /** 76 */public /** 77 */static /** 78 */int /** 79 */operator /** 80 */+/** 81 */(/** 82 */C /** 83 */c/** 84 */) /** 85 */{ /** 86 */return /** 87 */0/** 88 */; /** 89 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (10,147): warning CS1587: XML comment is not placed on a valid language element // /** 76 */public /** 77 */static /** 78 */int /** 79 */operator /** 80 */+/** 81 */(/** 82 */C /** 83 */c/** 84 */) /** 85 */{ /** 86 */return /** 87 */0/** 88 */; /** 89 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (10,157): warning CS1587: XML comment is not placed on a valid language element // /** 76 */public /** 77 */static /** 78 */int /** 79 */operator /** 80 */+/** 81 */(/** 82 */C /** 83 */c/** 84 */) /** 85 */{ /** 86 */return /** 87 */0/** 88 */; /** 89 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (10,168): warning CS1587: XML comment is not placed on a valid language element // /** 76 */public /** 77 */static /** 78 */int /** 79 */operator /** 80 */+/** 81 */(/** 82 */C /** 83 */c/** 84 */) /** 85 */{ /** 86 */return /** 87 */0/** 88 */; /** 89 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (11,21): warning CS1587: XML comment is not placed on a valid language element // /** 90 */public /** 91 */static /** 92 */explicit /** 93 */operator /** 94 */int/** 95 */(/** 96 */C /** 97 */c/** 98 */) /** 99 */{ /** 100 */return /** 101 */0/** 102 */; /** 103 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (11,37): warning CS1587: XML comment is not placed on a valid language element // /** 90 */public /** 91 */static /** 92 */explicit /** 93 */operator /** 94 */int/** 95 */(/** 96 */C /** 97 */c/** 98 */) /** 99 */{ /** 100 */return /** 101 */0/** 102 */; /** 103 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (11,55): warning CS1587: XML comment is not placed on a valid language element // /** 90 */public /** 91 */static /** 92 */explicit /** 93 */operator /** 94 */int/** 95 */(/** 96 */C /** 97 */c/** 98 */) /** 99 */{ /** 100 */return /** 101 */0/** 102 */; /** 103 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (11,73): warning CS1587: XML comment is not placed on a valid language element // /** 90 */public /** 91 */static /** 92 */explicit /** 93 */operator /** 94 */int/** 95 */(/** 96 */C /** 97 */c/** 98 */) /** 99 */{ /** 100 */return /** 101 */0/** 102 */; /** 103 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (11,85): warning CS1587: XML comment is not placed on a valid language element // /** 90 */public /** 91 */static /** 92 */explicit /** 93 */operator /** 94 */int/** 95 */(/** 96 */C /** 97 */c/** 98 */) /** 99 */{ /** 100 */return /** 101 */0/** 102 */; /** 103 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (11,95): warning CS1587: XML comment is not placed on a valid language element // /** 90 */public /** 91 */static /** 92 */explicit /** 93 */operator /** 94 */int/** 95 */(/** 96 */C /** 97 */c/** 98 */) /** 99 */{ /** 100 */return /** 101 */0/** 102 */; /** 103 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (11,106): warning CS1587: XML comment is not placed on a valid language element // /** 90 */public /** 91 */static /** 92 */explicit /** 93 */operator /** 94 */int/** 95 */(/** 96 */C /** 97 */c/** 98 */) /** 99 */{ /** 100 */return /** 101 */0/** 102 */; /** 103 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (11,116): warning CS1587: XML comment is not placed on a valid language element // /** 90 */public /** 91 */static /** 92 */explicit /** 93 */operator /** 94 */int/** 95 */(/** 96 */C /** 97 */c/** 98 */) /** 99 */{ /** 100 */return /** 101 */0/** 102 */; /** 103 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (11,127): warning CS1587: XML comment is not placed on a valid language element // /** 90 */public /** 91 */static /** 92 */explicit /** 93 */operator /** 94 */int/** 95 */(/** 96 */C /** 97 */c/** 98 */) /** 99 */{ /** 100 */return /** 101 */0/** 102 */; /** 103 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (11,138): warning CS1587: XML comment is not placed on a valid language element // /** 90 */public /** 91 */static /** 92 */explicit /** 93 */operator /** 94 */int/** 95 */(/** 96 */C /** 97 */c/** 98 */) /** 99 */{ /** 100 */return /** 101 */0/** 102 */; /** 103 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (11,155): warning CS1587: XML comment is not placed on a valid language element // /** 90 */public /** 91 */static /** 92 */explicit /** 93 */operator /** 94 */int/** 95 */(/** 96 */C /** 97 */c/** 98 */) /** 99 */{ /** 100 */return /** 101 */0/** 102 */; /** 103 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (11,166): warning CS1587: XML comment is not placed on a valid language element // /** 90 */public /** 91 */static /** 92 */explicit /** 93 */operator /** 94 */int/** 95 */(/** 96 */C /** 97 */c/** 98 */) /** 99 */{ /** 100 */return /** 101 */0/** 102 */; /** 103 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (11,178): warning CS1587: XML comment is not placed on a valid language element // /** 90 */public /** 91 */static /** 92 */explicit /** 93 */operator /** 94 */int/** 95 */(/** 96 */C /** 97 */c/** 98 */) /** 99 */{ /** 100 */return /** 101 */0/** 102 */; /** 103 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (12,23): warning CS1587: XML comment is not placed on a valid language element // /** 104 */private /** 105 */C/** 106 */(/** 107 */int /** 108 */x/** 109 */) /** 110 */: /** 111 */base/** 112 */(/** 113 */) /** 114 */{ /** 115 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (12,34): warning CS1587: XML comment is not placed on a valid language element // /** 104 */private /** 105 */C/** 106 */(/** 107 */int /** 108 */x/** 109 */) /** 110 */: /** 111 */base/** 112 */(/** 113 */) /** 114 */{ /** 115 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (12,45): warning CS1587: XML comment is not placed on a valid language element // /** 104 */private /** 105 */C/** 106 */(/** 107 */int /** 108 */x/** 109 */) /** 110 */: /** 111 */base/** 112 */(/** 113 */) /** 114 */{ /** 115 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (12,59): warning CS1587: XML comment is not placed on a valid language element // /** 104 */private /** 105 */C/** 106 */(/** 107 */int /** 108 */x/** 109 */) /** 110 */: /** 111 */base/** 112 */(/** 113 */) /** 114 */{ /** 115 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (12,70): warning CS1587: XML comment is not placed on a valid language element // /** 104 */private /** 105 */C/** 106 */(/** 107 */int /** 108 */x/** 109 */) /** 110 */: /** 111 */base/** 112 */(/** 113 */) /** 114 */{ /** 115 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (12,82): warning CS1587: XML comment is not placed on a valid language element // /** 104 */private /** 105 */C/** 106 */(/** 107 */int /** 108 */x/** 109 */) /** 110 */: /** 111 */base/** 112 */(/** 113 */) /** 114 */{ /** 115 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (12,94): warning CS1587: XML comment is not placed on a valid language element // /** 104 */private /** 105 */C/** 106 */(/** 107 */int /** 108 */x/** 109 */) /** 110 */: /** 111 */base/** 112 */(/** 113 */) /** 114 */{ /** 115 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (12,108): warning CS1587: XML comment is not placed on a valid language element // /** 104 */private /** 105 */C/** 106 */(/** 107 */int /** 108 */x/** 109 */) /** 110 */: /** 111 */base/** 112 */(/** 113 */) /** 114 */{ /** 115 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (12,119): warning CS1587: XML comment is not placed on a valid language element // /** 104 */private /** 105 */C/** 106 */(/** 107 */int /** 108 */x/** 109 */) /** 110 */: /** 111 */base/** 112 */(/** 113 */) /** 114 */{ /** 115 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (12,131): warning CS1587: XML comment is not placed on a valid language element // /** 104 */private /** 105 */C/** 106 */(/** 107 */int /** 108 */x/** 109 */) /** 110 */: /** 111 */base/** 112 */(/** 113 */) /** 114 */{ /** 115 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (12,143): warning CS1587: XML comment is not placed on a valid language element // /** 104 */private /** 105 */C/** 106 */(/** 107 */int /** 108 */x/** 109 */) /** 110 */: /** 111 */base/** 112 */(/** 113 */) /** 114 */{ /** 115 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (13,1): warning CS1587: XML comment is not placed on a valid language element // /** 116 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (15,16): warning CS1587: XML comment is not placed on a valid language element // /** 117 */enum /** 118 */E Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (16,1): warning CS1587: XML comment is not placed on a valid language element // /** 119 */{ Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (17,16): warning CS1587: XML comment is not placed on a valid language element // /** 120 */A/** 121 */, Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (18,1): warning CS1587: XML comment is not placed on a valid language element // /** 122 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (19,1): warning CS1587: XML comment is not placed on a valid language element // /** 123 */ Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/")); } [Fact] public void UnprocessedXMLComment_Expressions() { var source = @" class C { private int field = 1; private event System.Action FieldLikeEvent = () => { return; }; private C(int x = 1, int y = 2) { } private C(int x) : this(x, x + 1) { int y = x--; } } enum E { A = 1 + 1, } "; var revisedSource = new DocumentationCommentAdder().Visit(Parse(source).GetCompilationUnitRoot()).ToFullString(); // Manually verified that positions match dev11. CreateCompilationUtil(revisedSource).VerifyDiagnostics( // (4,41): warning CS0414: The field 'C.field' is assigned but its value is never used // /** 3 */private /** 4 */int /** 5 */field /** 6 */= /** 7 */1/** 8 */; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "field").WithArguments("C.field"), // (2,15): warning CS1587: XML comment is not placed on a valid language element // /** 0 */class /** 1 */C Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (3,1): warning CS1587: XML comment is not placed on a valid language element // /** 2 */{ Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (4,21): warning CS1587: XML comment is not placed on a valid language element // /** 3 */private /** 4 */int /** 5 */field /** 6 */= /** 7 */1/** 8 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (4,33): warning CS1587: XML comment is not placed on a valid language element // /** 3 */private /** 4 */int /** 5 */field /** 6 */= /** 7 */1/** 8 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (4,47): warning CS1587: XML comment is not placed on a valid language element // /** 3 */private /** 4 */int /** 5 */field /** 6 */= /** 7 */1/** 8 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (4,57): warning CS1587: XML comment is not placed on a valid language element // /** 3 */private /** 4 */int /** 5 */field /** 6 */= /** 7 */1/** 8 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (4,66): warning CS1587: XML comment is not placed on a valid language element // /** 3 */private /** 4 */int /** 5 */field /** 6 */= /** 7 */1/** 8 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (5,21): warning CS1587: XML comment is not placed on a valid language element // /** 9 */private /** 10 */event /** 11 */System/** 12 */./** 13 */Action /** 14 */FieldLikeEvent /** 15 */= /** 16 */(/** 17 */) /** 18 */=> /** 19 */{ /** 20 */return/** 21 */; /** 22 */}/** 23 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (5,36): warning CS1587: XML comment is not placed on a valid language element // /** 9 */private /** 10 */event /** 11 */System/** 12 */./** 13 */Action /** 14 */FieldLikeEvent /** 15 */= /** 16 */(/** 17 */) /** 18 */=> /** 19 */{ /** 20 */return/** 21 */; /** 22 */}/** 23 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (5,51): warning CS1587: XML comment is not placed on a valid language element // /** 9 */private /** 10 */event /** 11 */System/** 12 */./** 13 */Action /** 14 */FieldLikeEvent /** 15 */= /** 16 */(/** 17 */) /** 18 */=> /** 19 */{ /** 20 */return/** 21 */; /** 22 */}/** 23 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (5,61): warning CS1587: XML comment is not placed on a valid language element // /** 9 */private /** 10 */event /** 11 */System/** 12 */./** 13 */Action /** 14 */FieldLikeEvent /** 15 */= /** 16 */(/** 17 */) /** 18 */=> /** 19 */{ /** 20 */return/** 21 */; /** 22 */}/** 23 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (5,77): warning CS1587: XML comment is not placed on a valid language element // /** 9 */private /** 10 */event /** 11 */System/** 12 */./** 13 */Action /** 14 */FieldLikeEvent /** 15 */= /** 16 */(/** 17 */) /** 18 */=> /** 19 */{ /** 20 */return/** 21 */; /** 22 */}/** 23 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (5,101): warning CS1587: XML comment is not placed on a valid language element // /** 9 */private /** 10 */event /** 11 */System/** 12 */./** 13 */Action /** 14 */FieldLikeEvent /** 15 */= /** 16 */(/** 17 */) /** 18 */=> /** 19 */{ /** 20 */return/** 21 */; /** 22 */}/** 23 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (5,112): warning CS1587: XML comment is not placed on a valid language element // /** 9 */private /** 10 */event /** 11 */System/** 12 */./** 13 */Action /** 14 */FieldLikeEvent /** 15 */= /** 16 */(/** 17 */) /** 18 */=> /** 19 */{ /** 20 */return/** 21 */; /** 22 */}/** 23 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (5,122): warning CS1587: XML comment is not placed on a valid language element // /** 9 */private /** 10 */event /** 11 */System/** 12 */./** 13 */Action /** 14 */FieldLikeEvent /** 15 */= /** 16 */(/** 17 */) /** 18 */=> /** 19 */{ /** 20 */return/** 21 */; /** 22 */}/** 23 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (5,133): warning CS1587: XML comment is not placed on a valid language element // /** 9 */private /** 10 */event /** 11 */System/** 12 */./** 13 */Action /** 14 */FieldLikeEvent /** 15 */= /** 16 */(/** 17 */) /** 18 */=> /** 19 */{ /** 20 */return/** 21 */; /** 22 */}/** 23 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (5,145): warning CS1587: XML comment is not placed on a valid language element // /** 9 */private /** 10 */event /** 11 */System/** 12 */./** 13 */Action /** 14 */FieldLikeEvent /** 15 */= /** 16 */(/** 17 */) /** 18 */=> /** 19 */{ /** 20 */return/** 21 */; /** 22 */}/** 23 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (5,156): warning CS1587: XML comment is not placed on a valid language element // /** 9 */private /** 10 */event /** 11 */System/** 12 */./** 13 */Action /** 14 */FieldLikeEvent /** 15 */= /** 16 */(/** 17 */) /** 18 */=> /** 19 */{ /** 20 */return/** 21 */; /** 22 */}/** 23 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (5,171): warning CS1587: XML comment is not placed on a valid language element // /** 9 */private /** 10 */event /** 11 */System/** 12 */./** 13 */Action /** 14 */FieldLikeEvent /** 15 */= /** 16 */(/** 17 */) /** 18 */=> /** 19 */{ /** 20 */return/** 21 */; /** 22 */}/** 23 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (5,182): warning CS1587: XML comment is not placed on a valid language element // /** 9 */private /** 10 */event /** 11 */System/** 12 */./** 13 */Action /** 14 */FieldLikeEvent /** 15 */= /** 16 */(/** 17 */) /** 18 */=> /** 19 */{ /** 20 */return/** 21 */; /** 22 */}/** 23 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (5,192): warning CS1587: XML comment is not placed on a valid language element // /** 9 */private /** 10 */event /** 11 */System/** 12 */./** 13 */Action /** 14 */FieldLikeEvent /** 15 */= /** 16 */(/** 17 */) /** 18 */=> /** 19 */{ /** 20 */return/** 21 */; /** 22 */}/** 23 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (6,22): warning CS1587: XML comment is not placed on a valid language element // /** 24 */private /** 25 */C/** 26 */(/** 27 */int /** 28 */x /** 29 */= /** 30 */1/** 31 */, /** 32 */int /** 33 */y /** 34 */= /** 35 */2/** 36 */) /** 37 */{ /** 38 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (6,32): warning CS1587: XML comment is not placed on a valid language element // /** 24 */private /** 25 */C/** 26 */(/** 27 */int /** 28 */x /** 29 */= /** 30 */1/** 31 */, /** 32 */int /** 33 */y /** 34 */= /** 35 */2/** 36 */) /** 37 */{ /** 38 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (6,42): warning CS1587: XML comment is not placed on a valid language element // /** 24 */private /** 25 */C/** 26 */(/** 27 */int /** 28 */x /** 29 */= /** 30 */1/** 31 */, /** 32 */int /** 33 */y /** 34 */= /** 35 */2/** 36 */) /** 37 */{ /** 38 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (6,55): warning CS1587: XML comment is not placed on a valid language element // /** 24 */private /** 25 */C/** 26 */(/** 27 */int /** 28 */x /** 29 */= /** 30 */1/** 31 */, /** 32 */int /** 33 */y /** 34 */= /** 35 */2/** 36 */) /** 37 */{ /** 38 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (6,66): warning CS1587: XML comment is not placed on a valid language element // /** 24 */private /** 25 */C/** 26 */(/** 27 */int /** 28 */x /** 29 */= /** 30 */1/** 31 */, /** 32 */int /** 33 */y /** 34 */= /** 35 */2/** 36 */) /** 37 */{ /** 38 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (6,77): warning CS1587: XML comment is not placed on a valid language element // /** 24 */private /** 25 */C/** 26 */(/** 27 */int /** 28 */x /** 29 */= /** 30 */1/** 31 */, /** 32 */int /** 33 */y /** 34 */= /** 35 */2/** 36 */) /** 37 */{ /** 38 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (6,87): warning CS1587: XML comment is not placed on a valid language element // /** 24 */private /** 25 */C/** 26 */(/** 27 */int /** 28 */x /** 29 */= /** 30 */1/** 31 */, /** 32 */int /** 33 */y /** 34 */= /** 35 */2/** 36 */) /** 37 */{ /** 38 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (6,98): warning CS1587: XML comment is not placed on a valid language element // /** 24 */private /** 25 */C/** 26 */(/** 27 */int /** 28 */x /** 29 */= /** 30 */1/** 31 */, /** 32 */int /** 33 */y /** 34 */= /** 35 */2/** 36 */) /** 37 */{ /** 38 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (6,111): warning CS1587: XML comment is not placed on a valid language element // /** 24 */private /** 25 */C/** 26 */(/** 27 */int /** 28 */x /** 29 */= /** 30 */1/** 31 */, /** 32 */int /** 33 */y /** 34 */= /** 35 */2/** 36 */) /** 37 */{ /** 38 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (6,122): warning CS1587: XML comment is not placed on a valid language element // /** 24 */private /** 25 */C/** 26 */(/** 27 */int /** 28 */x /** 29 */= /** 30 */1/** 31 */, /** 32 */int /** 33 */y /** 34 */= /** 35 */2/** 36 */) /** 37 */{ /** 38 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (6,133): warning CS1587: XML comment is not placed on a valid language element // /** 24 */private /** 25 */C/** 26 */(/** 27 */int /** 28 */x /** 29 */= /** 30 */1/** 31 */, /** 32 */int /** 33 */y /** 34 */= /** 35 */2/** 36 */) /** 37 */{ /** 38 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (6,143): warning CS1587: XML comment is not placed on a valid language element // /** 24 */private /** 25 */C/** 26 */(/** 27 */int /** 28 */x /** 29 */= /** 30 */1/** 31 */, /** 32 */int /** 33 */y /** 34 */= /** 35 */2/** 36 */) /** 37 */{ /** 38 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (6,154): warning CS1587: XML comment is not placed on a valid language element // /** 24 */private /** 25 */C/** 26 */(/** 27 */int /** 28 */x /** 29 */= /** 30 */1/** 31 */, /** 32 */int /** 33 */y /** 34 */= /** 35 */2/** 36 */) /** 37 */{ /** 38 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (6,165): warning CS1587: XML comment is not placed on a valid language element // /** 24 */private /** 25 */C/** 26 */(/** 27 */int /** 28 */x /** 29 */= /** 30 */1/** 31 */, /** 32 */int /** 33 */y /** 34 */= /** 35 */2/** 36 */) /** 37 */{ /** 38 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (7,22): warning CS1587: XML comment is not placed on a valid language element // /** 39 */private /** 40 */C/** 41 */(/** 42 */int /** 43 */x/** 44 */) /** 45 */: /** 46 */this/** 47 */(/** 48 */x/** 49 */, /** 50 */x /** 51 */+ /** 52 */1/** 53 */) Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (7,32): warning CS1587: XML comment is not placed on a valid language element // /** 39 */private /** 40 */C/** 41 */(/** 42 */int /** 43 */x/** 44 */) /** 45 */: /** 46 */this/** 47 */(/** 48 */x/** 49 */, /** 50 */x /** 51 */+ /** 52 */1/** 53 */) Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (7,42): warning CS1587: XML comment is not placed on a valid language element // /** 39 */private /** 40 */C/** 41 */(/** 42 */int /** 43 */x/** 44 */) /** 45 */: /** 46 */this/** 47 */(/** 48 */x/** 49 */, /** 50 */x /** 51 */+ /** 52 */1/** 53 */) Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (7,55): warning CS1587: XML comment is not placed on a valid language element // /** 39 */private /** 40 */C/** 41 */(/** 42 */int /** 43 */x/** 44 */) /** 45 */: /** 46 */this/** 47 */(/** 48 */x/** 49 */, /** 50 */x /** 51 */+ /** 52 */1/** 53 */) Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (7,65): warning CS1587: XML comment is not placed on a valid language element // /** 39 */private /** 40 */C/** 41 */(/** 42 */int /** 43 */x/** 44 */) /** 45 */: /** 46 */this/** 47 */(/** 48 */x/** 49 */, /** 50 */x /** 51 */+ /** 52 */1/** 53 */) Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (7,76): warning CS1587: XML comment is not placed on a valid language element // /** 39 */private /** 40 */C/** 41 */(/** 42 */int /** 43 */x/** 44 */) /** 45 */: /** 46 */this/** 47 */(/** 48 */x/** 49 */, /** 50 */x /** 51 */+ /** 52 */1/** 53 */) Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (7,87): warning CS1587: XML comment is not placed on a valid language element // /** 39 */private /** 40 */C/** 41 */(/** 42 */int /** 43 */x/** 44 */) /** 45 */: /** 46 */this/** 47 */(/** 48 */x/** 49 */, /** 50 */x /** 51 */+ /** 52 */1/** 53 */) Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (7,100): warning CS1587: XML comment is not placed on a valid language element // /** 39 */private /** 40 */C/** 41 */(/** 42 */int /** 43 */x/** 44 */) /** 45 */: /** 46 */this/** 47 */(/** 48 */x/** 49 */, /** 50 */x /** 51 */+ /** 52 */1/** 53 */) Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (7,110): warning CS1587: XML comment is not placed on a valid language element // /** 39 */private /** 40 */C/** 41 */(/** 42 */int /** 43 */x/** 44 */) /** 45 */: /** 46 */this/** 47 */(/** 48 */x/** 49 */, /** 50 */x /** 51 */+ /** 52 */1/** 53 */) Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (7,120): warning CS1587: XML comment is not placed on a valid language element // /** 39 */private /** 40 */C/** 41 */(/** 42 */int /** 43 */x/** 44 */) /** 45 */: /** 46 */this/** 47 */(/** 48 */x/** 49 */, /** 50 */x /** 51 */+ /** 52 */1/** 53 */) Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (7,131): warning CS1587: XML comment is not placed on a valid language element // /** 39 */private /** 40 */C/** 41 */(/** 42 */int /** 43 */x/** 44 */) /** 45 */: /** 46 */this/** 47 */(/** 48 */x/** 49 */, /** 50 */x /** 51 */+ /** 52 */1/** 53 */) Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (7,142): warning CS1587: XML comment is not placed on a valid language element // /** 39 */private /** 40 */C/** 41 */(/** 42 */int /** 43 */x/** 44 */) /** 45 */: /** 46 */this/** 47 */(/** 48 */x/** 49 */, /** 50 */x /** 51 */+ /** 52 */1/** 53 */) Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (7,153): warning CS1587: XML comment is not placed on a valid language element // /** 39 */private /** 40 */C/** 41 */(/** 42 */int /** 43 */x/** 44 */) /** 45 */: /** 46 */this/** 47 */(/** 48 */x/** 49 */, /** 50 */x /** 51 */+ /** 52 */1/** 53 */) Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (7,163): warning CS1587: XML comment is not placed on a valid language element // /** 39 */private /** 40 */C/** 41 */(/** 42 */int /** 43 */x/** 44 */) /** 45 */: /** 46 */this/** 47 */(/** 48 */x/** 49 */, /** 50 */x /** 51 */+ /** 52 */1/** 53 */) Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (8,5): warning CS1587: XML comment is not placed on a valid language element // /** 54 */{ Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (9,9): warning CS1587: XML comment is not placed on a valid language element // /** 55 */int /** 56 */y /** 57 */= /** 58 */x/** 59 */--/** 60 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (9,22): warning CS1587: XML comment is not placed on a valid language element // /** 55 */int /** 56 */y /** 57 */= /** 58 */x/** 59 */--/** 60 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (9,33): warning CS1587: XML comment is not placed on a valid language element // /** 55 */int /** 56 */y /** 57 */= /** 58 */x/** 59 */--/** 60 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (9,44): warning CS1587: XML comment is not placed on a valid language element // /** 55 */int /** 56 */y /** 57 */= /** 58 */x/** 59 */--/** 60 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (9,54): warning CS1587: XML comment is not placed on a valid language element // /** 55 */int /** 56 */y /** 57 */= /** 58 */x/** 59 */--/** 60 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (9,65): warning CS1587: XML comment is not placed on a valid language element // /** 55 */int /** 56 */y /** 57 */= /** 58 */x/** 59 */--/** 60 */; Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (10,5): warning CS1587: XML comment is not placed on a valid language element // /** 61 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (11,1): warning CS1587: XML comment is not placed on a valid language element // /** 62 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (13,15): warning CS1587: XML comment is not placed on a valid language element // /** 63 */enum /** 64 */E Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (14,1): warning CS1587: XML comment is not placed on a valid language element // /** 65 */{ Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (15,16): warning CS1587: XML comment is not placed on a valid language element // /** 66 */A /** 67 */= /** 68 */1 /** 69 */+ /** 70 */1/** 71 */, Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (15,27): warning CS1587: XML comment is not placed on a valid language element // /** 66 */A /** 67 */= /** 68 */1 /** 69 */+ /** 70 */1/** 71 */, Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (15,38): warning CS1587: XML comment is not placed on a valid language element // /** 66 */A /** 67 */= /** 68 */1 /** 69 */+ /** 70 */1/** 71 */, Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (15,49): warning CS1587: XML comment is not placed on a valid language element // /** 66 */A /** 67 */= /** 68 */1 /** 69 */+ /** 70 */1/** 71 */, Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (15,59): warning CS1587: XML comment is not placed on a valid language element // /** 66 */A /** 67 */= /** 68 */1 /** 69 */+ /** 70 */1/** 71 */, Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (16,1): warning CS1587: XML comment is not placed on a valid language element // /** 72 */} Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (17,1): warning CS1587: XML comment is not placed on a valid language element // /** 73 */ Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/")); } [Fact] public void UnprocessedXMLComment_AfterAttribute() { var source = @" [System.Serializable] /// Comment class C { } "; CreateCompilationUtil(source).VerifyDiagnostics( // (3,1): warning CS1587: XML comment is not placed on a valid language element // /// Comment Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/")); } [Fact] public void UnprocessedXMLComment_CompiledOut() { var source = @" class C { #if false /// Comment #endif } "; CreateCompilationUtil(source).VerifyDiagnostics(); } [Fact] public void UnprocessedXMLComment_FilterTree() { var source1 = @" partial class C { /// Unprocessed 1 } "; var source2 = @" partial class C { /// Unprocessed 2 } "; var tree1 = Parse(source1, options: TestOptions.RegularWithDocumentationComments); var tree2 = Parse(source2, options: TestOptions.RegularWithDocumentationComments); var comp = CreateCompilation(new[] { tree1, tree2 }); comp.GetSemanticModel(tree1).GetDiagnostics().Verify( // (4,5): warning CS1587: XML comment is not placed on a valid language element // /// Unprocessed 1 Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/")); comp.GetSemanticModel(tree2).GetDiagnostics().Verify( // (4,5): warning CS1587: XML comment is not placed on a valid language element // /// Unprocessed 2 Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/")); } [Fact] public void UnprocessedXMLComment_Unparsed() { var source = @" partial class C { /// Unprocessed 1 } "; CreateCompilation(source).VerifyDiagnostics(); } [WorkItem(547139, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547139")] [Fact] public void UnprocessedXMLComment_Accessor() { var source = @" class MyClass { string MyProperty { get; /// <param name=""a"" /> /// <param name=""b"" /> set; } } "; CreateCompilationUtil(source).VerifyDiagnostics( // (7,9): warning CS1587: XML comment is not placed on a valid language element // /// <param name="a" /> Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/")); } /// <summary> /// Insert a numbered documentation comment as leading trivia on every token. /// </summary> private class DocumentationCommentAdder : CSharpSyntaxRewriter { private int _count; public override SyntaxToken VisitToken(SyntaxToken token) { var newToken = base.VisitToken(token); if (newToken.Width == 0 && newToken.Kind() != SyntaxKind.EndOfFileToken) { return newToken; } var existingLeadingTrivia = token.LeadingTrivia; var newLeadingTrivia = SyntaxFactory.ParseToken("/** " + (_count++) + " */1)").LeadingTrivia; return newToken.WithLeadingTrivia(existingLeadingTrivia.Concat(newLeadingTrivia)); } } #endregion WRN_UnprocessedXMLComment #region Invalid XML [Fact] public void InvalidXml() { var source = @" /// <unterminated_tag class C1 { } /// <unterminated_element> class C2 { } /// <no_attribute_value attr/> class C3 { } /// <bad_attribute_value attr=""&""/> class C4 { } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp); var expected = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <!-- Badly formed XML comment ignored for member ""T:C1"" --> <!-- Badly formed XML comment ignored for member ""T:C2"" --> <!-- Badly formed XML comment ignored for member ""T:C3"" --> <!-- Badly formed XML comment ignored for member ""T:C4"" --> </members> </doc> ").Trim(); Assert.Equal(expected, actual); } [Fact] public void InvalidXmlOnPartialTypes() { var source = @" /// <invalid partial class C { } /// <valid/> partial class C { } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp); var expected = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <!-- Badly formed XML comment ignored for member ""T:C"" --> </members> </doc> ").Trim(); Assert.Equal(expected, actual); } [Fact] public void InvalidXmlOnPartialMethods() { var source = @" partial class C { /// <invalid1 partial void M1(); /// <valid1/> partial void M2(); } partial class C { /// <valid2/> partial void M1() { } /// <invalid2 partial void M2() { } } "; // NOTE: separate error comment for each part. var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp); var expected = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""M:C.M1""> <valid2/> </member> <!-- Badly formed XML comment ignored for member ""M:C.M1"" --> <!-- Badly formed XML comment ignored for member ""M:C.M2"" --> </members> </doc> ").Trim(); Assert.Equal(expected, actual); } [ConditionalFact(typeof(ClrOnly), typeof(DesktopOnly))] [WorkItem(637435, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/637435")] [WorkItem(18610, "https://github.com/dotnet/roslyn/issues/18610")] public void NonXmlWhitespace() { var ch = '\u1680'; Assert.True(char.IsWhiteSpace(ch)); Assert.True(SyntaxFacts.IsWhitespace(ch)); Assert.False(XmlCharType.IsWhiteSpace(ch)); var xml = "<see\u1680cref='C'/>"; Assert.Throws<XmlException>(() => XElement.Parse(xml)); var sourceTemplate = @" /// {0} class C {{ }} "; var source = string.Format(sourceTemplate, xml); // NOTE: separate error comment for each part. var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp, // (2,4): warning CS1570: XML comment has badly formed XML -- 'The '\u1680' character, hexadecimal value 0x1680, cannot be included in a name.' // /// <see cref='C'/> Diagnostic(ErrorCode.WRN_XMLParseError, "").WithArguments("The '\u1680' character, hexadecimal value 0x1680, cannot be included in a name.")); var expected = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <!-- Badly formed XML comment ignored for member ""T:C"" --> </members> </doc> ").Trim(); Assert.Equal(expected, actual); } [ConditionalFact(typeof(ClrOnly), typeof(DesktopOnly))] [WorkItem(637435, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/637435")] [WorkItem(18610, "https://github.com/dotnet/roslyn/issues/18610")] public void Repro637435() { var sourceTemplate = @" // 1) Both Roslyn and Dev11 report an error. ///<see ///{0}cref='C1'/> class C1 {{ }} // 2) Both Roslyn and Dev11 report an error. /// <see /// {0}cref='C2'/> class C2 {{ }} // 3) Both Roslyn and Dev11 report an error. ///<see /// {0}cref='C3'/> class C3 {{ }} // 4) Dev11 reports an error, but Roslyn does not. /// <see ///{0}cref='C4'/> class C4 {{ }} "; var source = string.Format(sourceTemplate, '\u1680'); CreateCompilationUtil(source).GetDiagnostics().VerifyWithFallbackToErrorCodeOnlyForNonEnglish( // (4,4): warning CS1570: XML comment has badly formed XML -- 'Name cannot begin with the '\u1680' character, hexadecimal value 0x1680.' // ///<see Diagnostic(ErrorCode.WRN_XMLParseError, "").WithArguments("Name cannot begin with the '\u1680' character, hexadecimal value 0x1680."), // (11,4): warning CS1570: XML comment has badly formed XML -- 'Name cannot begin with the '\u1680' character, hexadecimal value 0x1680.' // /// <see Diagnostic(ErrorCode.WRN_XMLParseError, "").WithArguments("Name cannot begin with the '\u1680' character, hexadecimal value 0x1680."), // (18,4): warning CS1570: XML comment has badly formed XML -- 'Name cannot begin with the '\u1680' character, hexadecimal value 0x1680.' // ///<see Diagnostic(ErrorCode.WRN_XMLParseError, "").WithArguments("Name cannot begin with the '\u1680' character, hexadecimal value 0x1680.")); } #endregion Invalid XML #region Include [Fact] public void IncludeNone() { var xml = @" <root/> "; var xmlFile = Temp.CreateFile(extension: ".xml").WriteAllText(xml); string xmlFilePath = xmlFile.Path; var sourceTemplate = @" /// <include file='{0}' path='//target'/> class C {{ }} "; var comp = CreateCompilationUtil(string.Format(sourceTemplate, xmlFilePath)); var actual = GetDocumentationCommentText(comp); var expectedTemplate = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <!-- No matching elements were found for the following include tag --><include file=""{0}"" path=""//target"" /> </member> </members> </doc> ").Trim(); Assert.Equal(string.Format(expectedTemplate, xmlFilePath), actual); } [Fact] public void IncludeOne() { var xml = @" <root> <target stuff=""things"" /> </root> "; var xmlFile = Temp.CreateFile(extension: ".xml").WriteAllText(xml); string xmlFilePath = xmlFile.Path; var sourceTemplate = @" /// <include file='{0}' path='//target'/> class C {{ }} "; var comp = CreateCompilationUtil(string.Format(sourceTemplate, xmlFilePath)); var actual = GetDocumentationCommentText(comp); var expectedTemplate = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <target stuff=""things"" /> </member> </members> </doc> ").Trim(); Assert.Equal(string.Format(expectedTemplate, xmlFilePath), actual); } [Fact] public void IncludeMultiple() { var xml = @" <root> <target stuff=""things"" /> <parent> <target stuff=""garbage"" /> </parent> </root> "; var xmlFile = Temp.CreateFile(extension: ".xml").WriteAllText(xml); string xmlFilePath = xmlFile.Path; var sourceTemplate = @" /// <include file='{0}' path='//target'/> class C {{ }} "; var comp = CreateCompilationUtil(string.Format(sourceTemplate, xmlFilePath)); var actual = GetDocumentationCommentText(comp); var expectedTemplate = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <target stuff=""things"" /><target stuff=""garbage"" /> </member> </members> </doc> ").Trim(); Assert.Equal(string.Format(expectedTemplate, xmlFilePath), actual); } [Fact] public void IncludeWithChildren_Success() { var xml = @" <root> <target stuff=""things"" /> </root> "; var xmlFile = Temp.CreateFile(extension: ".xml").WriteAllText(xml); string xmlFilePath = xmlFile.Path; var sourceTemplate = @" /// <include file='{0}' path='//target'> /// <child /> /// </include> class C {{ }} "; var comp = CreateCompilationUtil(string.Format(sourceTemplate, xmlFilePath)); var actual = GetDocumentationCommentText(comp); var expectedTemplate = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <target stuff=""things"" /> </member> </members> </doc> ").Trim(); Assert.Equal(string.Format(expectedTemplate, xmlFilePath), actual); } [Fact] public void IncludeWithChildren_Failure() { var xml = @" <root> </root> "; var xmlFile = Temp.CreateFile(extension: ".xml").WriteAllText(xml); string xmlFilePath = xmlFile.Path; var sourceTemplate = @" /// <include file='{0}' path='//target'> /// <child /> /// </include> class C {{ }} "; var comp = CreateCompilationUtil(string.Format(sourceTemplate, xmlFilePath)); var actual = GetDocumentationCommentText(comp); var expectedTemplate = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <!-- No matching elements were found for the following include tag --><include file=""{0}"" path=""//target""> <child /> </include> </member> </members> </doc> ").Trim(); Assert.Equal(string.Format(expectedTemplate, xmlFilePath), actual); } [ConditionalFact(typeof(ClrOnly), typeof(DesktopOnly))] [WorkItem(18610, "https://github.com/dotnet/roslyn/issues/18610")] public void IncludeFileResolution() { var xml1 = @" <root> <include file=""test.xml"" path=""//element""/> <!--relative to d1 --> <include file=""d2/test.xml"" path=""//include""/> <!-- relative to root --> <element value=""1""/> </root> "; var xml2 = @" <root> <include file=""test.xml"" path=""//element""/> <!--relative to d2 --> <include file=""d3/test.xml"" path=""//include""/> <!-- relative to root --> <element value=""2""/> </root> "; var xml3 = @" <root> <include file=""test.xml"" path=""//element""/> <!--relative to d3 --> <element value=""3""/> </root> "; var rootDir = Temp.CreateDirectory(); var dir1 = rootDir.CreateDirectory("d1"); var dir1XmlFile = dir1.CreateFile("test.xml").WriteAllText(xml1); var dir2 = rootDir.CreateDirectory("d2"); var dir2XmlFile = dir2.CreateFile("test.xml").WriteAllText(xml2); var dir3 = rootDir.CreateDirectory("d3"); var dir3XmlFile = dir3.CreateFile("test.xml").WriteAllText(xml3); var source = @" /// <include file='d1\test.xml' path='//include' /> class C { } "; var tree = Parse(source, options: TestOptions.RegularWithDocumentationComments); var resolver = new XmlFileResolver(rootDir.Path); var comp = CSharpCompilation.Create("Test", new[] { tree }, new[] { MscorlibRef }, TestOptions.ReleaseDll.WithXmlReferenceResolver(resolver)); var actual = GetDocumentationCommentText(comp); var expected = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <element value=""1"" /><element value=""2"" /><element value=""3"" /> </member> </members> </doc> ").Trim(); Assert.Equal(expected, actual); } [Fact] public void WRN_InvalidInclude_Source() { var source = @" /// <include/> /// <include other='stuff'/> /// <include path='path'/> /// <include file='file'/> class C { } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp, // (2,5): warning CS1590: Invalid XML include element -- Missing file attribute // /// <include/> Diagnostic(ErrorCode.WRN_InvalidInclude, "<include/>").WithArguments("Missing file attribute"), // (3,5): warning CS1590: Invalid XML include element -- Missing file attribute // /// <include other='stuff'/> Diagnostic(ErrorCode.WRN_InvalidInclude, "<include other='stuff'/>").WithArguments("Missing file attribute"), // (4,5): warning CS1590: Invalid XML include element -- Missing file attribute // /// <include path='path'/> Diagnostic(ErrorCode.WRN_InvalidInclude, "<include path='path'/>").WithArguments("Missing file attribute"), // (5,5): warning CS1590: Invalid XML include element -- Missing path attribute // /// <include file='file'/> Diagnostic(ErrorCode.WRN_InvalidInclude, "<include file='file'/>").WithArguments("Missing path attribute")); var expected = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <!-- Include tag is invalid --><include /> <!-- Include tag is invalid --><include other=""stuff"" /> <!-- Include tag is invalid --><include path=""path"" /> <!-- Include tag is invalid --><include file=""file"" /> </member> </members> </doc> ").Trim(); Assert.Equal(expected, actual); } [Fact] public void WRN_InvalidInclude_Xml() { var xml = @" <root> <include/> <include other='stuff'/> <include path='path'/> <include file='file'/> </root> "; var xmlFile = Temp.CreateFile(extension: ".xml").WriteAllText(xml); var sourceTemplate = @" /// <include file='{0}' path='//include'/> class C {{ }} "; var comp = CreateCompilationUtil(string.Format(sourceTemplate, xmlFile.Path)); var actual = GetDocumentationCommentText(comp, // warning CS1590: Invalid XML include element -- Missing file attribute Diagnostic(ErrorCode.WRN_InvalidInclude).WithArguments("Missing file attribute"), // warning CS1590: Invalid XML include element -- Missing file attribute Diagnostic(ErrorCode.WRN_InvalidInclude).WithArguments("Missing file attribute"), // warning CS1590: Invalid XML include element -- Missing file attribute Diagnostic(ErrorCode.WRN_InvalidInclude).WithArguments("Missing file attribute"), // warning CS1590: Invalid XML include element -- Missing path attribute Diagnostic(ErrorCode.WRN_InvalidInclude).WithArguments("Missing path attribute")); // NOTE: the whitespace is external to the selected nodes, so it's not included. var expected = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <include /><include other=""stuff"" /><include path=""path"" /><include file=""file"" /> </member> </members> </doc> ").Trim(); Assert.Equal(expected, actual); } [Fact] public void WRN_FailedInclude_NonExistent_Source() { var source = @" /// <include file='file' path='path'/> class C { } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp, // (2,5): warning CS1589: Unable to include XML fragment 'path' of file 'file' -- File not found. // /// <include file='file' path='path'/> Diagnostic(ErrorCode.WRN_FailedInclude, "<include file='file' path='path'/>").WithArguments("file", "path", "File not found.")); var expected = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <!-- Failed to insert some or all of included XML --><include file=""file"" path=""path"" /> </member> </members> </doc> ").Trim(); Assert.Equal(expected, actual); } [Fact] public void WRN_FailedInclude_NonExistent_Xml() { var xml = @" <root> <include file='file' path='path'/> </root> "; var xmlFile = Temp.CreateFile(extension: ".xml").WriteAllText(xml); var sourceTemplate = @" /// <include file='{0}' path='//include'/> class C {{ }} "; var comp = CreateCompilationUtil(string.Format(sourceTemplate, xmlFile.Path)); var actual = GetDocumentationCommentText(comp, // 56e57d80-44fc-4e2c-b839-0bf3d9c830b7.xml(3,6): warning CS1589: Unable to include XML fragment 'path' of file 'file' -- File not found. Diagnostic(ErrorCode.WRN_FailedInclude).WithArguments("file", "path", "File not found.")); // NOTE: the whitespace is external to the selected nodes, so it's not included. var expected = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <include file=""file"" path=""path"" /> </member> </members> </doc> ").Trim(); Assert.Equal(expected, actual); } [ClrOnlyFact(ClrOnlyReason.Unknown)] public void WRN_FailedInclude_Locked_Source() { var xmlFile = Temp.CreateFile(extension: ".xml"); var xmlFilePath = xmlFile.Path; var includeTemplate = "<include file='{0}' path='path'/>"; var includeElement = string.Format(includeTemplate, xmlFilePath); var sourceTemplate = @" /// {0} class C {{ }} "; using (File.Open(xmlFilePath, FileMode.Open, FileAccess.Write, FileShare.None)) { var comp = CreateCompilationUtil(string.Format(sourceTemplate, includeElement)); var actual = GetDocumentationCommentText(comp, // (2,5): warning CS1589: Unable to include XML fragment 'path' of file 'c3af0dc5a3cf.xml' -- The process cannot access the file 'c3af0dc5a3cf.xml' because it is being used by another process. // /// <include file='c3af0dc5a3cf.xml' path='path'/> Diagnostic(ErrorCode.WRN_FailedInclude, includeElement).WithArguments(xmlFilePath, "path", string.Format("The process cannot access the file '{0}' because it is being used by another process.", xmlFilePath))); var expectedTemplate = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <!-- Failed to insert some or all of included XML --><include file=""{0}"" path=""path"" /> </member> </members> </doc> ").Trim(); Assert.Equal(string.Format(expectedTemplate, xmlFilePath), actual); } } [ClrOnlyFact(ClrOnlyReason.Unknown)] public void WRN_FailedInclude_Locked_Xml() { var xmlFile1 = Temp.CreateFile(extension: ".xml"); var xmlFilePath1 = xmlFile1.Path; var xmlFile2 = Temp.CreateFile(extension: ".xml").WriteAllText(string.Format("<include file='{0}' path='path'/>", xmlFilePath1)); var xmlFilePath2 = xmlFile2.Path; var sourceTemplate = @" /// <include file='{0}' path='//include'/> class C {{ }} "; using (File.Open(xmlFilePath1, FileMode.Open, FileAccess.Write, FileShare.None)) { var comp = CreateCompilationUtil(string.Format(sourceTemplate, xmlFilePath2)); var actual = GetDocumentationCommentText(comp, // 3fba660141b6.xml(1,2): warning CS1589: Unable to include XML fragment 'path' of file 'd4241d125755.xml' -- The process cannot access the file 'd4241d125755.xml' because it is being used by another process. Diagnostic(ErrorCode.WRN_FailedInclude).WithArguments(xmlFilePath1, "path", string.Format("The process cannot access the file '{0}' because it is being used by another process.", xmlFilePath1))); var expectedTemplate = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <include file=""{0}"" path=""path"" /> </member> </members> </doc> ").Trim(); Assert.Equal(string.Format(expectedTemplate, xmlFilePath1), actual); } } [Fact] public void WRN_FailedInclude_XPath_Source() { var xmlFile = Temp.CreateFile(extension: ".xml").WriteAllText("<element/>"); var xmlFilePath = xmlFile.Path; var includeTemplate = "<include file='{0}' path=':'/>"; var includeElement = string.Format(includeTemplate, xmlFilePath); var sourceTemplate = @" /// {0} class C {{ }} "; var comp = CreateCompilationUtil(string.Format(sourceTemplate, includeElement)); var actual = GetDocumentationCommentText(comp, // (2,5): warning CS1589: Unable to include XML fragment 'path' of file 'c3af0dc5a3cf.xml' -- The process cannot access the file 'c3af0dc5a3cf.xml' because it is being used by another process. // /// <include file='c3af0dc5a3cf.xml' path='path'/> Diagnostic(ErrorCode.WRN_FailedInclude, includeElement).WithArguments(xmlFilePath, ":", "':' has an invalid token.")); var expectedTemplate = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <!-- Failed to insert some or all of included XML --><include file=""{0}"" path="":"" /> </member> </members> </doc> ").Trim(); Assert.Equal(string.Format(expectedTemplate, xmlFilePath), actual); } [Fact] public void WRN_FailedInclude_XPath_Xml() { var xmlFile1 = Temp.CreateFile(extension: ".xml").WriteAllText("<element/>"); var xmlFilePath1 = xmlFile1.Path; var xmlFile2 = Temp.CreateFile(extension: ".xml").WriteAllText(string.Format("<include file='{0}' path=':'/>", xmlFilePath1)); var xmlFilePath2 = xmlFile2.Path; var sourceTemplate = @" /// <include file='{0}' path='//include'/> class C {{ }} "; var comp = CreateCompilationUtil(string.Format(sourceTemplate, xmlFilePath2)); var actual = GetDocumentationCommentText(comp, // 3fba660141b6.xml(1,2): warning CS1589: Unable to include XML fragment 'path' of file 'd4241d125755.xml' -- The process cannot access the file 'd4241d125755.xml' because it is being used by another process. Diagnostic(ErrorCode.WRN_FailedInclude).WithArguments(xmlFilePath1, ":", "':' has an invalid token.")); var expectedTemplate = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <include file=""{0}"" path="":"" /> </member> </members> </doc> ").Trim(); Assert.Equal(string.Format(expectedTemplate, xmlFilePath1), actual); } [ClrOnlyFact(ClrOnlyReason.DocumentationComment, Skip = "https://github.com/dotnet/roslyn/issues/8807")] public void WRN_XMLParseIncludeError_Source() { var xmlFile = Temp.CreateFile(extension: ".xml").WriteAllText("<OpenWithoutClose>"); var xmlFilePath = xmlFile.Path; var includeTemplate = "<include file='{0}' path='path'/>"; var includeElement = string.Format(includeTemplate, xmlFilePath); var sourceTemplate = @" /// {0} class C {{ }} "; var comp = CreateCompilationUtil(string.Format(sourceTemplate, includeElement)); var actual = GetDocumentationCommentText(comp, // 327697461814.xml(1,19): warning CS1592: Badly formed XML in included comments file -- 'Unexpected end of file has occurred. The following elements are not closed: OpenWithoutClose.' Diagnostic(ErrorCode.WRN_XMLParseIncludeError).WithArguments("Unexpected end of file has occurred. The following elements are not closed: OpenWithoutClose.")); var expectedTemplate = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <!-- Badly formed XML file ""{0}"" cannot be included --> </member> </members> </doc> ").Trim(); Assert.Equal(string.Format(expectedTemplate, TestHelpers.AsXmlCommentText(xmlFilePath)), actual); } [ConditionalFact(typeof(ClrOnly), typeof(DesktopOnly))] [WorkItem(18610, "https://github.com/dotnet/roslyn/issues/18610")] public void WRN_XMLParseIncludeError_Xml() { var xmlFile1 = Temp.CreateFile(extension: ".xml").WriteAllText("<OpenWithoutClose>"); var xmlFilePath1 = xmlFile1.Path; var xmlFile2 = Temp.CreateFile(extension: ".xml").WriteAllText(string.Format("<include file='{0}' path='path'/>", xmlFilePath1)); var xmlFilePath2 = xmlFile2.Path; var sourceTemplate = @" /// <include file='{0}' path='//include'/> class C {{ }} "; var comp = CreateCompilationUtil(string.Format(sourceTemplate, xmlFilePath2)); var actual = GetDocumentationCommentText(comp, // 408eee49f410.xml(1,19): warning CS1592: Badly formed XML in included comments file -- 'Unexpected end of file has occurred. The following elements are not closed: OpenWithoutClose.' Diagnostic(ErrorCode.WRN_XMLParseIncludeError).WithArguments("Unexpected end of file has occurred. The following elements are not closed: OpenWithoutClose.")); var expectedTemplate = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <!-- No matching elements were found for the following include tag --><include file=""{0}"" path=""//include"" /> </member> </members> </doc> ").Trim(); Assert.Equal(string.Format(expectedTemplate, xmlFilePath2), actual); } [Fact] public void IncludeCycle_Simple() { var xmlFile = Temp.CreateFile(extension: ".xml"); var xmlFilePath = xmlFile.Path; xmlFile.WriteAllText(string.Format(@"<include file=""{0}"" path=""//include""/>", xmlFilePath)); //Includes itself. var sourceTemplate = @" /// <include file='{0}' path='//include'/> class C {{ }} "; var comp = CreateCompilationUtil(string.Format(sourceTemplate, xmlFilePath)); var actual = GetDocumentationCommentText(comp, // 3fba660141b6.xml(1,2): warning CS1589: Unable to include XML fragment 'path' of file 'd4241d125755.xml' -- The process cannot access the file 'd4241d125755.xml' because it is being used by another process. Diagnostic(ErrorCode.WRN_FailedInclude).WithArguments(xmlFilePath, "//include", "Operation caused a stack overflow.")); var expectedTemplate = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <!-- No matching elements were found for the following include tag --><include file=""{0}"" path=""//include"" /> </member> </members> </doc> ").Trim(); Assert.Equal(string.Format(expectedTemplate, xmlFilePath), actual); } [Fact] public void IncludeCycle_Containment() { var xmlFile = Temp.CreateFile(extension: ".xml"); var xmlFilePath = xmlFile.Path; xmlFile.WriteAllText(string.Format(@"<parent><include file=""{0}"" path=""//parent""/></parent>", xmlFilePath)); //Includes its parent. var sourceTemplate = @" /// <include file='{0}' path='//include'/> class C {{ }} "; var comp = CreateCompilationUtil(string.Format(sourceTemplate, xmlFilePath)); // CONSIDER: differs from dev11, but this is a reasonable recovery. var actual = GetDocumentationCommentText(comp, // 3fba660141b6.xml(1,2): warning CS1589: Unable to include XML fragment 'path' of file 'd4241d125755.xml' -- The process cannot access the file 'd4241d125755.xml' because it is being used by another process. Diagnostic(ErrorCode.WRN_FailedInclude).WithArguments(xmlFilePath, "//parent", "Operation caused a stack overflow.")); var expectedTemplate = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <parent><!-- No matching elements were found for the following include tag --><include file=""{0}"" path=""//parent"" /></parent> </member> </members> </doc> ").Trim(); Assert.Equal(string.Format(expectedTemplate, xmlFilePath), actual); } [Fact] public void IncludeCycle_Nesting() { var xmlFile = Temp.CreateFile(extension: ".xml"); var xmlFilePath = xmlFile.Path; xmlFile.WriteAllText(string.Format(@" <include file=""{0}"" path=""//include""> <include file=""{0}"" path=""//include"" /> </include>", xmlFilePath)); //Everything includes everything, includes within includes. var sourceTemplate = @" /// <include file='{0}' path='//include'/> class C {{ }} "; var comp = CreateCompilationUtil(string.Format(sourceTemplate, xmlFilePath)); // CONSIDER: not checked against dev11 - just don't blow up. var actual = GetDocumentationCommentText(comp, // 1dc0fa5fb526.xml(2,2): warning CS1589: Unable to include XML fragment '//include' of file '1dc0fa5fb526.xml' -- Operation caused a stack overflow. Diagnostic(ErrorCode.WRN_FailedInclude).WithArguments(xmlFilePath, "//include", "Operation caused a stack overflow."), // 1dc0fa5fb526.xml(2,2): warning CS1589: Unable to include XML fragment '//include' of file '1dc0fa5fb526.xml' -- Operation caused a stack overflow. Diagnostic(ErrorCode.WRN_FailedInclude).WithArguments(xmlFilePath, "//include", "Operation caused a stack overflow."), // 1dc0fa5fb526.xml(2,2): warning CS1589: Unable to include XML fragment '//include' of file '1dc0fa5fb526.xml' -- Operation caused a stack overflow. Diagnostic(ErrorCode.WRN_FailedInclude).WithArguments(xmlFilePath, "//include", "Operation caused a stack overflow."), // 1dc0fa5fb526.xml(3,6): warning CS1589: Unable to include XML fragment '//include' of file '1dc0fa5fb526.xml' -- Operation caused a stack overflow. Diagnostic(ErrorCode.WRN_FailedInclude).WithArguments(xmlFilePath, "//include", "Operation caused a stack overflow."), // 1dc0fa5fb526.xml(3,6): warning CS1589: Unable to include XML fragment '//include' of file '1dc0fa5fb526.xml' -- Operation caused a stack overflow. Diagnostic(ErrorCode.WRN_FailedInclude).WithArguments(xmlFilePath, "//include", "Operation caused a stack overflow."), // 1dc0fa5fb526.xml(3,6): warning CS1589: Unable to include XML fragment '//include' of file '1dc0fa5fb526.xml' -- Operation caused a stack overflow. Diagnostic(ErrorCode.WRN_FailedInclude).WithArguments(xmlFilePath, "//include", "Operation caused a stack overflow.")); var expectedTemplate = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <!-- No matching elements were found for the following include tag --><include file=""{0}"" path=""//include""> <include file=""{0}"" path=""//include"" /> </include><!-- No matching elements were found for the following include tag --><include file=""{0}"" path=""//include""> <include file=""{0}"" path=""//include"" /> </include><!-- No matching elements were found for the following include tag --><include file=""{0}"" path=""//include"" /><!-- No matching elements were found for the following include tag --><include file=""{0}"" path=""//include""> <include file=""{0}"" path=""//include"" /> </include><!-- No matching elements were found for the following include tag --><include file=""{0}"" path=""//include"" /><!-- No matching elements were found for the following include tag --><include file=""{0}"" path=""//include"" /> </member> </members> </doc> ").Trim(); Assert.Equal(string.Format(expectedTemplate, xmlFilePath), actual); } // It should be legal to include the same acyclic element along multiple paths - that isn't a cycle. [Fact] public void IncludeAlongMultiplePaths() { var xmlFile = Temp.CreateFile(extension: ".xml"); var xmlFilePath = xmlFile.Path; string xmlTemplate = @" <root> <include file=""{0}"" path=""//stuff""/> <stuff/> </root>"; xmlFile.WriteAllText(string.Format(xmlTemplate, xmlFilePath)); var sourceTemplate = @" /// <include file='{0}' path='//include'/> /// <include file='{0}' path='//include'/> class C {{ }} "; var comp = CreateCompilationUtil(string.Format(sourceTemplate, xmlFilePath)); var actual = GetDocumentationCommentText(comp); var expected = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <stuff /> <stuff /> </member> </members> </doc> ").Trim(); Assert.Equal(expected, actual); } // As in dev11, the xpath is evaluated *before* includes are expanded. [Fact] public void XPathAssumesExpandedInclude() { var xmlFile1 = Temp.CreateFile(extension: ".xml"); var xmlFilePath1 = xmlFile1.Path; var xmlFile2 = Temp.CreateFile(extension: ".xml"); var xmlFilePath2 = xmlFile2.Path; string xmlTemplate1 = @"<include file=""{0}"" path=""//stuff""/>"; string xml2 = @"<stuff/>"; xmlFile1.WriteAllText(string.Format(xmlTemplate1, xmlFilePath2)); xmlFile2.WriteAllText(xml2); var sourceTemplate = @" /// <include file='{0}' path='//stuff'/> class C {{ }} "; var comp = CreateCompilationUtil(string.Format(sourceTemplate, xmlFilePath1)); var actual = GetDocumentationCommentText(comp); var expectedTemplate = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <!-- No matching elements were found for the following include tag --><include file=""{0}"" path=""//stuff"" /> </member> </members> </doc> ").Trim(); Assert.Equal(string.Format(expectedTemplate, xmlFilePath1), actual); } [WorkItem(554196, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/554196")] [Fact] public void XPathDocumentRoot() { var xmlFile = Temp.CreateFile(extension: ".xml"); var xmlFilePath = xmlFile.Path; xmlFile.WriteAllText(@"<?xml version=""1.0""?> <doc> <assembly> <name>Roslyn.Utilities</name> </assembly> <members> </members> </doc>"); var sourceTemplate = @" /// <include file=""{0}"" path=""/""/> enum A {{ }} /// <include file=""{0}"" path="".""/> enum B {{ }} /// <include file=""{0}"" path=""doc""/> enum C {{ }} /// <include file=""{0}"" path=""/doc""/> enum D {{ }} "; var comp = CreateCompilationUtil(string.Format(sourceTemplate, xmlFilePath)); var actual = GetDocumentationCommentText(comp, // (2,5): warning CS1589: Unable to include XML fragment '/' of file '012bf028d62c.xml' -- The XPath expression evaluated to unexpected type System.Xml.Linq.XDocument. // /// <include file="012bf028d62c.xml" path="/"/> Diagnostic(ErrorCode.WRN_FailedInclude, string.Format(@"<include file=""{0}"" path=""/""/>", xmlFilePath)).WithArguments(xmlFilePath, "/", "The XPath expression evaluated to unexpected type System.Xml.Linq.XDocument."), // (5,5): warning CS1589: Unable to include XML fragment '.' of file '012bf028d62c.xml' -- The XPath expression evaluated to unexpected type System.Xml.Linq.XDocument. // /// <include file="012bf028d62c.xml" path="."/> Diagnostic(ErrorCode.WRN_FailedInclude, string.Format(@"<include file=""{0}"" path="".""/>", xmlFilePath)).WithArguments(xmlFilePath, ".", "The XPath expression evaluated to unexpected type System.Xml.Linq.XDocument.")); var expected = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:A""> <!-- Failed to insert some or all of included XML --> </member> <member name=""T:B""> <!-- Failed to insert some or all of included XML --> </member> <member name=""T:C""> <doc> <assembly> <name>Roslyn.Utilities</name> </assembly> <members> </members> </doc> </member> <member name=""T:D""> <doc> <assembly> <name>Roslyn.Utilities</name> </assembly> <members> </members> </doc> </member> </members> </doc> ").Trim(); Assert.Equal(expected, actual); } #region Included crefs [Fact] public void IncludedCref_Valid() { var xmlFile = Temp.CreateFile(extension: ".xml").WriteAllText(@"<see cref=""Main""/>"); var xmlFilePath = xmlFile.Path; var includeElementTemplate = @"<include file='{0}' path='//see'/>"; var includeElement = string.Format(includeElementTemplate, xmlFilePath); var sourceTemplate = @" /// {0} class C {{ static void Main() {{ }} }} "; var comp = CreateCompilationUtil(string.Format(sourceTemplate, includeElement)); var actual = GetDocumentationCommentText(comp); var expected = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <see cref=""M:C.Main"" /> </member> </members> </doc> ").Trim(); Assert.Equal(expected, actual); } [Fact] public void IncludedCref_Verbatim() { var xmlFile = Temp.CreateFile(extension: ".xml").WriteAllText(@"<see cref=""M:Verbatim""/>"); var xmlFilePath = xmlFile.Path; var includeElementTemplate = @"<include file='{0}' path='//see'/>"; var includeElement = string.Format(includeElementTemplate, xmlFilePath); var sourceTemplate = @" /// {0} class C {{ static void Main() {{ }} }} "; var comp = CreateCompilationUtil(string.Format(sourceTemplate, includeElement)); var actual = GetDocumentationCommentText(comp); var expected = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <see cref=""M:Verbatim"" /> </member> </members> </doc> ").Trim(); Assert.Equal(expected, actual); } [Fact] public void IncludedCref_MultipleSyntaxTrees() { var xmlFile = Temp.CreateFile(extension: ".xml").WriteAllText(@"<see cref=""Int32""/>"); var xmlFilePath = xmlFile.Path; var includeElementTemplate = @"<include file='{0}' path='//see'/>"; var includeElement = string.Format(includeElementTemplate, xmlFilePath); var sourceTemplate = @" namespace N {{ /// {0} class C {{ }} }} namespace N {{ using System; /// {0} class C {{ }} }} "; var comp = CreateCompilationUtil(string.Format(sourceTemplate, includeElement)); // Error for the first include, but not for the second. var actual = GetDocumentationCommentText(comp, // (4,9): warning CS1574: XML comment has cref attribute 'Int32' that could not be resolved Diagnostic(ErrorCode.WRN_BadXMLRef, includeElement).WithArguments("Int32")); var expected = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:N.C""> <see cref=""!:Int32"" /> <see cref=""T:System.Int32"" /> </member> </members> </doc> ").Trim(); Assert.Equal(expected, actual); } [Fact] public void IncludedCref_SyntaxError() { var xmlFile = Temp.CreateFile(extension: ".xml").WriteAllText(@"<see cref=""#""/>"); var xmlFilePath = xmlFile.Path; var includeElementTemplate = @"<include file='{0}' path='//see'/>"; var includeElement = string.Format(includeElementTemplate, xmlFilePath); var sourceTemplate = @" /// {0} class C {{ }} "; var comp = CreateCompilationUtil(string.Format(sourceTemplate, includeElement)); var actual = GetDocumentationCommentText(comp, // (2,5): warning CS1584: XML comment has syntactically incorrect cref attribute '#' // /// <include file='aa671ee8adcd.xml' path='//see'/> Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, includeElement).WithArguments("#"), // (2,5): warning CS1658: Identifier expected. See also error CS1001. // /// <include file='aa671ee8adcd.xml' path='//see'/> Diagnostic(ErrorCode.WRN_ErrorOverride, includeElement).WithArguments("Identifier expected", "1001"), // (2,5): warning CS1658: Unexpected character '#'. See also error CS1056. // /// <include file='aa671ee8adcd.xml' path='//see'/> Diagnostic(ErrorCode.WRN_ErrorOverride, includeElement).WithArguments("Unexpected character '#'", "1056")); var expected = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <see cref=""!:#"" /> </member> </members> </doc> ").Trim(); Assert.Equal(expected, actual); } [Fact] public void IncludedCref_SemanticError() { var xmlFile = Temp.CreateFile(extension: ".xml").WriteAllText(@"<see cref=""Invalid""/>"); var xmlFilePath = xmlFile.Path; var includeElementTemplate = @"<include file='{0}' path='//see'/>"; var includeElement = string.Format(includeElementTemplate, xmlFilePath); var sourceTemplate = @" /// {0} class C {{ }} "; var comp = CreateCompilationUtil(string.Format(sourceTemplate, includeElement)); var actual = GetDocumentationCommentText(comp, // (2,5): warning CS1574: XML comment has cref attribute 'Invalid' that could not be resolved // /// <include file='f76ef125d03d.xml' path='//see'/> Diagnostic(ErrorCode.WRN_BadXMLRef, includeElement).WithArguments("Invalid")); var expected = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <see cref=""!:Invalid"" /> </member> </members> </doc> ").Trim(); Assert.Equal(expected, actual); } [WorkItem(552495, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552495")] [Fact] public void IncludeMismatchedQuotationMarks() { var source = @" /// <summary> /// <include file='C:\file.xml"" path=""/""/> /// </summary> class C { } "; // This is mode typically used by the IDE. var tree = Parse(source, options: TestOptions.Regular.WithDocumentationMode(DocumentationMode.Parse)); var compilation = CreateCompilation(tree); compilation.VerifyDiagnostics(); } [WorkItem(598371, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/598371")] [Fact] public void CrefParameterOrReturnTypeLookup1() { var seeElement = @"<see cref=""Y.implicit operator Y.Y""/>"; var xmlFile = Temp.CreateFile(extension: ".xml").WriteAllText(seeElement); var xmlFilePath = xmlFile.Path; var includeElementTemplate = @"<include file='{0}' path='//see'/>"; var includeElement = string.Format(includeElementTemplate, xmlFilePath); var sourceTemplate = @" class X {{ /// {0} /// {1} public class Y : X {{ public static implicit operator Y(int x) {{ return null; }} }} }} "; var comp = CreateCompilationUtil(string.Format(sourceTemplate, seeElement, includeElement)); var actual = GetDocumentationCommentText(comp); var expected = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:X.Y""> <see cref=""M:X.Y.op_Implicit(System.Int32)~X.Y"" /> <see cref=""M:X.Y.op_Implicit(System.Int32)~X.Y"" /> </member> </members> </doc> ").Trim(); Assert.Equal(expected, actual); } [WorkItem(586815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/586815")] [Fact] public void CrefParameterOrReturnTypeLookup2() { var seeElement = @"<see cref=""Foo(B)""/>"; var xmlFile = Temp.CreateFile(extension: ".xml").WriteAllText(seeElement); var xmlFilePath = xmlFile.Path; var includeElementTemplate = @"<include file='{0}' path='//see'/>"; var includeElement = string.Format(includeElementTemplate, xmlFilePath); var sourceTemplate = @" class A<T> {{ class B : A<B> {{ /// {0} /// {1} void Foo(B x) {{ }} }} }} "; var comp = CreateCompilationUtil(string.Format(sourceTemplate, seeElement, includeElement)); var actual = GetDocumentationCommentText(comp); var expected = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""M:A`1.B.Foo(A{A{`0}.B}.B)""> <see cref=""M:A`1.B.Foo(A{A{`0}.B}.B)"" /> <see cref=""M:A`1.B.Foo(A{A{`0}.B}.B)"" /> </member> </members> </doc> ").Trim(); Assert.Equal(expected, actual); } #endregion Included crefs #region Included names [Fact] public void IncludedName_Success() { var xml = @" <root> <member0> <summary> <typeparam name=""T"">Text</typeparam> <typeparamref name=""T"">Text</typeparamref> </summary> </member0> <member1> <summary> <param name=""x"">Text</param> <paramref name=""x"">Text</paramref> </summary> </member1> <member2> <summary> <param name=""u"">Text</param> <paramref name=""u"">Text</paramref> <typeparam name=""U"">Text</typeparam> <typeparamref name=""U"">Text</typeparamref> </summary> </member2> <member3> <summary> <param name=""v"">Text</param> <paramref name=""v"">Text</paramref> <typeparam name=""V"">Text</typeparam> <typeparamref name=""V"">Text</typeparamref> </summary> </member3> </root> "; var xmlFile = Temp.CreateFile(extension: ".xml").WriteAllText(xml); var xmlFilePath = xmlFile.Path; var includeElementTemplate = @"<include file='{0}' path='root/member{1}/summary'/>"; string[] includeElements = Enumerable.Range(0, 4).Select(i => string.Format(includeElementTemplate, xmlFilePath, i)).ToArray(); var sourceTemplate = @" /// {0} class C<T> {{ /// {1} int this[int x] {{ get {{ return 0; }} set {{ }} }} /// {2} void M<U>(U u) {{ }} /// {3} delegate void D<V>(V v) {{ }} }} "; var comp = CreateCompilationUtil(string.Format(sourceTemplate, includeElements)); var actual = GetDocumentationCommentText(comp); var expected = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C`1""> <summary> <typeparam name=""T"">Text</typeparam> <typeparamref name=""T"">Text</typeparamref> </summary> </member> <member name=""P:C`1.Item(System.Int32)""> <summary> <param name=""x"">Text</param> <paramref name=""x"">Text</paramref> </summary> </member> <member name=""M:C`1.M``1(``0)""> <summary> <param name=""u"">Text</param> <paramref name=""u"">Text</paramref> <typeparam name=""U"">Text</typeparam> <typeparamref name=""U"">Text</typeparamref> </summary> </member> <member name=""T:C`1.D`1""> <summary> <param name=""v"">Text</param> <paramref name=""v"">Text</paramref> <typeparam name=""V"">Text</typeparam> <typeparamref name=""V"">Text</typeparamref> </summary> </member> </members> </doc> ").Trim(); Assert.Equal(expected, actual); } [Fact] public void IncludedName_OverlappedWithSource() { var xml = @" <root> <param name=""u"">Text</param> <param name=""v"">Text</param> <paramref name=""u"">Text</paramref> <paramref name=""v"">Text</paramref> <typeparam name=""U"">Text</typeparam> <typeparam name=""V"">Text</typeparam> <typeparamref name=""U"">Text</typeparamref> <typeparamref name=""V"">Text</typeparamref> </root> "; var xmlFile = Temp.CreateFile(extension: ".xml").WriteAllText(xml); var xmlFilePath = xmlFile.Path; var includeElementTemplate = @"<include file='{0}' path='root/*'/>"; string includeElement = string.Format(includeElementTemplate, xmlFilePath); var sourceTemplate = @" /// <param name=""u"">Text</param> /// <param name=""v"">Text</param> /// <paramref name=""u"">Text</paramref> /// <paramref name=""v"">Text</paramref> /// <typeparam name=""U"">Text</typeparam> /// <typeparam name=""V"">Text</typeparam> /// <typeparamref name=""U"">Text</typeparamref> /// <typeparamref name=""V"">Text</typeparamref> /// {0} delegate void D<U, V>(U u, V v); "; var comp = CreateCompilationUtil(string.Format(sourceTemplate, includeElement)); var actual = GetDocumentationCommentText(comp, // (10,5): warning CS1571: XML comment has a duplicate param tag for 'u' // /// <include file='f59a2ef50b4d.xml' path='root/*'/> Diagnostic(ErrorCode.WRN_DuplicateParamTag, includeElement).WithArguments("u"), // (10,5): warning CS1571: XML comment has a duplicate param tag for 'v' // /// <include file='f59a2ef50b4d.xml' path='root/*'/> Diagnostic(ErrorCode.WRN_DuplicateParamTag, includeElement).WithArguments("v"), // (10,5): warning CS1710: XML comment has a duplicate typeparam tag for 'U' // /// <include file='f59a2ef50b4d.xml' path='root/*'/> Diagnostic(ErrorCode.WRN_DuplicateTypeParamTag, includeElement).WithArguments("U"), // (10,5): warning CS1710: XML comment has a duplicate typeparam tag for 'V' // /// <include file='f59a2ef50b4d.xml' path='root/*'/> Diagnostic(ErrorCode.WRN_DuplicateTypeParamTag, includeElement).WithArguments("V")); var expected = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:D`2""> <param name=""u"">Text</param> <param name=""v"">Text</param> <paramref name=""u"">Text</paramref> <paramref name=""v"">Text</paramref> <typeparam name=""U"">Text</typeparam> <typeparam name=""V"">Text</typeparam> <typeparamref name=""U"">Text</typeparamref> <typeparamref name=""V"">Text</typeparamref> <param name=""u"">Text</param><param name=""v"">Text</param><paramref name=""u"">Text</paramref><paramref name=""v"">Text</paramref><typeparam name=""U"">Text</typeparam><typeparam name=""V"">Text</typeparam><typeparamref name=""U"">Text</typeparamref><typeparamref name=""V"">Text</typeparamref> </member> </members> </doc> ").Trim(); Assert.Equal(expected, actual); } [Fact] public void IncludedName_MixedWithSource() { var xml = @" <root> <param name=""v"">Text</param> <paramref name=""u"">Text</paramref> <paramref name=""v"">Text</paramref> <typeparam name=""V"">Text</typeparam> <typeparamref name=""U"">Text</typeparamref> <typeparamref name=""V"">Text</typeparamref> </root> "; var xmlFile = Temp.CreateFile(extension: ".xml").WriteAllText(xml); var xmlFilePath = xmlFile.Path; var includeElementTemplate = @"<include file='{0}' path='root/*'/>"; string includeElement = string.Format(includeElementTemplate, xmlFilePath); var sourceTemplate = @" /// <param name=""u"">Text</param> /// <paramref name=""u"">Text</paramref> /// <paramref name=""v"">Text</paramref> /// <typeparam name=""U"">Text</typeparam> /// <typeparamref name=""U"">Text</typeparamref> /// <typeparamref name=""V"">Text</typeparamref> /// {0} delegate void D<U, V>(U u, V v); "; var comp = CreateCompilationUtil(string.Format(sourceTemplate, includeElement)); var actual = GetDocumentationCommentText(comp); var expected = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:D`2""> <param name=""u"">Text</param> <paramref name=""u"">Text</paramref> <paramref name=""v"">Text</paramref> <typeparam name=""U"">Text</typeparam> <typeparamref name=""U"">Text</typeparamref> <typeparamref name=""V"">Text</typeparamref> <param name=""v"">Text</param><paramref name=""u"">Text</paramref><paramref name=""v"">Text</paramref><typeparam name=""V"">Text</typeparam><typeparamref name=""U"">Text</typeparamref><typeparamref name=""V"">Text</typeparamref> </member> </members> </doc> ").Trim(); Assert.Equal(expected, actual); } [Fact] public void IncludedName_SyntacticError() { var xmlFile = Temp.CreateFile(extension: ".xml").WriteAllText(@"<typeparam name=""#""/>"); var xmlFilePath = xmlFile.Path; var includeElementTemplate = @"<include file='{0}' path='//typeparam'/>"; var includeElement = string.Format(includeElementTemplate, xmlFilePath); var sourceTemplate = @" /// {0} class C<T> {{ }} "; var comp = CreateCompilationUtil(string.Format(sourceTemplate, includeElement)); var actual = GetDocumentationCommentText(comp, // (2,5): warning CS1658: Unexpected character '#'. See also error CS1056. // /// <include file='3d2052d10358.xml' path='//typeparam'/> Diagnostic(ErrorCode.WRN_ErrorOverride, includeElement).WithArguments("Unexpected character '#'", "1056"), // (3,9): warning CS1712: Type parameter 'T' has no matching typeparam tag in the XML comment on 'C<T>' (but other type parameters do) // class C<T> { } Diagnostic(ErrorCode.WRN_MissingTypeParamTag, "T").WithArguments("T", "C<T>")); var expected = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C`1""> <typeparam name=""#"" /> </member> </members> </doc> ").Trim(); Assert.Equal(expected, actual); } [Fact] public void IncludedName_SemanticError() { var xmlFile = Temp.CreateFile(extension: ".xml").WriteAllText(@"<param name=""Q""/>"); var xmlFilePath = xmlFile.Path; var includeElementTemplate = @"<include file='{0}' path='//param'/>"; var includeElement = string.Format(includeElementTemplate, xmlFilePath); var sourceTemplate = @" class C {{ /// {0} void M(int x) {{ }} }} "; var comp = CreateCompilationUtil(string.Format(sourceTemplate, includeElement)); var actual = GetDocumentationCommentText(comp, // (4,9): warning CS1572: XML comment has a param tag for 'Q', but there is no parameter by that name // /// <include file='4f57d3a0db53.xml' path='//param'/> Diagnostic(ErrorCode.WRN_UnmatchedParamTag, includeElement).WithArguments("Q"), // (5,16): warning CS1573: Parameter 'x' has no matching param tag in the XML comment for 'C.M(int)' (but other parameters do) // void M(int x) { } Diagnostic(ErrorCode.WRN_MissingParamTag, "x").WithArguments("x", "C.M(int)")); var expected = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""M:C.M(System.Int32)""> <param name=""Q"" /> </member> </members> </doc> ").Trim(); Assert.Equal(expected, actual); } [Fact] public void IncludedName_DuplicateParameterName() { var xmlFile = Temp.CreateFile(extension: ".xml").WriteAllText(@"<param name=""x""/>"); var xmlFilePath = xmlFile.Path; var includeElementTemplate = @"<include file='{0}' path='//param'/>"; var includeElement = string.Format(includeElementTemplate, xmlFilePath); var sourceTemplate = @" class C {{ /// {0} void M(int x, int x) {{ }} }} "; var comp = CreateCompilationUtil(string.Format(sourceTemplate, includeElement)); // NOTE: no *xml* diagnostics, not no diagnostics. var actual = GetDocumentationCommentText(comp); var expected = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""M:C.M(System.Int32,System.Int32)""> <param name=""x"" /> </member> </members> </doc> ").Trim(); Assert.Equal(expected, actual); } [ClrOnlyFact(ClrOnlyReason.DocumentationComment, Skip = "https://github.com/dotnet/roslyn/issues/8807")] public void IncludedName_DuplicateNameAttribute() { var xmlFile = Temp.CreateFile(extension: ".xml").WriteAllText(@"<param name=""x"" name=""y""/>"); var xmlFilePath = xmlFile.Path; var includeElementTemplate = @"<include file='{0}' path='//param'/>"; var includeElement = string.Format(includeElementTemplate, xmlFilePath); var sourceTemplate = @" class C {{ /// {0} void M(int x, int y) {{ }} }} "; var comp = CreateCompilationUtil(string.Format(sourceTemplate, includeElement)); var actual = GetDocumentationCommentText(comp, // df33b60df5a9.xml(1,17): warning CS1592: Badly formed XML in included comments file -- ''name' is a duplicate attribute name.' Diagnostic(ErrorCode.WRN_XMLParseIncludeError).WithArguments("'name' is a duplicate attribute name.")); var expectedTemplate = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""M:C.M(System.Int32,System.Int32)""> <!-- Badly formed XML file ""{0}"" cannot be included --> </member> </members> </doc> ").Trim(); Assert.Equal(string.Format(expectedTemplate, TestHelpers.AsXmlCommentText(xmlFilePath)), actual); } [Fact] public void IncludedName_PartialMethod() { string xml = @" <root> <param name=""x""/> <param name=""y""/> </root>"; var xmlFile = Temp.CreateFile(extension: ".xml").WriteAllText(xml); var xmlFilePath = xmlFile.Path; var includeElementTemplate = @"<include file='{0}' path='//param'/>"; var includeElement = string.Format(includeElementTemplate, xmlFilePath); var sourceTemplate = @" partial class C {{ /// Part 1. /// {0} partial void M(int x, int y); }} partial class C {{ /// Part 2. /// {0} partial void M(int x, int y) {{ }} }} "; var comp = CreateCompilationUtil(string.Format(sourceTemplate, includeElement)); var actual = GetDocumentationCommentText(comp); var expectedTemplate = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""M:C.M(System.Int32,System.Int32)""> Part 2. <param name=""x"" /><param name=""y"" /> </member> </members> </doc> ").Trim(); Assert.Equal(string.Format(expectedTemplate, TestHelpers.AsXmlCommentText(xmlFilePath)), actual); } [Fact] [WorkItem(21348, "https://github.com/dotnet/roslyn/issues/21348")] public void IncludedName_TypeParamAndTypeParamRefHandling() { var xml = @" <root> <target> Included section <summary> See <typeparam/>. See <typeparam name=""X""/>. See <typeparam name=""Y""/>. See <typeparam name=""XY""/>. </summary> <remarks></remarks> </target> <target> Included section <summary> See <typeparamref/>. See <typeparamref name=""X""/>. See <typeparamref name=""Y""/>. See <typeparamref name=""XY""/>. </summary> <remarks></remarks> </target> </root> "; var xmlFile = Temp.CreateFile(extension: ".xml").WriteAllText(xml); var xmlFilePath = xmlFile.Path; var includeElementTemplate = @"<include file='{0}' path='//target'/>"; string includeElement = string.Format(includeElementTemplate, xmlFilePath); var sourceTemplate = @" /// {0} class OuterClass<X> {{ /// {0} class InnerClass<Y> {{ /// {0} public void Foo() {{}} }} }} "; var comp = CreateCompilationUtil(string.Format(sourceTemplate, includeElement)); var actual = GetDocumentationCommentText(comp, expectedDiagnostics: new[] { // (3,5): warning CS1711: XML comment has a typeparam tag for 'Y', but there is no type parameter by that name // /// <include file='b16c2dc7f738.xml' path='//target'/> Diagnostic(ErrorCode.WRN_UnmatchedTypeParamTag, includeElement).WithArguments("Y").WithLocation(3, 5), // (3,5): warning CS1711: XML comment has a typeparam tag for 'XY', but there is no type parameter by that name // /// <include file='b16c2dc7f738.xml' path='//target'/> Diagnostic(ErrorCode.WRN_UnmatchedTypeParamTag, includeElement).WithArguments("XY").WithLocation(3, 5), // (3,5): warning CS1735: XML comment on 'OuterClass<X>' has a typeparamref tag for 'Y', but there is no type parameter by that name // /// <include file='b16c2dc7f738.xml' path='//target'/> Diagnostic(ErrorCode.WRN_UnmatchedTypeParamRefTag, includeElement).WithArguments("Y", "OuterClass<X>").WithLocation(3, 5), // (3,5): warning CS1735: XML comment on 'OuterClass<X>' has a typeparamref tag for 'XY', but there is no type parameter by that name // /// <include file='b16c2dc7f738.xml' path='//target'/> Diagnostic(ErrorCode.WRN_UnmatchedTypeParamRefTag, includeElement).WithArguments("XY", "OuterClass<X>").WithLocation(3, 5), // (6,9): warning CS1711: XML comment has a typeparam tag for 'X', but there is no type parameter by that name // /// <include file='b16c2dc7f738.xml' path='//target'/> Diagnostic(ErrorCode.WRN_UnmatchedTypeParamTag, includeElement).WithArguments("X").WithLocation(6, 9), // (6,9): warning CS1711: XML comment has a typeparam tag for 'XY', but there is no type parameter by that name // /// <include file='b16c2dc7f738.xml' path='//target'/> Diagnostic(ErrorCode.WRN_UnmatchedTypeParamTag, includeElement).WithArguments("XY").WithLocation(6, 9), // (6,9): warning CS1735: XML comment on 'OuterClass<X>.InnerClass<Y>' has a typeparamref tag for 'XY', but there is no type parameter by that name // /// <include file='b16c2dc7f738.xml' path='//target'/> Diagnostic(ErrorCode.WRN_UnmatchedTypeParamRefTag, includeElement).WithArguments("XY", "OuterClass<X>.InnerClass<Y>").WithLocation(6, 9), // (9,13): warning CS1711: XML comment has a typeparam tag for 'X', but there is no type parameter by that name // /// <include file='b16c2dc7f738.xml' path='//target'/> Diagnostic(ErrorCode.WRN_UnmatchedTypeParamTag, includeElement).WithArguments("X").WithLocation(9, 13), // (9,13): warning CS1711: XML comment has a typeparam tag for 'Y', but there is no type parameter by that name // /// <include file='b16c2dc7f738.xml' path='//target'/> Diagnostic(ErrorCode.WRN_UnmatchedTypeParamTag, includeElement).WithArguments("Y").WithLocation(9, 13), // (9,13): warning CS1711: XML comment has a typeparam tag for 'XY', but there is no type parameter by that name // /// <include file='b16c2dc7f738.xml' path='//target'/> Diagnostic(ErrorCode.WRN_UnmatchedTypeParamTag, includeElement).WithArguments("XY").WithLocation(9, 13), // (9,13): warning CS1735: XML comment on 'OuterClass<X>.InnerClass<Y>.Foo()' has a typeparamref tag for 'XY', but there is no type parameter by that name // /// <include file='b16c2dc7f738.xml' path='//target'/> Diagnostic(ErrorCode.WRN_UnmatchedTypeParamRefTag, includeElement).WithArguments("XY", "OuterClass<X>.InnerClass<Y>.Foo()").WithLocation(9, 13) }); var expected = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:OuterClass`1""> <target> Included section <summary> See <typeparam />. See <typeparam name=""X"" />. See <typeparam name=""Y"" />. See <typeparam name=""XY"" />. </summary> <remarks /> </target><target> Included section <summary> See <typeparamref />. See <typeparamref name=""X"" />. See <typeparamref name=""Y"" />. See <typeparamref name=""XY"" />. </summary> <remarks /> </target> </member> <member name=""T:OuterClass`1.InnerClass`1""> <target> Included section <summary> See <typeparam />. See <typeparam name=""X"" />. See <typeparam name=""Y"" />. See <typeparam name=""XY"" />. </summary> <remarks /> </target><target> Included section <summary> See <typeparamref />. See <typeparamref name=""X"" />. See <typeparamref name=""Y"" />. See <typeparamref name=""XY"" />. </summary> <remarks /> </target> </member> <member name=""M:OuterClass`1.InnerClass`1.Foo""> <target> Included section <summary> See <typeparam />. See <typeparam name=""X"" />. See <typeparam name=""Y"" />. See <typeparam name=""XY"" />. </summary> <remarks /> </target><target> Included section <summary> See <typeparamref />. See <typeparamref name=""X"" />. See <typeparamref name=""Y"" />. See <typeparamref name=""XY"" />. </summary> <remarks /> </target> </member> </members> </doc> ").Trim(); Assert.Equal(expected, actual); } #endregion Included names #endregion Include #region For single symbol [Fact] public void ForSingleType() { var source = @" /// <summary> /// A /// B /// C /// </summary> class C { } "; var compilation = CreateCompilationUtil(source); var type = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var actualText = DocumentationCommentCompiler.GetDocumentationCommentXml(type, processIncludes: true, cancellationToken: default(CancellationToken)); var expectedText = @"<member name=""T:C""> <summary> A B C </summary> </member> "; Assert.Equal(expectedText, actualText); } [Fact] public void ForSingleTypeWithInclude() { var xmlFile = Temp.CreateFile(extension: ".xml").WriteAllText("<stuff />"); var xmlFilePath = xmlFile.Path; var sourceTemplate = @" /// <summary> /// A /// <include file='{0}' path='stuff'/> /// C /// </summary> class C {{ /// Shouldn't appear in doc comment for C. void M(){{}} }} "; var source = string.Format(sourceTemplate, xmlFilePath); var compilation = CreateCompilationUtil(source); var type = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); // Expand includes. { var actualText = DocumentationCommentCompiler.GetDocumentationCommentXml(type, processIncludes: true, cancellationToken: default(CancellationToken)); var expectedText = @"<member name=""T:C""> <summary> A <stuff /> C </summary> </member> "; Assert.Equal(expectedText, actualText); } // Do not expand includes. { var actualText = DocumentationCommentCompiler.GetDocumentationCommentXml(type, processIncludes: false, cancellationToken: default(CancellationToken)); var expectedTextTemplate = @"<member name=""T:C""> <summary> A <include file='{0}' path='stuff'/> C </summary> </member> "; Assert.Equal(string.Format(expectedTextTemplate, xmlFilePath), actualText); } } #endregion #region Misc [Fact] public void FilterTree() { var source1 = @" partial class C { /// <see cref=""Bogus1""/> void M1() { } } "; var source2 = @" partial class C { /// <see cref=""Bogus2""/> void M2() { } } "; var tree1 = SyntaxFactory.ParseSyntaxTree(source1, options: TestOptions.RegularWithDocumentationComments); var tree2 = SyntaxFactory.ParseSyntaxTree(source2, options: TestOptions.RegularWithDocumentationComments); // Files passed in order. var comp = CreateCompilation(new[] { tree1, tree2 }, assemblyName: "Test"); var actual1 = GetDocumentationCommentText(comp, null, filterTree: tree1, expectedDiagnostics: new[] { // (4,20): warning CS1574: XML comment has cref attribute 'Bogus1' that could not be resolved // /// <see cref="Bogus1"/> Diagnostic(ErrorCode.WRN_BadXMLRef, "Bogus1").WithArguments("Bogus1") }); var expected1 = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""M:C.M1""> <see cref=""!:Bogus1""/> </member> </members> </doc> ".Trim(); Assert.Equal(expected1, actual1); var actual2 = GetDocumentationCommentText(comp, null, filterTree: tree2, expectedDiagnostics: new[] { // (4,20): warning CS1574: XML comment has cref attribute 'Bogus2' that could not be resolved // /// <see cref="Bogus2"/> Diagnostic(ErrorCode.WRN_BadXMLRef, "Bogus2").WithArguments("Bogus2")}); var expected2 = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""M:C.M2""> <see cref=""!:Bogus2""/> </member> </members> </doc> ".Trim(); Assert.Equal(expected2, actual2); } [Fact] public void Utf8() { // NOTE: This character is interesting because it has a three-byte utf-8 representation. var source = "///\u20ac" + @" public class C { static void Main() {} } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp, "OutputName"); var expected = (@" <?xml version=""1.0""?> <doc> <assembly> <name>OutputName</name> </assembly> <members> <member name=""T:C""> " + "\u20ac" + @" </member> </members> </doc> ").Trim(); Assert.Equal(expected, actual); } [Fact, WorkItem(921838, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/921838")] public void InaccessibleMembers() { var source = @"/// <summary> /// See <see cref=""C.M""/>. /// </summary> class A { } class C { private void M() { } }"; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp, "OutputName"); var expected = (@" <?xml version=""1.0""?> <doc> <assembly> <name>OutputName</name> </assembly> <members> <member name=""T:A""> <summary> See <see cref=""M:C.M""/>. </summary> </member> </members> </doc>").Trim(); Assert.Equal(expected, actual); } [WorkItem(531144, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531144")] [Fact] public void NamespaceCref() { var source = @" /// <see cref=""System""/> public class C { static void Main() {} } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp); var expected = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <see cref=""N:System""/> </member> </members> </doc> ").Trim(); Assert.Equal(expected, actual); } [WorkItem(531144, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531144")] [Fact] public void SymbolKinds() { var source = @" using AliasN = System; using AliasT = System.String; class Generic<T> { /// <summary> /// Namespace alias <see cref=""AliasN""/> /// Type alias <see cref=""AliasT""/> /// Array type <see cref=""C[]""/> -- warning /// There's no way to get a cref to bind to an assembly. /// Dynamic type <see cref=""dynamic""/> -- warning /// Error type <see cref=""C{T}""/> -- warning /// Event <see cref=""E""/> /// Field <see cref=""f""/> /// There's no way to get a cref to bind to a label. /// There's no way to get a cref to bind to a local. /// Method <see cref=""M""/> /// There's no way to get a cref to bind to a net module. /// Named type <see cref=""C""/> /// Namespace <see cref=""System""/> /// There's no way to get a cref to bind to a parameter. /// Pointer type <see cref=""C*""/> -- warning /// Property <see cref=""P""/> /// There's no way to get a cref to bind to a range variable. /// Type parameter <see cref=""T""/> -- warning /// </summary> public class C { int f; event System.Action E; int P { get; set; } void M() {} } } "; var comp = CreateCompilationUtil(source); comp.VerifyDiagnostics( // Cref parse warnings. // (10,31): warning CS1584: XML comment has syntactically incorrect cref attribute 'C[]' // /// Array type <see cref="C[]"/> -- warning Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "C").WithArguments("C[]"), // (23,33): warning CS1584: XML comment has syntactically incorrect cref attribute 'C*' // /// Pointer type <see cref="C*"/> -- warning Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "C").WithArguments("C*"), // Boring warnings. // (31,29): warning CS0067: The event 'Generic<T>.C.E' is never used // event System.Action E; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("Generic<T>.C.E"), // (30,13): warning CS0169: The field 'Generic<T>.C.f' is never used // int f; Diagnostic(ErrorCode.WRN_UnreferencedField, "f").WithArguments("Generic<T>.C.f"), // Cref binding warnings. // (12,33): warning CS1574: XML comment has cref attribute 'dynamic' that could not be resolved // /// Dynamic type <see cref="dynamic"/> -- warning Diagnostic(ErrorCode.WRN_BadXMLRef, "dynamic").WithArguments("dynamic"), // (13,31): warning CS1574: XML comment has cref attribute 'C{T}' that could not be resolved // /// Error type <see cref="C{T}"/> -- warning Diagnostic(ErrorCode.WRN_BadXMLRef, "C{T}").WithArguments("C{T}"), // (26,35): warning CS1723: XML comment has cref attribute 'T' that refers to a type parameter // /// Type parameter <see cref="T"/> -- warning Diagnostic(ErrorCode.WRN_BadXMLRefTypeVar, "T").WithArguments("T")); var actual = GetDocumentationCommentText(comp, // (12,33): warning CS1574: XML comment has cref attribute 'dynamic' that could not be resolved // /// Dynamic type <see cref="dynamic"/> -- warning Diagnostic(ErrorCode.WRN_BadXMLRef, "dynamic").WithArguments("dynamic"), // (13,31): warning CS1574: XML comment has cref attribute 'C{T}' that could not be resolved // /// Error type <see cref="C{T}"/> -- warning Diagnostic(ErrorCode.WRN_BadXMLRef, "C{T}").WithArguments("C{T}"), // (26,35): warning CS1723: XML comment has cref attribute 'T' that refers to a type parameter // /// Type parameter <see cref="T"/> -- warning Diagnostic(ErrorCode.WRN_BadXMLRefTypeVar, "T").WithArguments("T")); var expected = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:Generic`1.C""> <summary> Namespace alias <see cref=""N:System""/> Type alias <see cref=""T:System.String""/> Array type <see cref=""!:C[]""/> -- warning There's no way to get a cref to bind to an assembly. Dynamic type <see cref=""!:dynamic""/> -- warning Error type <see cref=""!:C&lt;T&gt;""/> -- warning Event <see cref=""E:Generic`1.C.E""/> Field <see cref=""F:Generic`1.C.f""/> There's no way to get a cref to bind to a label. There's no way to get a cref to bind to a local. Method <see cref=""M:Generic`1.C.M""/> There's no way to get a cref to bind to a net module. Named type <see cref=""T:Generic`1.C""/> Namespace <see cref=""N:System""/> There's no way to get a cref to bind to a parameter. Pointer type <see cref=""!:C*""/> -- warning Property <see cref=""P:Generic`1.C.P""/> There's no way to get a cref to bind to a range variable. Type parameter <see cref=""!:T""/> -- warning </summary> </member> </members> </doc> ").Trim(); Assert.Equal(expected, actual); } [WorkItem(530695, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530695")] [Fact] public void FieldDocComment() { var source = @" class C { /// 1 int f; /// 2 int g, h; /// 3 event System.Action p; /// 4 event System.Action q, r; } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp); var expected = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""F:C.f""> 1 </member> <member name=""F:C.g""> 2 </member> <member name=""F:C.h""> 2 </member> <member name=""E:C.p""> 3 </member> <member name=""E:C.q""> 4 </member> <member name=""E:C.r""> 4 </member> </members> </doc> ").Trim(); Assert.Equal(expected, actual); } [WorkItem(530695, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530695")] [Fact] public void FieldDocCommentDiagnostics() { var source = @" class C { /// <see cref=""fake1""/> int f; /// <see cref=""fake2""/> int g, h; /// <see cref=""fake3""/> event System.Action p; /// <see cref=""fake4""/> event System.Action q, r; } "; // Duplicate diagnostics, as in dev11. var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp, // (4,20): warning CS1574: XML comment has cref attribute 'fake1' that could not be resolved // /// <see cref="fake1"/> Diagnostic(ErrorCode.WRN_BadXMLRef, "fake1").WithArguments("fake1"), // (6,20): warning CS1574: XML comment has cref attribute 'fake2' that could not be resolved // /// <see cref="fake2"/> Diagnostic(ErrorCode.WRN_BadXMLRef, "fake2").WithArguments("fake2"), // (6,20): warning CS1574: XML comment has cref attribute 'fake2' that could not be resolved // /// <see cref="fake2"/> Diagnostic(ErrorCode.WRN_BadXMLRef, "fake2").WithArguments("fake2"), // (9,20): warning CS1574: XML comment has cref attribute 'fake3' that could not be resolved // /// <see cref="fake3"/> Diagnostic(ErrorCode.WRN_BadXMLRef, "fake3").WithArguments("fake3"), // (11,20): warning CS1574: XML comment has cref attribute 'fake4' that could not be resolved // /// <see cref="fake4"/> Diagnostic(ErrorCode.WRN_BadXMLRef, "fake4").WithArguments("fake4"), // (11,20): warning CS1574: XML comment has cref attribute 'fake4' that could not be resolved // /// <see cref="fake4"/> Diagnostic(ErrorCode.WRN_BadXMLRef, "fake4").WithArguments("fake4")); var expected = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""F:C.f""> <see cref=""!:fake1""/> </member> <member name=""F:C.g""> <see cref=""!:fake2""/> </member> <member name=""F:C.h""> <see cref=""!:fake2""/> </member> <member name=""E:C.p""> <see cref=""!:fake3""/> </member> <member name=""E:C.q""> <see cref=""!:fake4""/> </member> <member name=""E:C.r""> <see cref=""!:fake4""/> </member> </members> </doc> ").Trim(); Assert.Equal(expected, actual); } [WorkItem(531187, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531187")] [Fact] public void DelegateDocComments() { var source = @" /// <param name=""t""/> /// <param name=""q""/> /// <paramref name=""t""/> /// <paramref name=""q""/> /// <typeparam name=""T""/> /// <typeparam name=""Q""/> /// <typeparamref name=""T""/> /// <typeparamref name=""Q""/> delegate void D<T, U>(T t, U u); "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp, // (3,18): warning CS1572: XML comment has a param tag for 'q', but there is no parameter by that name // /// <param name="q"/> Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "q").WithArguments("q"), // (5,21): warning CS1734: XML comment on 'D<T, U>' has a paramref tag for 'q', but there is no parameter by that name // /// <paramref name="q"/> Diagnostic(ErrorCode.WRN_UnmatchedParamRefTag, "q").WithArguments("q", "D<T, U>"), // (7,22): warning CS1711: XML comment has a typeparam tag for 'Q', but there is no type parameter by that name // /// <typeparam name="Q"/> Diagnostic(ErrorCode.WRN_UnmatchedTypeParamTag, "Q").WithArguments("Q"), // (9,25): warning CS1735: XML comment on 'D<T, U>' has a typeparamref tag for 'Q', but there is no type parameter by that name // /// <typeparamref name="Q"/> Diagnostic(ErrorCode.WRN_UnmatchedTypeParamRefTag, "Q").WithArguments("Q", "D<T, U>"), // (10,30): warning CS1573: Parameter 'u' has no matching param tag in the XML comment for 'D<T, U>' (but other parameters do) // delegate void D<T, U>(T t, U u); Diagnostic(ErrorCode.WRN_MissingParamTag, "u").WithArguments("u", "D<T, U>"), // (10,20): warning CS1712: Type parameter 'U' has no matching typeparam tag in the XML comment on 'D<T, U>' (but other type parameters do) // delegate void D<T, U>(T t, U u); Diagnostic(ErrorCode.WRN_MissingTypeParamTag, "U").WithArguments("U", "D<T, U>")); var expected = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:D`2""> <param name=""t""/> <param name=""q""/> <paramref name=""t""/> <paramref name=""q""/> <typeparam name=""T""/> <typeparam name=""Q""/> <typeparamref name=""T""/> <typeparamref name=""Q""/> </member> </members> </doc> ").Trim(); Assert.Equal(expected, actual); } [Fact] public void NoWarn1591() { var source = @" public class C { } "; var tree = Parse(source, options: TestOptions.RegularWithDocumentationComments); var warnDict = new Dictionary<string, ReportDiagnostic> { { MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_MissingXMLComment), ReportDiagnostic.Suppress } }; var comp = CreateCompilation(tree, options: TestOptions.ReleaseDll.WithSpecificDiagnosticOptions(warnDict), assemblyName: "Test"); comp.VerifyDiagnostics(); //NOTE: no WRN_MissingXMLComment var actual = GetDocumentationCommentText(comp, // (2,14): warning CS1591: Missing XML comment for publicly visible type or member 'C' // public class C { } Diagnostic(ErrorCode.WRN_MissingXMLComment, "C").WithArguments("C")); //Filtering happens later. var expected = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> </members> </doc> ").Trim(); Assert.Equal(expected, actual); } [WorkItem(531233, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531233")] [Fact] public void CrefAttributeInOtherElement() { var source = @" class C { /// <other cref=""C""/> void M() { } } "; var comp = CreateCompilationUtil(source); comp.VerifyDiagnostics(); var actual = GetDocumentationCommentText(comp); var expected = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""M:C.M""> <other cref=""T:C""/> </member> </members> </doc> ").Trim(); Assert.Equal(expected, actual); } [WorkItem(531233, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531233")] [Fact] public void NameAttributeInOtherElement() { var source = @" class C { /// <other name=""X""/> void M() { } } "; var comp = CreateCompilationUtil(source); comp.VerifyDiagnostics(); var actual = GetDocumentationCommentText(comp); var expected = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""M:C.M""> <other name=""X""/> </member> </members> </doc> ").Trim(); Assert.Equal(expected, actual); } [Fact] public void GetParseDiagnostics() { var source = @" class Program { /// <summary> /// static void Main(string[] args) { } }"; var comp = CreateCompilationUtil(source); Assert.NotEmpty(comp.GetParseDiagnostics()); Assert.Empty(comp.GetDeclarationDiagnostics()); Assert.Empty(comp.GetMethodBodyDiagnostics()); Assert.NotEmpty(comp.GetDiagnostics()); } [WorkItem(531349, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531349")] [Fact] public void GetDeclarationDiagnostics() { var source = @" class Program { /// <summary> /// /// </summary> /// <param name=""a""></param> static void Main(string[] args) { } }"; var comp = CreateCompilationUtil(source); Assert.Empty(comp.GetParseDiagnostics()); Assert.Empty(comp.GetDeclarationDiagnostics()); Assert.Equal(2, comp.GetMethodBodyDiagnostics().Count()); Assert.Equal(2, comp.GetDiagnostics().Count()); } [WorkItem(531409, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531409")] [Fact] public void ExplicitInterfaceImplementation() { var source = @" interface I<T> { void M(); } class C<T> : I<T> { /// <see cref=""object""/> void I<T>.M() { } } "; var comp = CreateCompilationUtil(source); comp.VerifyDiagnostics(); var actual = GetDocumentationCommentText(comp); var expected = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""M:C`1.I{T}#M""> <see cref=""T:System.Object""/> </member> </members> </doc> ").Trim(); Assert.Equal(expected, actual); } [Fact] public void ArrayRankSpecifierOrder() { var source = @" class C { /// <see cref=""M""/> int[][,] M(int[,][] x) { return null; } } "; var comp = CreateCompilationUtil(source); comp.VerifyDiagnostics(); var actual = GetDocumentationCommentText(comp); var expected = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""M:C.M(System.Int32[][0:,0:])""> <see cref=""M:C.M(System.Int32[][0:,0:])""/> </member> </members> </doc> ").Trim(); Assert.Equal(expected, actual); } // As in dev11, the pragma has no effect. [ClrOnlyFact(ClrOnlyReason.DocumentationComment, Skip = "https://github.com/dotnet/roslyn/issues/8807")] public void PragmaDisableWarningInXmlFile() { var xmlFile = Temp.CreateFile(extension: ".xml").WriteAllText("&"); var sourceTemplate = @" #pragma warning disable 1592 /// <include file='{0}' path='element'/> class C {{ }} "; var comp = CreateCompilationUtil(string.Format(sourceTemplate, xmlFile.Path)); var actual = GetDocumentationCommentText(comp, // 054c2dcb7959.xml(1,1): warning CS1592: Badly formed XML in included comments file -- 'Data at the root level is invalid.' Diagnostic(ErrorCode.WRN_XMLParseIncludeError).WithArguments("Data at the root level is invalid.")); var expectedTemplate = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <!-- Badly formed XML file ""{0}"" cannot be included --> </member> </members> </doc> ").Trim(); Assert.Equal(string.Format(expectedTemplate, TestHelpers.AsXmlCommentText(xmlFile.Path)), actual); } [Fact] public void DynamicInParameters() { // BREAK: Dev11 drops candidates with "dynamic" anywhere in their parameter lists. // As a result, it does not match the first two or last two crefs. var source = @" /// <see cref=""M1(dynamic)""/> /// <see cref=""M1(C{dynamic})""/> /// <see cref=""M2(object)""/> /// <see cref=""M2(C{object})""/> /// /// <see cref=""M1(object)""/> /// <see cref=""M1(C{object})""/> /// <see cref=""M2(dynamic)""/> /// <see cref=""M2(C{dynamic})""/> class C<T> { void M1(dynamic p) { } void M1(C<dynamic> p) { } void M2(object p) { } void M2(C<object> p) { } } "; SyntaxTree tree = Parse(source, options: TestOptions.RegularWithDocumentationComments); var comp = CreateCompilationWithMscorlib40AndSystemCore(new[] { tree }, assemblyName: "Test"); var actualText = GetDocumentationCommentText(comp); var expectedText = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C`1""> <see cref=""M:C`1.M1(System.Object)""/> <see cref=""M:C`1.M1(C{System.Object})""/> <see cref=""M:C`1.M2(System.Object)""/> <see cref=""M:C`1.M2(C{System.Object})""/> <see cref=""M:C`1.M1(System.Object)""/> <see cref=""M:C`1.M1(C{System.Object})""/> <see cref=""M:C`1.M2(System.Object)""/> <see cref=""M:C`1.M2(C{System.Object})""/> </member> </members> </doc>".Trim(); Assert.Equal(expectedText, actualText); } [WorkItem(546989, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546989")] [Fact] public void GenericMethodWithoutTypeParameters1() { var source = @" /// <see cref=""M""/> /// <see cref=""M(int)""/> /// <see cref=""M{T}""/> /// <see cref=""M{T}(int)""/> /// /// <see cref=""C.M""/> /// <see cref=""C.M(int)""/> /// <see cref=""C.M{T}""/> /// <see cref=""C.M{T}(int)""/> class C { void M(int x) { } void M(string x) { } void M<T>(int x) { } void M<T>(string x) { } } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp, // (2,16): warning CS0419: Ambiguous reference in cref attribute: 'M'. Assuming 'C.M(int)', but could have also matched other overloads including 'C.M(string)'. // /// <see cref="M"/> Diagnostic(ErrorCode.WRN_AmbiguousXMLReference, "M").WithArguments("M", "C.M(int)", "C.M(string)"), // (4,16): warning CS0419: Ambiguous reference in cref attribute: 'M{T}'. Assuming 'C.M<T>(int)', but could have also matched other overloads including 'C.M<T>(string)'. // /// <see cref="M{T}"/> Diagnostic(ErrorCode.WRN_AmbiguousXMLReference, "M{T}").WithArguments("M{T}", "C.M<T>(int)", "C.M<T>(string)"), // (7,16): warning CS0419: Ambiguous reference in cref attribute: 'C.M'. Assuming 'C.M(int)', but could have also matched other overloads including 'C.M(string)'. // /// <see cref="C.M"/> Diagnostic(ErrorCode.WRN_AmbiguousXMLReference, "C.M").WithArguments("C.M", "C.M(int)", "C.M(string)"), // (9,16): warning CS0419: Ambiguous reference in cref attribute: 'C.M{T}'. Assuming 'C.M<T>(int)', but could have also matched other overloads including 'C.M<T>(string)'. // /// <see cref="C.M{T}"/> Diagnostic(ErrorCode.WRN_AmbiguousXMLReference, "C.M{T}").WithArguments("C.M{T}", "C.M<T>(int)", "C.M<T>(string)")); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <see cref=""M:C.M(System.Int32)""/> <see cref=""M:C.M(System.Int32)""/> <see cref=""M:C.M``1(System.Int32)""/> <see cref=""M:C.M``1(System.Int32)""/> <see cref=""M:C.M(System.Int32)""/> <see cref=""M:C.M(System.Int32)""/> <see cref=""M:C.M``1(System.Int32)""/> <see cref=""M:C.M``1(System.Int32)""/> </member> </members> </doc>".Trim(); Assert.Equal(expected, actual); } [WorkItem(546989, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546989")] [Fact] public void GenericMethodWithoutTypeParameters2() { var source = @" /// <see cref=""M""/> /// <see cref=""M(int)""/> /// <see cref=""M{T}""/> /// <see cref=""M{T}(int)""/> /// /// <see cref=""C.M""/> /// <see cref=""C.M(int)""/> /// <see cref=""C.M{T}""/> /// <see cref=""C.M{T}(int)""/> class C { void M<T>(int x) { } void M<T>(string x) { } void M<T, U>(int x) { } void M<T, U>(string x) { } } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp, // (2,16): warning CS0419: Ambiguous reference in cref attribute: 'M'. Assuming 'C.M<T>(int)', but could have also matched other overloads including 'C.M<T>(string)'. // /// <see cref="M"/> Diagnostic(ErrorCode.WRN_AmbiguousXMLReference, "M").WithArguments("M", "C.M<T>(int)", "C.M<T>(string)"), // (3,16): warning CS0419: Ambiguous reference in cref attribute: 'M(int)'. Assuming 'C.M<T>(int)', but could have also matched other overloads including 'C.M<T, U>(int)'. // /// <see cref="M(int)"/> Diagnostic(ErrorCode.WRN_AmbiguousXMLReference, "M(int)").WithArguments("M(int)", "C.M<T>(int)", "C.M<T, U>(int)"), // (4,16): warning CS0419: Ambiguous reference in cref attribute: 'M{T}'. Assuming 'C.M<T>(int)', but could have also matched other overloads including 'C.M<T>(string)'. // /// <see cref="M{T}"/> Diagnostic(ErrorCode.WRN_AmbiguousXMLReference, "M{T}").WithArguments("M{T}", "C.M<T>(int)", "C.M<T>(string)"), // (7,16): warning CS0419: Ambiguous reference in cref attribute: 'C.M'. Assuming 'C.M<T>(int)', but could have also matched other overloads including 'C.M<T>(string)'. // /// <see cref="C.M"/> Diagnostic(ErrorCode.WRN_AmbiguousXMLReference, "C.M").WithArguments("C.M", "C.M<T>(int)", "C.M<T>(string)"), // (8,16): warning CS0419: Ambiguous reference in cref attribute: 'C.M(int)'. Assuming 'C.M<T>(int)', but could have also matched other overloads including 'C.M<T, U>(int)'. // /// <see cref="C.M(int)"/> Diagnostic(ErrorCode.WRN_AmbiguousXMLReference, "C.M(int)").WithArguments("C.M(int)", "C.M<T>(int)", "C.M<T, U>(int)"), // (9,16): warning CS0419: Ambiguous reference in cref attribute: 'C.M{T}'. Assuming 'C.M<T>(int)', but could have also matched other overloads including 'C.M<T>(string)'. // /// <see cref="C.M{T}"/> Diagnostic(ErrorCode.WRN_AmbiguousXMLReference, "C.M{T}").WithArguments("C.M{T}", "C.M<T>(int)", "C.M<T>(string)")); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <see cref=""M:C.M``1(System.Int32)""/> <see cref=""M:C.M``1(System.Int32)""/> <see cref=""M:C.M``1(System.Int32)""/> <see cref=""M:C.M``1(System.Int32)""/> <see cref=""M:C.M``1(System.Int32)""/> <see cref=""M:C.M``1(System.Int32)""/> <see cref=""M:C.M``1(System.Int32)""/> <see cref=""M:C.M``1(System.Int32)""/> </member> </members> </doc>".Trim(); Assert.Equal(expected, actual); } [WorkItem(546989, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546989")] [Fact] public void GenericMethodWithoutTypeParameters3() { var source = @" /// <see cref=""M""/> /// <see cref=""M(int)""/> /// /// <see cref=""N""/> /// <see cref=""N(int)""/> class C { void M<T, U>(int x) { } void M<T>(int x) { } void M(int x) { } void N<T>(int x) { } void N(int x) { } void N(string x) { } } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp, // (5,16): warning CS0419: Ambiguous reference in cref attribute: 'N'. Assuming 'C.N(int)', but could have also matched other overloads including 'C.N(string)'. // /// <see cref="N"/> Diagnostic(ErrorCode.WRN_AmbiguousXMLReference, "N").WithArguments("N", "C.N(int)", "C.N(string)")); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <see cref=""M:C.M(System.Int32)""/> <see cref=""M:C.M(System.Int32)""/> <see cref=""M:C.N(System.Int32)""/> <see cref=""M:C.N(System.Int32)""/> </member> </members> </doc>".Trim(); Assert.Equal(expected, actual); } [WorkItem(547163, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547163")] [Fact] public void NestedGenericTypes() { var source = @" class A<TA1, TA2> { class B<TB1, TB2> { class C<TC1, TC2> { /// Comment void M<TM1, TM2>(TA1 a1, TA2 a2, TB1 b1, TB2 b2, TC1 c1, TC2 c2, TM1 m1, TM2 m2) { } } } } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""M:A`2.B`2.C`2.M``2(`0,`1,`2,`3,`4,`5,``0,``1)""> Comment </member> </members> </doc>".Trim(); Assert.Equal(expected, actual); } [Fact] public void WhitespaceAroundCref() { var source = @" /// <see cref="" A ""/> class A { } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:A""> <see cref=""T:A""/> </member> </members> </doc>".Trim(); Assert.Equal(expected, actual); } [Fact] public void TypeParamRef_ContainingType() { var source = @" class A<T> { class B { class C<U> { class D { /// <typeparamref name=""T"" /> /// <typeparamref name=""U"" /> /// <typeparamref name=""V"" /> class E<V> { } /// <typeparamref name=""T"" /> /// <typeparamref name=""U"" /> /// <typeparamref name=""V"" /> void M<V>() { } /// <typeparamref name=""T"" /> /// <typeparamref name=""U"" /> int P { get; set; } } } } } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:A`1.B.C`1.D.E`1""> <typeparamref name=""T"" /> <typeparamref name=""U"" /> <typeparamref name=""V"" /> </member> <member name=""M:A`1.B.C`1.D.M``1""> <typeparamref name=""T"" /> <typeparamref name=""U"" /> <typeparamref name=""V"" /> </member> <member name=""P:A`1.B.C`1.D.P""> <typeparamref name=""T"" /> <typeparamref name=""U"" /> </member> </members> </doc>".Trim(); Assert.Equal(expected, actual); } [WorkItem(527260, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527260")] [Fact] public void IllegalXmlCharacter() { var source = @" /// <" + "\u037F" + @"/> class A { } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <!-- Badly formed XML comment ignored for member ""T:A"" --> </members> </doc>".Trim(); Assert.Equal(expected, actual); } [WorkItem(547311, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547311")] [ConditionalFact(typeof(ClrOnly), typeof(DesktopOnly))] [WorkItem(18610, "https://github.com/dotnet/roslyn/issues/18610")] public void UndeclaredXmlNamespace() { var source = @" /// <summary> /// Implement of the bindable radio button /// /// Usage: /// Bind your source property to the Control property Value, and set the CheckValue to your expected value. /// /// Sample: /// /// public enum Shapes /// { /// Square, Circle, Rectangle, Ellipse /// } /// /// class MyControl /// { /// public Shapes Shape { get; set; } /// } /// /// <WpfUtils:BindableRadioButton Value=""{Binding Shape}"" CheckedValue=""Square"">Square</WpfUtils:BindableRadioButton> /// <WpfUtils:BindableRadioButton Value=""{Binding Shape}"" CheckedValue=""Circle"">Circle</WpfUtils:BindableRadioButton> /// <WpfUtils:BindableRadioButton Value=""{Binding Shape}"" CheckedValue=""Ellipse"">Ellipse</WpfUtils:BindableRadioButton> /// /// </summary> class A { } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp, // (2,4): warning CS1570: XML comment has badly formed XML -- ''WpfUtils' is an undeclared prefix.' // /// <summary> Diagnostic(ErrorCode.WRN_XMLParseError, "").WithArguments("'WpfUtils' is an undeclared prefix.")); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <!-- Badly formed XML comment ignored for member ""T:A"" --> </members> </doc>".Trim(); Assert.Equal(expected, actual); } [WorkItem(551323, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/551323")] [Fact] public void MultiLine_OneLinePlusEnding() { var source = @" /** Stuff */ class C { } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> Stuff </member> </members> </doc>".Trim(); Assert.Equal(expected, actual); } [WorkItem(577385, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/577385")] [Fact] public void FormatBeforeFinalParse() { var source = @" /// <summary> /// Get the syntax node(s) where this symbol was declared in source. Some symbols (for /// example, partial classes) may be defined in more than one location. This property should /// return one or more syntax nodes only if the symbol was declared in source code and also /// was not implicitly declared (see the IsImplicitlyDeclared property). /// /// Note that for namespace symbol, the declaring syntax might be declaring a nested /// namespace. For example, the declaring syntax node for N1 in ""namespace N1.N2 {...}"" is /// the entire NamespaceDeclarationSyntax for N1.N2. For the global namespace, the declaring /// syntax will be the CompilationUnitSyntax. /// </summary> /// <returns> /// The syntax node(s) that declared the symbol. If the symbol was declared in metadata or /// was implicitly declared, returns an empty read-only array. /// </returns> /// <remarks> /// To go the opposite direction (from syntax node to symbol), see <see /// cref=""SemanticModel.GetDeclaredSymbol(MemberDeclarationSyntax, CancellationToken)""/>. /// </remarks> class C { } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp, // (19,11): warning CS1574: XML comment has cref attribute 'SemanticModel.GetDeclaredSymbol(MemberDeclarationSyntax, CancellationToken)' that could not be resolved // /// cref="SemanticModel.GetDeclaredSymbol(MemberDeclarationSyntax, CancellationToken)"/>. Diagnostic(ErrorCode.WRN_BadXMLRef, "SemanticModel.GetDeclaredSymbol(MemberDeclarationSyntax, CancellationToken)").WithArguments("GetDeclaredSymbol(MemberDeclarationSyntax, CancellationToken)")); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <summary> Get the syntax node(s) where this symbol was declared in source. Some symbols (for example, partial classes) may be defined in more than one location. This property should return one or more syntax nodes only if the symbol was declared in source code and also was not implicitly declared (see the IsImplicitlyDeclared property). Note that for namespace symbol, the declaring syntax might be declaring a nested namespace. For example, the declaring syntax node for N1 in ""namespace N1.N2 {...}"" is the entire NamespaceDeclarationSyntax for N1.N2. For the global namespace, the declaring syntax will be the CompilationUnitSyntax. </summary> <returns> The syntax node(s) that declared the symbol. If the symbol was declared in metadata or was implicitly declared, returns an empty read-only array. </returns> <remarks> To go the opposite direction (from syntax node to symbol), see <see cref=""!:SemanticModel.GetDeclaredSymbol(MemberDeclarationSyntax, CancellationToken)""/>. </remarks> </member> </members> </doc>".Trim(); Assert.Equal(expected, actual); } [WorkItem(587126, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/587126")] [Fact] public void DeclaringGenericTypeInReturnType() { var source = @" /// <see cref='System.Nullable{T}.op_Implicit'/> class C { } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <see cref='M:System.Nullable`1.op_Implicit(`0)~System.Nullable{`0}'/> </member> </members> </doc>".Trim(); Assert.Equal(expected, actual); } [WorkItem(587126, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/587126")] [Fact] public void DeclaringGenericTypeInParameterType1() { var source = @" /// <see cref=""C{T}.M""/> /// <see cref=""M""/> class C<T> { void M(T t, C<T> c, C<C<T>> cc) { } } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C`1""> <see cref=""M:C`1.M(`0,C{`0},C{C{`0}})""/> <see cref=""M:C`1.M(`0,C{`0},C{C{`0}})""/> </member> </members> </doc>".Trim(); Assert.Equal(expected, actual); } [WorkItem(587126, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/587126")] [Fact] public void DeclaringGenericTypeInParameterType2() { var source = @" class B<U> { /// <see cref=""M1""/> /// <see cref=""M2""/> /// <see cref=""M3""/> /// <see cref=""M4""/> class C<T> { void M1(T t, C<T> c, C<C<T>> cc) { } void M2(U u, C<U> c, C<C<U>> cc) { } void M3(T t, B<T> b, B<B<T>> bb) { } void M4(U u, B<U> b, B<B<U>> bb) { } } } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:B`1.C`1""> <see cref=""M:B`1.C`1.M1(`1,B{`0}.C{`1},B{`0}.C{B{`0}.C{`1}})""/> <see cref=""M:B`1.C`1.M2(`0,B{`0}.C{`0},B{`0}.C{B{`0}.C{`0}})""/> <see cref=""M:B`1.C`1.M3(`1,B{`1},B{B{`1}})""/> <see cref=""M:B`1.C`1.M4(`0,B{`0},B{B{`0}})""/> </member> </members> </doc>".Trim(); Assert.Equal(expected, actual); } [WorkItem(552379, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552379")] [Fact] public void MultipleDocComments() { var source = @" /** Multiline 1. */ /** Multiline 2. */ public class A { } /** Multiline 1. */ /// Single line 1. /** Multiline 2. */ /// Single line 2. public class B { } /** Multiline 1. */ /// Single line 1. public partial class C { } /** Multiline 2. */ /// Single line 2. public partial class C { } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:A""> Multiline 1. Multiline 2. </member> <member name=""T:B""> Multiline 1. Single line 1. Multiline 2. Single line 2. </member> <member name=""T:C""> Multiline 1. Single line 1. Multiline 2. Single line 2. </member> </members> </doc>".Trim(); Assert.Equal(expected, actual); } [WorkItem(552379, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552379")] [Fact] public void MultipleDocComments_Separated() { var source = @" /** Multiline 1. */ // Normal single-line comment. /** Multiline 2. */ public class A { } /** Multiline 1. */ /* Normal multiline comment. */ /** Multiline 2. */ public class B { } /** Multiline 1. */ public partial class C { } // Normal single-line comment. /** Multiline 2. */ public partial class C { } /** Multiline 1. */ #region /** Multiline 2. */ public class D { } /** Multiline 1. */ #endregion /** Multiline 2. */ public class E { } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp, // (2,1): warning CS1587: XML comment is not placed on a valid language element // /** Multiline 1. */ Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (7,1): warning CS1587: XML comment is not placed on a valid language element // /** Multiline 1. */ Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (19,1): warning CS1587: XML comment is not placed on a valid language element // /** Multiline 1. */ Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"), // (24,1): warning CS1587: XML comment is not placed on a valid language element // /** Multiline 1. */ Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/")); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:A""> Multiline 2. </member> <member name=""T:B""> Multiline 2. </member> <member name=""T:C""> Multiline 1. Multiline 2. </member> <member name=""T:D""> Multiline 2. </member> <member name=""T:E""> Multiline 2. </member> </members> </doc>".Trim(); Assert.Equal(expected, actual); } [WorkItem(552379, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552379")] [Fact] public void MultipleDocComments_SplitXml() { var source = @" /** <tag> */ /** </tag> */ public class A { } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp); // NOTE: Dev11 allows this but Roslyn does not. There's no way for // us to build sensible structured trivia for the XML in this scenario. var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <!-- Badly formed XML comment ignored for member ""T:A"" --> </members> </doc>".Trim(); Assert.Equal(expected, actual); } [WorkItem(689497, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/689497")] [Fact] public void TriviaBetweenDocCommentAndDeclaration() { var source = @" /// <summary/> // Single-line comment. /* Multi-line comment. */ #if true #endif #if false #endif #region #endregion public class A { } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:A""> <summary/> </member> </members> </doc>".Trim(); Assert.Equal(expected, actual); } [WorkItem(703368, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/703368")] [Fact] public void NonGenericBeatsGeneric() { var source = @" /// <see cref='M(string)'/> public class C { void M(string s) { } void M<T>(string s) { } } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <see cref='M:C.M(System.String)'/> </member> </members> </doc>".Trim(); Assert.Equal(expected, actual); } [WorkItem(703587, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/703587")] [Fact] public void ObjectMemberViaInterface() { var source = @" using System; /// Comment public class C : IEquatable<C> { /// Implements <see cref=""IEquatable{T}.Equals""/>. /// Implements <see cref=""IEquatable{T}.GetHashCode""/>. bool IEquatable<C>.Equals(C c) { throw null; } } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp, // (7,31): warning CS1574: XML comment has cref attribute 'IEquatable{T}.GetHashCode' that could not be resolved // /// Implements <see cref="IEquatable{T}.GetHashCode"/>. Diagnostic(ErrorCode.WRN_BadXMLRef, "IEquatable{T}.GetHashCode").WithArguments("GetHashCode")); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> Comment </member> <member name=""M:C.System#IEquatable{C}#Equals(C)""> Implements <see cref=""M:System.IEquatable`1.Equals(`0)""/>. Implements <see cref=""!:IEquatable&lt;T&gt;.GetHashCode""/>. </member> </members> </doc>".Trim(); Assert.Equal(expected, actual); } [WorkItem(531505, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531505")] [ClrOnlyFact] public void Pia() { var source = @" /// <see cref='FooStruct'/> /// <see cref='FooStruct.NET'/> public class C { } "; var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <see cref='T:FooStruct'/> <see cref='F:FooStruct.NET'/> </member> </members> </doc>".Trim(); Action<ModuleSymbol> validator = module => { ((PEModuleSymbol)module).Module.PretendThereArentNoPiaLocalTypes(); // No reference added. AssertEx.None(module.GetReferencedAssemblies(), id => id.Name.Contains("GeneralPia")); // No type embedded. Assert.Equal(0, module.GlobalNamespace.GetMembers("FooStruct").Length); }; // Don't embed. { var reference = TestReferences.SymbolsTests.NoPia.GeneralPia.WithEmbedInteropTypes(false); var comp = CreateCompilationUtil(source, new[] { reference }); var actual = GetDocumentationCommentText(comp); Assert.Equal(expected, actual); CompileAndVerify(comp, symbolValidator: validator); } // Do embed. { var reference = TestReferences.SymbolsTests.NoPia.GeneralPia.WithEmbedInteropTypes(true); var comp = CreateCompilationUtil(source, new[] { reference }); var actual = GetDocumentationCommentText(comp); Assert.Equal(expected, actual); CompileAndVerify(comp, symbolValidator: validator); } } [WorkItem(757110, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/757110")] [Fact] public void NoAssemblyElementForNetModule() { var source = @" /// <summary>Text</summary> public class C { } "; var comp = CreateCompilationUtil(source, options: TestOptions.ReleaseModule); var actual = GetDocumentationCommentText(comp); var expected = @" <?xml version=""1.0""?> <doc> <members> <member name=""T:C""> <summary>Text</summary> </member> </members> </doc> ".Trim(); Assert.Equal(expected, actual); } [WorkItem(743425, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/743425")] [Fact] public void WRN_UnqualifiedNestedTypeInCref() { var source = @" class C<T> { class Inner { } void M(Inner i) { } /// <see cref=""M""/> /// <see cref=""C{T}.M""/> /// <see cref=""C{Q}.M""/> /// <see cref=""C{Q}.M(C{Q}.Inner)""/> /// <see cref=""C{Q}.M(Inner)""/> void N() { } } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp, // (12,27): warning CS8018: Within cref attributes, nested types of generic types should be qualified. // /// <see cref="C{Q}.M(Inner)"/> Diagnostic(ErrorCode.WRN_UnqualifiedNestedTypeInCref, "Inner"), // (12,20): warning CS1574: XML comment has cref attribute 'C{Q}.M(Inner)' that could not be resolved // /// <see cref="C{Q}.M(Inner)"/> Diagnostic(ErrorCode.WRN_BadXMLRef, "C{Q}.M(Inner)").WithArguments("M(Inner)")); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""M:C`1.N""> <see cref=""M:C`1.M(C{`0}.Inner)""/> <see cref=""M:C`1.M(C{`0}.Inner)""/> <see cref=""M:C`1.M(C{`0}.Inner)""/> <see cref=""M:C`1.M(C{`0}.Inner)""/> <see cref=""!:C&lt;Q&gt;.M(Inner)""/> </member> </members> </doc> ".Trim(); Assert.Equal(expected, actual); } [WorkItem(743425, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/743425")] [Fact] public void WRN_UnqualifiedNestedTypeInCref_Buried() { var source = @" class C<T> { class Inner { } void M(C<Inner[]> i) { } /// <see cref=""C{Q}.M(C{Inner[]})""/> /// <see cref=""C{Q}.M(C{C{Q}.Inner[]})""/> void N() { } } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp, // (8,27): warning CS8018: Within cref attributes, nested types of generic types should be qualified. // /// <see cref="C{Q}.M(C{Inner[]})"/> Diagnostic(ErrorCode.WRN_UnqualifiedNestedTypeInCref, "C{Inner[]}"), // (8,20): warning CS1574: XML comment has cref attribute 'C{Q}.M(C{Inner[]})' that could not be resolved // /// <see cref="C{Q}.M(C{Inner[]})"/> Diagnostic(ErrorCode.WRN_BadXMLRef, "C{Q}.M(C{Inner[]})").WithArguments("M(C{Inner[]})")); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""M:C`1.N""> <see cref=""!:C&lt;Q&gt;.M(C&lt;Inner[]&gt;)""/> <see cref=""M:C`1.M(C{C{`0}.Inner[]})""/> </member> </members> </doc> ".Trim(); Assert.Equal(expected, actual); } [WorkItem(743425, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/743425")] [Fact] public void WRN_UnqualifiedNestedTypeInCref_Generic() { var source = @" class C<T> { class Inner<U> { } void M(Inner<int> i) { } /// <see cref=""C{Q}.M(C{Q}.Inner{int})""/> /// <see cref=""C{Q}.M(Inner{int})""/> void N() { } } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp, // (9,27): warning CS8018: Within cref attributes, nested types of generic types should be qualified. // /// <see cref="C{Q}.M(Inner{int})"/> Diagnostic(ErrorCode.WRN_UnqualifiedNestedTypeInCref, "Inner{int}"), // (9,20): warning CS1574: XML comment has cref attribute 'C{Q}.M(Inner{int})' that could not be resolved // /// <see cref="C{Q}.M(Inner{int})"/> Diagnostic(ErrorCode.WRN_BadXMLRef, "C{Q}.M(Inner{int})").WithArguments("M(Inner{int})")); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""M:C`1.N""> <see cref=""M:C`1.M(C{`0}.Inner{System.Int32})""/> <see cref=""!:C&lt;Q&gt;.M(Inner&lt;int&gt;)""/> </member> </members> </doc> ".Trim(); Assert.Equal(expected, actual); } #endregion Misc #region Dev11 bugs [Fact] public void Dev11_422418() { // Warn-as-error var source = @" public class C {} // CS1587 "; var tree = Parse(source, options: TestOptions.RegularWithDocumentationComments); var compOptions = TestOptions.ReleaseDll.WithGeneralDiagnosticOption(ReportDiagnostic.Error); CreateCompilation(tree, options: compOptions).VerifyDiagnostics( // (2,14): error CS1591: Warning as Error: Missing XML comment for publicly visible type or member 'C' // public class C {} // CS1587 Diagnostic(ErrorCode.WRN_MissingXMLComment, "C").WithArguments("C").WithWarningAsError(true)); } [ConditionalFact(typeof(ClrOnly), typeof(DesktopOnly))] [WorkItem(18610, "https://github.com/dotnet/roslyn/issues/18610")] public void Dev11_303769() { // XML processing instructions var source = @" /// <summary> /// <?xml:a ?> /// </summary> class C { } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp, // (2,4): warning CS1570: XML comment has badly formed XML -- 'The ':' character, hexadecimal value 0x3A, cannot be included in a name.' // /// <summary> Diagnostic(ErrorCode.WRN_XMLParseError, "").WithArguments("The ':' character, hexadecimal value 0x3A, cannot be included in a name.")); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <!-- Badly formed XML comment ignored for member ""T:C"" --> </members> </doc> ".Trim(); Assert.Equal(expected, actual); } [Fact] public void Dev11_275507() { // Array rank specifier order var source = @" class Program { /** * <param name=""x1""></param> * <param name=""x2""></param> * <returns></returns> */ public void M2(int[] x1, long[][, ,] x2) { } public static void main() { } } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""M:Program.M2(System.Int32[],System.Int64[0:,0:,0:][])""> <param name=""x1""></param> <param name=""x2""></param> <returns></returns> </member> </members> </doc> ".Trim(); Assert.Equal(expected, actual); } [Fact] public void Dev11_274116() { // Included element order. var xml = @" <?xml version=""1.0"" encoding=""utf-8"" ?> <Docs> <Class1> <Remarks name=""Part1""> <para>EXAMPLE 1</para> </Remarks> <Remarks name=""Part2""> <para>EXAMPLE 2</para> </Remarks> </Class1> </Docs> ".Trim(); var xmlFile = Temp.CreateFile(extension: ".xml").WriteAllText(xml); var xmlFilePath = xmlFile.Path; var sourceTemplate = @" /// <summary> /// ... /// </summary> /// <remarks> /// <para>One</para> /// <include file=""{0}"" path=""Docs/Class1/Remarks[@name='Part1']/*"" /> /// <para>Two</para> /// <include file=""{0}"" path=""Docs/Class1/Remarks[@name='Part2']/*"" /> /// <para>Three</para> /// </remarks> public class C {{ }} "; var comp = CreateCompilationUtil(string.Format(sourceTemplate, xmlFilePath)); var actual = GetDocumentationCommentText(comp); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <summary> ... </summary> <remarks> <para>One</para> <para>EXAMPLE 1</para> <para>Two</para> <para>EXAMPLE 2</para> <para>Three</para> </remarks> </member> </members> </doc> ".Trim(); Assert.Equal(expected, actual); } [Fact] public void Dev11_209994() { // Array rank specifier order // NOTE: the remark on the method is copied directly from the bug - // it does not correctly indicate the doc comment ID of the method. var source = @" namespace Demo { public class Example { /// <remarks>M:Demo.Example.M(double[0:,0:,0:][])</remarks> public static void M(double[][, , ,] value) { } } } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp, // (4,18): warning CS1591: Missing XML comment for publicly visible type or member 'Demo.Example' // public class Example Diagnostic(ErrorCode.WRN_MissingXMLComment, "Example").WithArguments("Demo.Example")); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""M:Demo.Example.M(System.Double[0:,0:,0:,0:][])""> <remarks>M:Demo.Example.M(double[0:,0:,0:][])</remarks> </member> </members> </doc> ".Trim(); Assert.Equal(expected, actual); } [ConditionalFact(typeof(ClrOnly), typeof(DesktopOnly))] [WorkItem(18610, "https://github.com/dotnet/roslyn/issues/18610")] public void Dev11_142553() { // Need to cache XML files. var xmlFile = Temp.CreateFile(extension: ".xml").WriteAllText("<hello/>"); string fullPath = xmlFile.Path; string fileName = Path.GetFileName(fullPath); string dirPath = Path.GetDirectoryName(fullPath); var source = @" /// <include file='" + fullPath + @"' path='hello'/> /// <include file='" + fullPath + @"' path='hello'/> /// <include file='" + Path.Combine(dirPath, "a/..", fileName) + @"' path='hello'/> /// <include file='" + Path.Combine(dirPath, @"a\b/../..", fileName) + @"' path='hello'/> class C { } "; CreateCompilationUtil(source).VerifyDiagnostics(); Assert.InRange(DocumentationCommentIncludeCache.CacheMissCount, 1, 2); //Not none, not all. } [Fact] public void UriNotAllowed() { // Need to cache XML files. var xmlFile = Temp.CreateFile(extension: ".xml").WriteAllText("<hello/>"); var source = @" /// <include file='file://" + xmlFile.Path + @"' path='hello'/> class C { } "; CreateCompilationUtil(source).VerifyDiagnostics( // (2,5): warning CS1589: Unable to include XML fragment 'hello' of file '' -- Unable to find the specified file. Diagnostic(ErrorCode.WRN_FailedInclude, @"<include file='file://" + xmlFile.Path + @"' path='hello'/>"). WithArguments("file://" + xmlFile.Path, "hello", "File not found.").WithLocation(2, 5)); } [Fact] public void FileDirective() { // Line directive not considered. var xmlFile = Temp.CreateFile(extension: ".xml").WriteAllText("<hello/>"); string xmlFilePath = Path.GetFileName(xmlFile.Path); string dirPath = Path.GetDirectoryName(xmlFile.Path); string sourcePath = Path.Combine(dirPath, "test.cs"); var source = @" #line 200 ""C:\path\that\doesnt\exist.cs"" /// <include file='" + xmlFilePath + @"' path='hello'/> class C { } "; var comp = CreateCompilation( Parse(source, options: TestOptions.RegularWithDocumentationComments, filename: sourcePath), options: TestOptions.ReleaseDll.WithSourceReferenceResolver(SourceFileResolver.Default).WithXmlReferenceResolver(XmlFileResolver.Default), assemblyName: "Test"); var actual = GetDocumentationCommentText(comp); var expected = @"<?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <hello /> </member> </members> </doc>"; Assert.Equal(expected, actual); } [ConditionalFact(typeof(ClrOnly), typeof(DesktopOnly))] [WorkItem(18610, "https://github.com/dotnet/roslyn/issues/18610")] public void DtdDenialOfService() { var xmlFile = Temp.CreateFile(extension: ".xml").WriteAllText( @"<?xml version=""1.0""?> <!DOCTYPE root [ <!ENTITY expand ""expand""> <!ENTITY expand2 ""&expand;&expand;&expand;&expand;&expand;&expand;&expand;&expand;&expand;&expand;""> <!ENTITY expand3 ""&expand2;&expand2;&expand2;&expand2;&expand2;&expand2;&expand2;&expand2;&expand2;&expand2;""> <!ENTITY expand4 ""&expand3;&expand3;&expand3;&expand3;&expand3;&expand3;&expand3;&expand3;&expand3;&expand3;""> <!ENTITY expand5 ""&expand4;&expand4;&expand4;&expand4;&expand4;&expand4;&expand4;&expand4;&expand4;&expand4;""> <!ENTITY expand6 ""&expand5;&expand5;&expand5;&expand5;&expand5;&expand5;&expand5;&expand5;&expand5;&expand5;""> <!ENTITY expand7 ""&expand6;&expand6;&expand6;&expand6;&expand6;&expand6;&expand6;&expand6;&expand6;&expand6;""> <!ENTITY expand8 ""&expand7;&expand7;&expand7;&expand7;&expand7;&expand7;&expand7;&expand7;&expand7;&expand7;""> <!ENTITY expand9 ""&expand8;&expand8;&expand8;&expand8;&expand8;&expand8;&expand8;&expand8;&expand8;&expand8;""> ]> <root>&expand9;</root> "); var source = @" /// <include file='" + xmlFile.Path + @"' path='hello'/> class C { } "; CreateCompilationUtil(source).GetDiagnostics().VerifyWithFallbackToErrorCodeOnlyForNonEnglish( Diagnostic(ErrorCode.WRN_XMLParseIncludeError).WithArguments("For security reasons DTD is prohibited in this XML document. To enable DTD processing set the DtdProcessing property on XmlReaderSettings to Parse and pass the settings into XmlReader.Create method.").WithLocation(1, 1)); } #endregion Dev11 bugs #region Dev10 bugs [Fact] public void Dev10_898556() { // Somehow, this was causing an infinite loop (even though there's no cycle?). // Delete some irrelevant sections to save space. var xmlTemplate = @" <?xml version=""1.0"" encoding=""utf-8"" ?> <docs> <doc name=""ArrayExtensions.BinarySearchCore""> <overloads>Searches a sorted array for a value using a binary search algorithm.</overloads> <typeparam name=""T"">The type of items in the array.</typeparam> <typeparam name=""TComparator"">The type of comparator used to compare items during the search operation.</typeparam> <param name=""array"">The sorted array to search.</param> <param name=""value"">The object to search for.</param> <returns>If found, the index of the specified value in the given array. Otherwise, if not found, and the value is less than one or more items in the array, a negative number which is the bitwise complement of the index of the first item that is larger than the given value. If the value is not found and it is greater than any of the items in the array, a negative number which is the bitwise complement of (the index of the last item plus 1).</returns> </doc> <doc name=""ArrayExtensions.BinarySearch(ArrayType,T)""> <include file=""{0}"" path=""docs/doc[@name='ArrayExtensions.BinarySearchCore']/*"" /> </doc> <doc name=""ArrayExtensions.BinarySearch(ArrayType,T,TComparator)""> <include file=""{0}"" path=""docs/doc[@name='ArrayExtensions.BinarySearchCore']/*"" /> <param name=""comp"">The comparator used to evaluate the order of items.</param> </doc> <doc name=""ArrayExtensions.BinarySearch(ArrayType,int,int,T)""> <include file=""{0}"" path=""docs/doc[@name='ArrayExtensions.BinarySearchCore']/*"" /> <param name=""index"">The index of the first item in the range.</param> <param name=""count"">The total number of items in the range.</param> </doc> <doc name=""ArrayExtensions.BinarySearch(ArrayType,int,int,T,TComparator)""> <include file=""{0}"" path=""docs/doc[@name='ArrayExtensions.BinarySearch(ArrayType,int,int,T)']/*"" /> <param name=""comp"">The comparator used to evaluate the order of items.</param> </doc> </docs> ".Trim(); var xmlFile = Temp.CreateFile(extension: ".xml"); var xmlFilePath = xmlFile.Path; xmlFile.WriteAllText(string.Format(xmlTemplate, xmlFilePath)); var includeElementTemplate = @"<include file=""{0}"" path=""docs/doc[@name=&quot;ArrayExtensions.BinarySearch(ArrayType,T)&quot;]/*""/>"; var includeElement = string.Format(includeElementTemplate, xmlFilePath); var sourceTemplate = @" /// {0} class C {{ static void Main() {{ }} }} "; var comp = CreateCompilationUtil(string.Format(sourceTemplate, includeElement)); var actual = GetDocumentationCommentText(comp, // (2,5): warning CS1711: XML comment has a typeparam tag for 'T', but there is no type parameter by that name // /// <include file="52f50b557f3d.xml" path="docs/doc[@name=&quot;ArrayExtensions.BinarySearch(ArrayType,T)&quot;]/*"/> Diagnostic(ErrorCode.WRN_UnmatchedTypeParamTag, includeElement).WithArguments("T"), // (2,5): warning CS1711: XML comment has a typeparam tag for 'TComparator', but there is no type parameter by that name // /// <include file="52f50b557f3d.xml" path="docs/doc[@name=&quot;ArrayExtensions.BinarySearch(ArrayType,T)&quot;]/*"/> Diagnostic(ErrorCode.WRN_UnmatchedTypeParamTag, includeElement).WithArguments("TComparator"), // (2,5): warning CS1572: XML comment has a param tag for 'array', but there is no parameter by that name // /// <include file="52f50b557f3d.xml" path="docs/doc[@name=&quot;ArrayExtensions.BinarySearch(ArrayType,T)&quot;]/*"/> Diagnostic(ErrorCode.WRN_UnmatchedParamTag, includeElement).WithArguments("array"), // (2,5): warning CS1572: XML comment has a param tag for 'value', but there is no parameter by that name // /// <include file="52f50b557f3d.xml" path="docs/doc[@name=&quot;ArrayExtensions.BinarySearch(ArrayType,T)&quot;]/*"/> Diagnostic(ErrorCode.WRN_UnmatchedParamTag, includeElement).WithArguments("value")); var expected = (@" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <overloads>Searches a sorted array for a value using a binary search algorithm.</overloads><typeparam name=""T"">" + @"The type of items in the array.</typeparam><typeparam name=""TComparator"">The type of comparator used to compare " + @"items during the search operation.</typeparam><param name=""array"">The sorted array to search.</param><param name=""value"">" + @"The object to search for.</param><returns>If found, the index of the specified value in the given array. Otherwise, if not " + @"found, and the value is less than one or more items in the array, a negative number which is the bitwise complement of the " + @"index of the first item that is larger than the given value. If the value is not found and it is greater than any of the items " + @"in the array, a negative number which is the bitwise complement of (the index of the last item plus 1).</returns> </member> </members> </doc> ").Trim(); Assert.Equal(expected, actual); } [Fact] public void Dev10_785160() { // Someone suggested preferring the more public member in case of ambiguity, but it was not implemented. var source = @" /// <see cref='M'/> class C { private void M(char c) { } public void M(int x) { } } "; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp, // (2,16): warning CS0419: Ambiguous reference in cref attribute: 'M'. Assuming 'C.M(char)', but could have also matched other overloads including 'C.M(int)'. // /// <see cref='M'/> Diagnostic(ErrorCode.WRN_AmbiguousXMLReference, "M").WithArguments("M", "C.M(char)", "C.M(int)")); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <see cref='M:C.M(System.Char)'/> </member> </members> </doc> ".Trim(); Assert.Equal(expected, actual); } [Fact] public void Dev10_747421() { // Bad XML. var source = @" class Module1 { ///<summary> /// ///</summary> ///<remarks><</remarks> public static void Main() { } } "; var comp = CreateCompilationUtil(source); comp.VerifyDiagnostics( // (7,18): warning CS1570: XML comment has badly formed XML -- 'An identifier was expected.' // ///<remarks><</remarks> Diagnostic(ErrorCode.WRN_XMLParseError, "")); var actual = GetDocumentationCommentText(comp); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <!-- Badly formed XML comment ignored for member ""M:Module1.Main"" --> </members> </doc> ".Trim(); Assert.Equal(expected, actual); } #endregion Dev10 bugs [ClrOnlyFact] [WorkItem(1115058, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1115058")] public void UnterminatedElement() { var source = @" class Module1 { ///<summary> /// Something ///<summary> static void Main() { System.Console.WriteLine(""Here""); } }"; var comp = CreateCompilationUtil(source, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "Here").VerifyDiagnostics( // (7,1): warning CS1570: XML comment has badly formed XML -- 'Expected an end tag for element 'summary'.' // static void Main() Diagnostic(ErrorCode.WRN_XMLParseError, "").WithArguments("summary").WithLocation(7, 1), // (7,1): warning CS1570: XML comment has badly formed XML -- 'Expected an end tag for element 'summary'.' // static void Main() Diagnostic(ErrorCode.WRN_XMLParseError, "").WithArguments("summary").WithLocation(7, 1) ); } /// <summary> /// "--" is not valid within an XML comment. /// </summary> [WorkItem(8807, "https://github.com/dotnet/roslyn/issues/8807")] [ConditionalFact(typeof(ClrOnly), typeof(DesktopOnly))] [WorkItem(18610, "https://github.com/dotnet/roslyn/issues/18610")] public void IncludeErrorDashDashInName() { var dir = Temp.CreateDirectory(); var path = dir.Path; var xmlFile = dir.CreateFile("---.xml").WriteAllText(@"<summary attrib="""" attrib=""""/>"); var source = $@"/// <include file='{Path.Combine(path, "---.xml")}' path='//summary'/> class C {{ }}"; var comp = CreateCompilationUtil(source); var actual = GetDocumentationCommentText(comp, // warning CS1592: Badly formed XML in included comments file -- ''attrib' is a duplicate attribute name.' Diagnostic(ErrorCode.WRN_XMLParseIncludeError).WithArguments("'attrib' is a duplicate attribute name.").WithLocation(1, 1)); var expected = $@"<?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <!-- Badly formed XML file ""{Path.Combine(TestHelpers.AsXmlCommentText(path), "- - -.xml")}"" cannot be included --> </member> </members> </doc>"; Assert.Equal(expected, actual); } } }
1
dotnet/roslyn
56,419
Fix partial method doc comments
Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
RikkiGibson
"2021-09-15T20:47:39Z"
"2021-09-21T23:49:10Z"
0f60b3e9446f5d0fc14a570998c81a5d6c40cc23
8cda7462843d43d9b72039eede2f4cb43126cac2
Fix partial method doc comments. Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
./src/Compilers/CSharp/Test/Symbol/DocumentationComments/PartialTypeDocumentationCommentTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class PartialTypeDocumentationCommentTests : CSharpTestBase { private readonly CSharpCompilation _compilation; private readonly NamedTypeSymbol _gooClass; public PartialTypeDocumentationCommentTests() { var tree1 = Parse( @" /// <summary>Summary on first file's Goo.</summary> partial class Goo { /// <summary>Summary on MethodWithNoImplementation.</summary> partial void MethodWithNoImplementation(); /// <summary>Summary in file one which should be shadowed.</summary> partial void ImplementedMethodWithNoSummaryOnImpl(); partial void ImplementedMethod(); }", options: TestOptions.RegularWithDocumentationComments); var tree2 = Parse( @" /// <summary>Summary on second file's Goo.</summary> partial class Goo { /// <remarks>Goo.</remarks> partial void ImplementedMethodWithNoSummaryOnImpl() { } /// <summary>Implemented method.</summary> partial void ImplementedMethod() { } }", options: TestOptions.RegularWithDocumentationComments); _compilation = CreateCompilation(new[] { tree1, tree2 }); _gooClass = _compilation.GlobalNamespace.GetTypeMembers("Goo").Single(); } [Fact] public void TestSummaryOfType() { Assert.Equal( @"<member name=""T:Goo""> <summary>Summary on first file's Goo.</summary> <summary>Summary on second file's Goo.</summary> </member> ", _gooClass.GetDocumentationCommentXml()); } [Fact] public void TestSummaryOfMethodWithNoImplementation() { var method = _gooClass.GetMembers("MethodWithNoImplementation").Single(); Assert.Equal(string.Empty, method.GetDocumentationCommentXml()); //Matches what would be written to an XML file. } [Fact] public void TestImplementedMethodWithNoSummaryOnImpl() { // This is an interesting behavior; as long as there is any XML at all on the implementation, it overrides // any XML on the latent declaration. Since we don't have a summary on this implementation, this should be // null! var method = _gooClass.GetMembers("ImplementedMethodWithNoSummaryOnImpl").Single(); Assert.Equal( @"<member name=""M:Goo.ImplementedMethodWithNoSummaryOnImpl""> <remarks>Goo.</remarks> </member> ", method.GetDocumentationCommentXml()); } [Fact] public void TestImplementedMethod() { var method = _gooClass.GetMembers("ImplementedMethod").Single(); Assert.Equal( @"<member name=""M:Goo.ImplementedMethod""> <summary>Implemented method.</summary> </member> ", method.GetDocumentationCommentXml()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class PartialTypeDocumentationCommentTests : CSharpTestBase { private readonly CSharpCompilation _compilation; private readonly NamedTypeSymbol _gooClass; public PartialTypeDocumentationCommentTests() { var tree1 = Parse( @" /// <summary>Summary on first file's Goo.</summary> partial class Goo { /// <summary>Summary on MethodWithNoImplementation.</summary> partial void MethodWithNoImplementation(); /// <summary>Summary in file one which should be shadowed.</summary> partial void ImplementedMethodWithNoSummaryOnImpl(); partial void ImplementedMethod(); }", options: TestOptions.RegularWithDocumentationComments); var tree2 = Parse( @" /// <summary>Summary on second file's Goo.</summary> partial class Goo { /// <remarks>Goo.</remarks> partial void ImplementedMethodWithNoSummaryOnImpl() { } /// <summary>Implemented method.</summary> partial void ImplementedMethod() { } }", options: TestOptions.RegularWithDocumentationComments); _compilation = CreateCompilation(new[] { tree1, tree2 }); _gooClass = _compilation.GlobalNamespace.GetTypeMembers("Goo").Single(); } [Fact] public void TestSummaryOfType() { Assert.Equal( @"<member name=""T:Goo""> <summary>Summary on first file's Goo.</summary> <summary>Summary on second file's Goo.</summary> </member> ", _gooClass.GetDocumentationCommentXml()); } [Fact] public void TestSummaryOfMethodWithNoImplementation() { var method = _gooClass.GetMembers("MethodWithNoImplementation").Single(); Assert.Equal( @"<member name=""M:Goo.MethodWithNoImplementation""> <summary>Summary on MethodWithNoImplementation.</summary> </member> ", method.GetDocumentationCommentXml()); } [Fact] public void TestImplementedMethodWithNoSummaryOnImpl() { // This is an interesting behavior; as long as there is any XML at all on the implementation, it overrides // any XML on the latent declaration. Since we don't have a summary on this implementation, this should be // null! var method = _gooClass.GetMembers("ImplementedMethodWithNoSummaryOnImpl").Single(); Assert.Equal( @"<member name=""M:Goo.ImplementedMethodWithNoSummaryOnImpl""> <remarks>Goo.</remarks> </member> ", method.GetDocumentationCommentXml()); } [Fact] public void TestImplementedMethod() { var method = _gooClass.GetMembers("ImplementedMethod").Single(); Assert.Equal( @"<member name=""M:Goo.ImplementedMethod""> <summary>Implemented method.</summary> </member> ", method.GetDocumentationCommentXml()); } } }
1
dotnet/roslyn
56,419
Fix partial method doc comments
Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
RikkiGibson
"2021-09-15T20:47:39Z"
"2021-09-21T23:49:10Z"
0f60b3e9446f5d0fc14a570998c81a5d6c40cc23
8cda7462843d43d9b72039eede2f4cb43126cac2
Fix partial method doc comments. Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
./src/EditorFeatures/CSharpTest/QuickInfo/SemanticQuickInfoSourceTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; using System.Security; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Editor.UnitTests.QuickInfo; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.QuickInfo; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using static Microsoft.CodeAnalysis.Editor.UnitTests.Classification.FormattedClassifications; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.QuickInfo { public class SemanticQuickInfoSourceTests : AbstractSemanticQuickInfoSourceTests { private static async Task TestWithOptionsAsync(CSharpParseOptions options, string markup, params Action<QuickInfoItem>[] expectedResults) { using var workspace = TestWorkspace.CreateCSharp(markup, options); await TestWithOptionsAsync(workspace, expectedResults); } private static async Task TestWithOptionsAsync(CSharpCompilationOptions options, string markup, params Action<QuickInfoItem>[] expectedResults) { using var workspace = TestWorkspace.CreateCSharp(markup, compilationOptions: options); await TestWithOptionsAsync(workspace, expectedResults); } private static async Task TestWithOptionsAsync(TestWorkspace workspace, params Action<QuickInfoItem>[] expectedResults) { var testDocument = workspace.DocumentWithCursor; var position = testDocument.CursorPosition.GetValueOrDefault(); var documentId = workspace.GetDocumentId(testDocument); var document = workspace.CurrentSolution.GetDocument(documentId); var service = QuickInfoService.GetService(document); await TestWithOptionsAsync(document, service, position, expectedResults); // speculative semantic model if (await CanUseSpeculativeSemanticModelAsync(document, position)) { var buffer = testDocument.GetTextBuffer(); using (var edit = buffer.CreateEdit()) { var currentSnapshot = buffer.CurrentSnapshot; edit.Replace(0, currentSnapshot.Length, currentSnapshot.GetText()); edit.Apply(); } await TestWithOptionsAsync(document, service, position, expectedResults); } } private static async Task TestWithOptionsAsync(Document document, QuickInfoService service, int position, Action<QuickInfoItem>[] expectedResults) { var info = await service.GetQuickInfoAsync(document, position, cancellationToken: CancellationToken.None); if (expectedResults.Length == 0) { Assert.Null(info); } else { Assert.NotNull(info); foreach (var expected in expectedResults) { expected(info); } } } private static async Task VerifyWithMscorlib45Async(string markup, Action<QuickInfoItem>[] expectedResults) { var xmlString = string.Format(@" <Workspace> <Project Language=""C#"" CommonReferencesNet45=""true""> <Document FilePath=""SourceDocument""> {0} </Document> </Project> </Workspace>", SecurityElement.Escape(markup)); using var workspace = TestWorkspace.Create(xmlString); var position = workspace.Documents.Single(d => d.Name == "SourceDocument").CursorPosition.Value; var documentId = workspace.Documents.Where(d => d.Name == "SourceDocument").Single().Id; var document = workspace.CurrentSolution.GetDocument(documentId); var service = QuickInfoService.GetService(document); var info = await service.GetQuickInfoAsync(document, position, cancellationToken: CancellationToken.None); if (expectedResults.Length == 0) { Assert.Null(info); } else { Assert.NotNull(info); foreach (var expected in expectedResults) { expected(info); } } } protected override async Task TestAsync(string markup, params Action<QuickInfoItem>[] expectedResults) { await TestWithOptionsAsync(Options.Regular, markup, expectedResults); await TestWithOptionsAsync(Options.Script, markup, expectedResults); } private async Task TestWithUsingsAsync(string markup, params Action<QuickInfoItem>[] expectedResults) { var markupWithUsings = @"using System; using System.Collections.Generic; using System.Linq; " + markup; await TestAsync(markupWithUsings, expectedResults); } private Task TestInClassAsync(string markup, params Action<QuickInfoItem>[] expectedResults) { var markupInClass = "class C { " + markup + " }"; return TestWithUsingsAsync(markupInClass, expectedResults); } private Task TestInMethodAsync(string markup, params Action<QuickInfoItem>[] expectedResults) { var markupInMethod = "class C { void M() { " + markup + " } }"; return TestWithUsingsAsync(markupInMethod, expectedResults); } private static async Task TestWithReferenceAsync(string sourceCode, string referencedCode, string sourceLanguage, string referencedLanguage, params Action<QuickInfoItem>[] expectedResults) { await TestWithMetadataReferenceHelperAsync(sourceCode, referencedCode, sourceLanguage, referencedLanguage, expectedResults); await TestWithProjectReferenceHelperAsync(sourceCode, referencedCode, sourceLanguage, referencedLanguage, expectedResults); // Multi-language projects are not supported. if (sourceLanguage == referencedLanguage) { await TestInSameProjectHelperAsync(sourceCode, referencedCode, sourceLanguage, expectedResults); } } private static async Task TestWithMetadataReferenceHelperAsync( string sourceCode, string referencedCode, string sourceLanguage, string referencedLanguage, params Action<QuickInfoItem>[] expectedResults) { var xmlString = string.Format(@" <Workspace> <Project Language=""{0}"" CommonReferences=""true""> <Document FilePath=""SourceDocument""> {1} </Document> <MetadataReferenceFromSource Language=""{2}"" CommonReferences=""true"" IncludeXmlDocComments=""true""> <Document FilePath=""ReferencedDocument""> {3} </Document> </MetadataReferenceFromSource> </Project> </Workspace>", sourceLanguage, SecurityElement.Escape(sourceCode), referencedLanguage, SecurityElement.Escape(referencedCode)); await VerifyWithReferenceWorkerAsync(xmlString, expectedResults); } private static async Task TestWithProjectReferenceHelperAsync( string sourceCode, string referencedCode, string sourceLanguage, string referencedLanguage, params Action<QuickInfoItem>[] expectedResults) { var xmlString = string.Format(@" <Workspace> <Project Language=""{0}"" CommonReferences=""true""> <ProjectReference>ReferencedProject</ProjectReference> <Document FilePath=""SourceDocument""> {1} </Document> </Project> <Project Language=""{2}"" CommonReferences=""true"" AssemblyName=""ReferencedProject""> <Document FilePath=""ReferencedDocument""> {3} </Document> </Project> </Workspace>", sourceLanguage, SecurityElement.Escape(sourceCode), referencedLanguage, SecurityElement.Escape(referencedCode)); await VerifyWithReferenceWorkerAsync(xmlString, expectedResults); } private static async Task TestInSameProjectHelperAsync( string sourceCode, string referencedCode, string sourceLanguage, params Action<QuickInfoItem>[] expectedResults) { var xmlString = string.Format(@" <Workspace> <Project Language=""{0}"" CommonReferences=""true""> <Document FilePath=""SourceDocument""> {1} </Document> <Document FilePath=""ReferencedDocument""> {2} </Document> </Project> </Workspace>", sourceLanguage, SecurityElement.Escape(sourceCode), SecurityElement.Escape(referencedCode)); await VerifyWithReferenceWorkerAsync(xmlString, expectedResults); } private static async Task VerifyWithReferenceWorkerAsync(string xmlString, params Action<QuickInfoItem>[] expectedResults) { using var workspace = TestWorkspace.Create(xmlString); var position = workspace.Documents.First(d => d.Name == "SourceDocument").CursorPosition.Value; var documentId = workspace.Documents.First(d => d.Name == "SourceDocument").Id; var document = workspace.CurrentSolution.GetDocument(documentId); var service = QuickInfoService.GetService(document); var info = await service.GetQuickInfoAsync(document, position, cancellationToken: CancellationToken.None); if (expectedResults.Length == 0) { Assert.Null(info); } else { Assert.NotNull(info); foreach (var expected in expectedResults) { expected(info); } } } protected async Task TestInvalidTypeInClassAsync(string code) { var codeInClass = "class C { " + code + " }"; await TestAsync(codeInClass); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestNamespaceInUsingDirective() { await TestAsync( @"using $$System;", MainDescription("namespace System")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestNamespaceInUsingDirective2() { await TestAsync( @"using System.Coll$$ections.Generic;", MainDescription("namespace System.Collections")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestNamespaceInUsingDirective3() { await TestAsync( @"using System.L$$inq;", MainDescription("namespace System.Linq")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestNamespaceInUsingDirectiveWithAlias() { await TestAsync( @"using Goo = Sys$$tem.Console;", MainDescription("namespace System")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestTypeInUsingDirectiveWithAlias() { await TestAsync( @"using Goo = System.Con$$sole;", MainDescription("class System.Console")); } [WorkItem(991466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991466")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestDocumentationInUsingDirectiveWithAlias() { var markup = @"using I$$ = IGoo; ///<summary>summary for interface IGoo</summary> interface IGoo { }"; await TestAsync(markup, MainDescription("interface IGoo"), Documentation("summary for interface IGoo")); } [WorkItem(991466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991466")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestDocumentationInUsingDirectiveWithAlias2() { var markup = @"using I = IGoo; ///<summary>summary for interface IGoo</summary> interface IGoo { } class C : I$$ { }"; await TestAsync(markup, MainDescription("interface IGoo"), Documentation("summary for interface IGoo")); } [WorkItem(991466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991466")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestDocumentationInUsingDirectiveWithAlias3() { var markup = @"using I = IGoo; ///<summary>summary for interface IGoo</summary> interface IGoo { void Goo(); } class C : I$$ { }"; await TestAsync(markup, MainDescription("interface IGoo"), Documentation("summary for interface IGoo")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestThis() { var markup = @" ///<summary>summary for Class C</summary> class C { string M() { return thi$$s.ToString(); } }"; await TestWithUsingsAsync(markup, MainDescription("class C"), Documentation("summary for Class C")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestClassWithDocComment() { var markup = @" ///<summary>Hello!</summary> class C { void M() { $$C obj; } }"; await TestAsync(markup, MainDescription("class C"), Documentation("Hello!")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestSingleLineDocComments() { // Tests chosen to maximize code coverage in DocumentationCommentCompiler.WriteFormattedSingleLineComment // SingleLine doc comment with leading whitespace await TestAsync( @"///<summary>Hello!</summary> class C { void M() { $$C obj; } }", MainDescription("class C"), Documentation("Hello!")); // SingleLine doc comment with space before opening tag await TestAsync( @"/// <summary>Hello!</summary> class C { void M() { $$C obj; } }", MainDescription("class C"), Documentation("Hello!")); // SingleLine doc comment with space before opening tag and leading whitespace await TestAsync( @"/// <summary>Hello!</summary> class C { void M() { $$C obj; } }", MainDescription("class C"), Documentation("Hello!")); // SingleLine doc comment with leading whitespace and blank line await TestAsync( @"///<summary>Hello! ///</summary> class C { void M() { $$C obj; } }", MainDescription("class C"), Documentation("Hello!")); // SingleLine doc comment with '\r' line separators await TestAsync("///<summary>Hello!\r///</summary>\rclass C { void M() { $$C obj; } }", MainDescription("class C"), Documentation("Hello!")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestMultiLineDocComments() { // Tests chosen to maximize code coverage in DocumentationCommentCompiler.WriteFormattedMultiLineComment // Multiline doc comment with leading whitespace await TestAsync( @"/**<summary>Hello!</summary>*/ class C { void M() { $$C obj; } }", MainDescription("class C"), Documentation("Hello!")); // Multiline doc comment with space before opening tag await TestAsync( @"/** <summary>Hello!</summary> **/ class C { void M() { $$C obj; } }", MainDescription("class C"), Documentation("Hello!")); // Multiline doc comment with space before opening tag and leading whitespace await TestAsync( @"/** ** <summary>Hello!</summary> **/ class C { void M() { $$C obj; } }", MainDescription("class C"), Documentation("Hello!")); // Multiline doc comment with no per-line prefix await TestAsync( @"/** <summary> Hello! </summary> */ class C { void M() { $$C obj; } }", MainDescription("class C"), Documentation("Hello!")); // Multiline doc comment with inconsistent per-line prefix await TestAsync( @"/** ** <summary> Hello!</summary> ** **/ class C { void M() { $$C obj; } }", MainDescription("class C"), Documentation("Hello!")); // Multiline doc comment with closing comment on final line await TestAsync( @"/** <summary>Hello! </summary>*/ class C { void M() { $$C obj; } }", MainDescription("class C"), Documentation("Hello!")); // Multiline doc comment with '\r' line separators await TestAsync("/**\r* <summary>\r* Hello!\r* </summary>\r*/\rclass C { void M() { $$C obj; } }", MainDescription("class C"), Documentation("Hello!")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestMethodWithDocComment() { var markup = @" ///<summary>Hello!</summary> void M() { M$$() }"; await TestInClassAsync(markup, MainDescription("void C.M()"), Documentation("Hello!")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestInt32() { await TestInClassAsync( @"$$Int32 i;", MainDescription("struct System.Int32")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestBuiltInInt() { await TestInClassAsync( @"$$int i;", MainDescription("struct System.Int32")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestString() { await TestInClassAsync( @"$$String s;", MainDescription("class System.String")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestBuiltInString() { await TestInClassAsync( @"$$string s;", MainDescription("class System.String")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestBuiltInStringAtEndOfToken() { await TestInClassAsync( @"string$$ s;", MainDescription("class System.String")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestBoolean() { await TestInClassAsync( @"$$Boolean b;", MainDescription("struct System.Boolean")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestBuiltInBool() { await TestInClassAsync( @"$$bool b;", MainDescription("struct System.Boolean")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestSingle() { await TestInClassAsync( @"$$Single s;", MainDescription("struct System.Single")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestBuiltInFloat() { await TestInClassAsync( @"$$float f;", MainDescription("struct System.Single")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestVoidIsInvalid() { await TestInvalidTypeInClassAsync( @"$$void M() { }"); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestInvalidPointer1_931958() { await TestInvalidTypeInClassAsync( @"$$T* i;"); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestInvalidPointer2_931958() { await TestInvalidTypeInClassAsync( @"T$$* i;"); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestInvalidPointer3_931958() { await TestInvalidTypeInClassAsync( @"T*$$ i;"); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestListOfString() { await TestInClassAsync( @"$$List<string> l;", MainDescription("class System.Collections.Generic.List<T>"), TypeParameterMap($"\r\nT {FeaturesResources.is_} string")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestListOfSomethingFromSource() { var markup = @" ///<summary>Generic List</summary> public class GenericList<T> { Generic$$List<int> t; }"; await TestAsync(markup, MainDescription("class GenericList<T>"), Documentation("Generic List"), TypeParameterMap($"\r\nT {FeaturesResources.is_} int")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestListOfT() { await TestInMethodAsync( @"class C<T> { $$List<T> l; }", MainDescription("class System.Collections.Generic.List<T>")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestDictionaryOfIntAndString() { await TestInClassAsync( @"$$Dictionary<int, string> d;", MainDescription("class System.Collections.Generic.Dictionary<TKey, TValue>"), TypeParameterMap( Lines($"\r\nTKey {FeaturesResources.is_} int", $"TValue {FeaturesResources.is_} string"))); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestDictionaryOfTAndU() { await TestInMethodAsync( @"class C<T, U> { $$Dictionary<T, U> d; }", MainDescription("class System.Collections.Generic.Dictionary<TKey, TValue>"), TypeParameterMap( Lines($"\r\nTKey {FeaturesResources.is_} T", $"TValue {FeaturesResources.is_} U"))); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestIEnumerableOfInt() { await TestInClassAsync( @"$$IEnumerable<int> M() { yield break; }", MainDescription("interface System.Collections.Generic.IEnumerable<out T>"), TypeParameterMap($"\r\nT {FeaturesResources.is_} int")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestEventHandler() { await TestInClassAsync( @"event $$EventHandler e;", MainDescription("delegate void System.EventHandler(object sender, System.EventArgs e)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestTypeParameter() { await TestAsync( @"class C<T> { $$T t; }", MainDescription($"T {FeaturesResources.in_} C<T>")); } [WorkItem(538636, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538636")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestTypeParameterWithDocComment() { var markup = @" ///<summary>Hello!</summary> ///<typeparam name=""T"">T is Type Parameter</typeparam> class C<T> { $$T t; }"; await TestAsync(markup, MainDescription($"T {FeaturesResources.in_} C<T>"), Documentation("T is Type Parameter")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestTypeParameter1_Bug931949() { await TestAsync( @"class T1<T11> { $$T11 t; }", MainDescription($"T11 {FeaturesResources.in_} T1<T11>")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestTypeParameter2_Bug931949() { await TestAsync( @"class T1<T11> { T$$11 t; }", MainDescription($"T11 {FeaturesResources.in_} T1<T11>")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestTypeParameter3_Bug931949() { await TestAsync( @"class T1<T11> { T1$$1 t; }", MainDescription($"T11 {FeaturesResources.in_} T1<T11>")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestTypeParameter4_Bug931949() { await TestAsync( @"class T1<T11> { T11$$ t; }", MainDescription($"T11 {FeaturesResources.in_} T1<T11>")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestNullableOfInt() { await TestInClassAsync(@"$$Nullable<int> i; }", MainDescription("struct System.Nullable<T> where T : struct"), TypeParameterMap($"\r\nT {FeaturesResources.is_} int")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestGenericTypeDeclaredOnMethod1_Bug1946() { await TestAsync( @"class C { static void Meth1<T1>($$T1 i) where T1 : struct { T1 i; } }", MainDescription($"T1 {FeaturesResources.in_} C.Meth1<T1> where T1 : struct")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestGenericTypeDeclaredOnMethod2_Bug1946() { await TestAsync( @"class C { static void Meth1<T1>(T1 i) where $$T1 : struct { T1 i; } }", MainDescription($"T1 {FeaturesResources.in_} C.Meth1<T1> where T1 : struct")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestGenericTypeDeclaredOnMethod3_Bug1946() { await TestAsync( @"class C { static void Meth1<T1>(T1 i) where T1 : struct { $$T1 i; } }", MainDescription($"T1 {FeaturesResources.in_} C.Meth1<T1> where T1 : struct")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestGenericTypeParameterConstraint_Class() { await TestAsync( @"class C<T> where $$T : class { }", MainDescription($"T {FeaturesResources.in_} C<T> where T : class")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestGenericTypeParameterConstraint_Struct() { await TestAsync( @"struct S<T> where $$T : class { }", MainDescription($"T {FeaturesResources.in_} S<T> where T : class")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestGenericTypeParameterConstraint_Interface() { await TestAsync( @"interface I<T> where $$T : class { }", MainDescription($"T {FeaturesResources.in_} I<T> where T : class")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestGenericTypeParameterConstraint_Delegate() { await TestAsync( @"delegate void D<T>() where $$T : class;", MainDescription($"T {FeaturesResources.in_} D<T> where T : class")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestMinimallyQualifiedConstraint() { await TestAsync(@"class C<T> where $$T : IEnumerable<int>", MainDescription($"T {FeaturesResources.in_} C<T> where T : IEnumerable<int>")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task FullyQualifiedConstraint() { await TestAsync(@"class C<T> where $$T : System.Collections.Generic.IEnumerable<int>", MainDescription($"T {FeaturesResources.in_} C<T> where T : System.Collections.Generic.IEnumerable<int>")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestMethodReferenceInSameMethod() { await TestAsync( @"class C { void M() { M$$(); } }", MainDescription("void C.M()")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestMethodReferenceInSameMethodWithDocComment() { var markup = @" ///<summary>Hello World</summary> void M() { M$$(); }"; await TestInClassAsync(markup, MainDescription("void C.M()"), Documentation("Hello World")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestFieldInMethodBuiltIn() { var markup = @"int field; void M() { field$$ }"; await TestInClassAsync(markup, MainDescription($"({FeaturesResources.field}) int C.field")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestFieldInMethodBuiltIn2() { await TestInClassAsync( @"int field; void M() { int f = field$$; }", MainDescription($"({FeaturesResources.field}) int C.field")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestFieldInMethodBuiltInWithFieldInitializer() { await TestInClassAsync( @"int field = 1; void M() { int f = field $$; }"); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestOperatorBuiltIn() { await TestInMethodAsync( @"int x; x = x$$+1;", MainDescription("int int.operator +(int left, int right)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestOperatorBuiltIn1() { await TestInMethodAsync( @"int x; x = x$$ + 1;", MainDescription($"({FeaturesResources.local_variable}) int x")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestOperatorBuiltIn2() { await TestInMethodAsync( @"int x; x = x+$$x;", MainDescription($"({FeaturesResources.local_variable}) int x")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestOperatorBuiltIn3() { await TestInMethodAsync( @"int x; x = x +$$ x;", MainDescription("int int.operator +(int left, int right)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestOperatorBuiltIn4() { await TestInMethodAsync( @"int x; x = x + $$x;", MainDescription($"({FeaturesResources.local_variable}) int x")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestOperatorCustomTypeBuiltIn() { var markup = @"class C { static void M() { C c; c = c +$$ c; } }"; await TestAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestOperatorCustomTypeOverload() { var markup = @"class C { static void M() { C c; c = c +$$ c; } static C operator+(C a, C b) { return a; } }"; await TestAsync(markup, MainDescription("C C.operator +(C a, C b)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestFieldInMethodMinimal() { var markup = @"DateTime field; void M() { field$$ }"; await TestInClassAsync(markup, MainDescription($"({FeaturesResources.field}) DateTime C.field")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestFieldInMethodQualified() { var markup = @"System.IO.FileInfo file; void M() { file$$ }"; await TestInClassAsync(markup, MainDescription($"({FeaturesResources.field}) System.IO.FileInfo C.file")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestMemberOfStructFromSource() { var markup = @"struct MyStruct { public static int SomeField; } static class Test { int a = MyStruct.Some$$Field; }"; await TestAsync(markup, MainDescription($"({FeaturesResources.field}) static int MyStruct.SomeField")); } [WorkItem(538638, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538638")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestMemberOfStructFromSourceWithDocComment() { var markup = @"struct MyStruct { ///<summary>My Field</summary> public static int SomeField; } static class Test { int a = MyStruct.Some$$Field; }"; await TestAsync(markup, MainDescription($"({FeaturesResources.field}) static int MyStruct.SomeField"), Documentation("My Field")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestMemberOfStructInsideMethodFromSource() { var markup = @"struct MyStruct { public static int SomeField; } static class Test { static void Method() { int a = MyStruct.Some$$Field; } }"; await TestAsync(markup, MainDescription($"({FeaturesResources.field}) static int MyStruct.SomeField")); } [WorkItem(538638, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538638")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestMemberOfStructInsideMethodFromSourceWithDocComment() { var markup = @"struct MyStruct { ///<summary>My Field</summary> public static int SomeField; } static class Test { static void Method() { int a = MyStruct.Some$$Field; } }"; await TestAsync(markup, MainDescription($"({FeaturesResources.field}) static int MyStruct.SomeField"), Documentation("My Field")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestMetadataFieldMinimal() { await TestInMethodAsync(@"DateTime dt = DateTime.MaxValue$$", MainDescription($"({FeaturesResources.field}) static readonly DateTime DateTime.MaxValue")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestMetadataFieldQualified1() { // NOTE: we qualify the field type, but not the type that contains the field in Dev10 var markup = @"class C { void M() { DateTime dt = System.DateTime.MaxValue$$ } }"; await TestAsync(markup, MainDescription($"({FeaturesResources.field}) static readonly System.DateTime System.DateTime.MaxValue")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestMetadataFieldQualified2() { await TestAsync( @"class C { void M() { DateTime dt = System.DateTime.MaxValue$$ } }", MainDescription($"({FeaturesResources.field}) static readonly System.DateTime System.DateTime.MaxValue")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestMetadataFieldQualified3() { await TestAsync( @"using System; class C { void M() { DateTime dt = System.DateTime.MaxValue$$ } }", MainDescription($"({FeaturesResources.field}) static readonly DateTime DateTime.MaxValue")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ConstructedGenericField() { await TestAsync( @"class C<T> { public T Field; } class D { void M() { new C<int>().Fi$$eld.ToString(); } }", MainDescription($"({FeaturesResources.field}) int C<int>.Field")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task UnconstructedGenericField() { await TestAsync( @"class C<T> { public T Field; void M() { Fi$$eld.ToString(); } }", MainDescription($"({FeaturesResources.field}) T C<T>.Field")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestIntegerLiteral() { await TestInMethodAsync(@"int f = 37$$", MainDescription("struct System.Int32")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestTrueKeyword() { await TestInMethodAsync(@"bool f = true$$", MainDescription("struct System.Boolean")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestFalseKeyword() { await TestInMethodAsync(@"bool f = false$$", MainDescription("struct System.Boolean")); } [WorkItem(26027, "https://github.com/dotnet/roslyn/issues/26027")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestNullLiteral() { await TestInMethodAsync(@"string f = null$$", MainDescription("class System.String")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestNullLiteralWithVar() => await TestInMethodAsync(@"var f = null$$"); [WorkItem(26027, "https://github.com/dotnet/roslyn/issues/26027")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestDefaultLiteral() { await TestInMethodAsync(@"string f = default$$", MainDescription("class System.String")); } [WorkItem(756226, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756226")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestAwaitKeywordOnGenericTaskReturningAsync() { var markup = @"using System.Threading.Tasks; class C { public async Task<int> Calc() { aw$$ait Calc(); return 5; } }"; await TestAsync(markup, MainDescription(string.Format(FeaturesResources.Awaited_task_returns_0, "struct System.Int32"))); } [WorkItem(756226, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756226")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestAwaitKeywordInDeclarationStatement() { var markup = @"using System.Threading.Tasks; class C { public async Task<int> Calc() { var x = $$await Calc(); return 5; } }"; await TestAsync(markup, MainDescription(string.Format(FeaturesResources.Awaited_task_returns_0, "struct System.Int32"))); } [WorkItem(756226, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756226")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestAwaitKeywordOnTaskReturningAsync() { var markup = @"using System.Threading.Tasks; class C { public async void Calc() { aw$$ait Task.Delay(100); } }"; await TestAsync(markup, MainDescription(FeaturesResources.Awaited_task_returns_no_value)); } [WorkItem(756226, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756226"), WorkItem(756337, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756337")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestNestedAwaitKeywords1() { var markup = @"using System; using System.Threading.Tasks; class AsyncExample2 { async Task<Task<int>> AsyncMethod() { return NewMethod(); } private static Task<int> NewMethod() { int hours = 24; return hours; } async Task UseAsync() { Func<Task<int>> lambda = async () => { return await await AsyncMethod(); }; int result = await await AsyncMethod(); Task<Task<int>> resultTask = AsyncMethod(); result = await awa$$it resultTask; result = await lambda(); } }"; await TestAsync(markup, MainDescription(string.Format(FeaturesResources.Awaited_task_returns_0, $"({CSharpFeaturesResources.awaitable}) class System.Threading.Tasks.Task<TResult>")), TypeParameterMap($"\r\nTResult {FeaturesResources.is_} int")); } [WorkItem(756226, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756226")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestNestedAwaitKeywords2() { var markup = @"using System; using System.Threading.Tasks; class AsyncExample2 { async Task<Task<int>> AsyncMethod() { return NewMethod(); } private static Task<int> NewMethod() { int hours = 24; return hours; } async Task UseAsync() { Func<Task<int>> lambda = async () => { return await await AsyncMethod(); }; int result = await await AsyncMethod(); Task<Task<int>> resultTask = AsyncMethod(); result = awa$$it await resultTask; result = await lambda(); } }"; await TestAsync(markup, MainDescription(string.Format(FeaturesResources.Awaited_task_returns_0, "struct System.Int32"))); } [WorkItem(756226, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756226"), WorkItem(756337, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756337")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestAwaitablePrefixOnCustomAwaiter() { var markup = @"using System; using System.Runtime.CompilerServices; using System.Threading.Tasks; using Z = $$C; class C { public MyAwaiter GetAwaiter() { throw new NotImplementedException(); } } class MyAwaiter : INotifyCompletion { public void OnCompleted(Action continuation) { throw new NotImplementedException(); } public bool IsCompleted { get { throw new NotImplementedException(); } } public void GetResult() { } }"; await TestAsync(markup, MainDescription($"({CSharpFeaturesResources.awaitable}) class C")); } [WorkItem(756226, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756226"), WorkItem(756337, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756337")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestTaskType() { var markup = @"using System.Threading.Tasks; class C { public void Calc() { Task$$ v1; } }"; await TestAsync(markup, MainDescription($"({CSharpFeaturesResources.awaitable}) class System.Threading.Tasks.Task")); } [WorkItem(756226, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756226"), WorkItem(756337, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756337")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestTaskOfTType() { var markup = @"using System; using System.Threading.Tasks; class C { public void Calc() { Task$$<int> v1; } }"; await TestAsync(markup, MainDescription($"({CSharpFeaturesResources.awaitable}) class System.Threading.Tasks.Task<TResult>"), TypeParameterMap($"\r\nTResult {FeaturesResources.is_} int")); } [WorkItem(7100, "https://github.com/dotnet/roslyn/issues/7100")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestDynamicIsntAwaitable() { var markup = @" class C { dynamic D() { return null; } void M() { D$$(); } } "; await TestAsync(markup, MainDescription("dynamic C.D()")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestStringLiteral() { await TestInMethodAsync(@"string f = ""Goo""$$", MainDescription("class System.String")); } [WorkItem(1280, "https://github.com/dotnet/roslyn/issues/1280")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestVerbatimStringLiteral() { await TestInMethodAsync(@"string f = @""cat""$$", MainDescription("class System.String")); } [WorkItem(1280, "https://github.com/dotnet/roslyn/issues/1280")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestInterpolatedStringLiteral() { await TestInMethodAsync(@"string f = $""cat""$$", MainDescription("class System.String")); await TestInMethodAsync(@"string f = $""c$$at""", MainDescription("class System.String")); await TestInMethodAsync(@"string f = $""$$cat""", MainDescription("class System.String")); await TestInMethodAsync(@"string f = $""cat {1$$ + 2} dog""", MainDescription("struct System.Int32")); } [WorkItem(1280, "https://github.com/dotnet/roslyn/issues/1280")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestVerbatimInterpolatedStringLiteral() { await TestInMethodAsync(@"string f = $@""cat""$$", MainDescription("class System.String")); await TestInMethodAsync(@"string f = $@""c$$at""", MainDescription("class System.String")); await TestInMethodAsync(@"string f = $@""$$cat""", MainDescription("class System.String")); await TestInMethodAsync(@"string f = $@""cat {1$$ + 2} dog""", MainDescription("struct System.Int32")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestCharLiteral() { await TestInMethodAsync(@"string f = 'x'$$", MainDescription("struct System.Char")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task DynamicKeyword() { await TestInMethodAsync( @"dyn$$amic dyn;", MainDescription("dynamic"), Documentation(FeaturesResources.Represents_an_object_whose_operations_will_be_resolved_at_runtime)); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task DynamicField() { await TestInClassAsync( @"dynamic dyn; void M() { d$$yn.Goo(); }", MainDescription($"({FeaturesResources.field}) dynamic C.dyn")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task LocalProperty_Minimal() { await TestInClassAsync( @"DateTime Prop { get; set; } void M() { P$$rop.ToString(); }", MainDescription("DateTime C.Prop { get; set; }")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task LocalProperty_Minimal_PrivateSet() { await TestInClassAsync( @"public DateTime Prop { get; private set; } void M() { P$$rop.ToString(); }", MainDescription("DateTime C.Prop { get; private set; }")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task LocalProperty_Minimal_PrivateSet1() { await TestInClassAsync( @"protected internal int Prop { get; private set; } void M() { P$$rop.ToString(); }", MainDescription("int C.Prop { get; private set; }")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task LocalProperty_Qualified() { await TestInClassAsync( @"System.IO.FileInfo Prop { get; set; } void M() { P$$rop.ToString(); }", MainDescription("System.IO.FileInfo C.Prop { get; set; }")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NonLocalProperty_Minimal() { await TestInMethodAsync(@"DateTime.No$$w.ToString();", MainDescription("DateTime DateTime.Now { get; }")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NonLocalProperty_Qualified() { await TestInMethodAsync( @"System.IO.FileInfo f; f.Att$$ributes.ToString();", MainDescription("System.IO.FileAttributes System.IO.FileSystemInfo.Attributes { get; set; }")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ConstructedGenericProperty() { await TestAsync( @"class C<T> { public T Property { get; set } } class D { void M() { new C<int>().Pro$$perty.ToString(); } }", MainDescription("int C<int>.Property { get; set; }")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task UnconstructedGenericProperty() { await TestAsync( @"class C<T> { public T Property { get; set} void M() { Pro$$perty.ToString(); } }", MainDescription("T C<T>.Property { get; set; }")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ValueInProperty() { await TestInClassAsync( @"public DateTime Property { set { goo = val$$ue; } }", MainDescription($"({FeaturesResources.parameter}) DateTime value")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task EnumTypeName() { await TestInMethodAsync(@"Consol$$eColor c", MainDescription("enum System.ConsoleColor")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(52490, "https://github.com/dotnet/roslyn/issues/52490")] public async Task EnumNonDefaultUnderlyingType_Definition() { await TestInClassAsync(@"enum E$$ : byte { A, B }", MainDescription("enum C.E : byte")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(52490, "https://github.com/dotnet/roslyn/issues/52490")] public async Task EnumNonDefaultUnderlyingType_AsField() { await TestInClassAsync(@" enum E : byte { A, B } private E$$ _E; ", MainDescription("enum C.E : byte")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(52490, "https://github.com/dotnet/roslyn/issues/52490")] public async Task EnumNonDefaultUnderlyingType_AsProperty() { await TestInClassAsync(@" enum E : byte { A, B } private E$$ E{ get; set; }; ", MainDescription("enum C.E : byte")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(52490, "https://github.com/dotnet/roslyn/issues/52490")] public async Task EnumNonDefaultUnderlyingType_AsParameter() { await TestInClassAsync(@" enum E : byte { A, B } private void M(E$$ e) { } ", MainDescription("enum C.E : byte")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(52490, "https://github.com/dotnet/roslyn/issues/52490")] public async Task EnumNonDefaultUnderlyingType_AsReturnType() { await TestInClassAsync(@" enum E : byte { A, B } private E$$ M() { } ", MainDescription("enum C.E : byte")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(52490, "https://github.com/dotnet/roslyn/issues/52490")] public async Task EnumNonDefaultUnderlyingType_AsLocal() { await TestInClassAsync(@" enum E : byte { A, B } private void M() { E$$ e = default; } ", MainDescription("enum C.E : byte")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(52490, "https://github.com/dotnet/roslyn/issues/52490")] public async Task EnumNonDefaultUnderlyingType_OnMemberAccessOnType() { await TestInClassAsync(@" enum E : byte { A, B } private void M() { var ea = E$$.A; } ", MainDescription("enum C.E : byte")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(52490, "https://github.com/dotnet/roslyn/issues/52490")] public async Task EnumNonDefaultUnderlyingType_NotOnMemberAccessOnMember() { await TestInClassAsync(@" enum E : byte { A, B } private void M() { var ea = E.A$$; } ", MainDescription("E.A = 0")); } [Theory, WorkItem(52490, "https://github.com/dotnet/roslyn/issues/52490")] [InlineData("byte", "byte")] [InlineData("byte", "System.Byte")] [InlineData("sbyte", "sbyte")] [InlineData("sbyte", "System.SByte")] [InlineData("short", "short")] [InlineData("short", "System.Int16")] [InlineData("ushort", "ushort")] [InlineData("ushort", "System.UInt16")] // int is the default type and is not shown [InlineData("uint", "uint")] [InlineData("uint", "System.UInt32")] [InlineData("long", "long")] [InlineData("long", "System.Int64")] [InlineData("ulong", "ulong")] [InlineData("ulong", "System.UInt64")] public async Task EnumNonDefaultUnderlyingType_ShowForNonDefaultTypes(string displayTypeName, string underlyingTypeName) { await TestInClassAsync(@$" enum E$$ : {underlyingTypeName} {{ A, B }}", MainDescription($"enum C.E : {displayTypeName}")); } [Theory, WorkItem(52490, "https://github.com/dotnet/roslyn/issues/52490")] [InlineData("")] [InlineData(": int")] [InlineData(": System.Int32")] public async Task EnumNonDefaultUnderlyingType_DontShowForDefaultType(string defaultType) { await TestInClassAsync(@$" enum E$$ {defaultType} {{ A, B }}", MainDescription("enum C.E")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task EnumMemberNameFromMetadata() { await TestInMethodAsync(@"ConsoleColor c = ConsoleColor.Bla$$ck", MainDescription("ConsoleColor.Black = 0")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task FlagsEnumMemberNameFromMetadata1() { await TestInMethodAsync(@"AttributeTargets a = AttributeTargets.Cl$$ass", MainDescription("AttributeTargets.Class = 4")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task FlagsEnumMemberNameFromMetadata2() { await TestInMethodAsync(@"AttributeTargets a = AttributeTargets.A$$ll", MainDescription("AttributeTargets.All = AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Parameter | AttributeTargets.Delegate | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task EnumMemberNameFromSource1() { await TestAsync( @"enum E { A = 1 << 0, B = 1 << 1, C = 1 << 2 } class C { void M() { var e = E.B$$; } }", MainDescription("E.B = 1 << 1")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task EnumMemberNameFromSource2() { await TestAsync( @"enum E { A, B, C } class C { void M() { var e = E.B$$; } }", MainDescription("E.B = 1")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Parameter_InMethod_Minimal() { await TestInClassAsync( @"void M(DateTime dt) { d$$t.ToString();", MainDescription($"({FeaturesResources.parameter}) DateTime dt")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Parameter_InMethod_Qualified() { await TestInClassAsync( @"void M(System.IO.FileInfo fileInfo) { file$$Info.ToString();", MainDescription($"({FeaturesResources.parameter}) System.IO.FileInfo fileInfo")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Parameter_FromReferenceToNamedParameter() { await TestInMethodAsync(@"Console.WriteLine(va$$lue: ""Hi"");", MainDescription($"({FeaturesResources.parameter}) string value")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Parameter_DefaultValue() { // NOTE: Dev10 doesn't show the default value, but it would be nice if we did. // NOTE: The "DefaultValue" property isn't implemented yet. await TestInClassAsync( @"void M(int param = 42) { para$$m.ToString(); }", MainDescription($"({FeaturesResources.parameter}) int param = 42")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Parameter_Params() { await TestInClassAsync( @"void M(params DateTime[] arg) { ar$$g.ToString(); }", MainDescription($"({FeaturesResources.parameter}) params DateTime[] arg")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Parameter_Ref() { await TestInClassAsync( @"void M(ref DateTime arg) { ar$$g.ToString(); }", MainDescription($"({FeaturesResources.parameter}) ref DateTime arg")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Parameter_Out() { await TestInClassAsync( @"void M(out DateTime arg) { ar$$g.ToString(); }", MainDescription($"({FeaturesResources.parameter}) out DateTime arg")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Local_Minimal() { await TestInMethodAsync( @"DateTime dt; d$$t.ToString();", MainDescription($"({FeaturesResources.local_variable}) DateTime dt")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Local_Qualified() { await TestInMethodAsync( @"System.IO.FileInfo fileInfo; file$$Info.ToString();", MainDescription($"({FeaturesResources.local_variable}) System.IO.FileInfo fileInfo")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Method_MetadataOverload() { await TestInMethodAsync("Console.Write$$Line();", MainDescription($"void Console.WriteLine() (+ 18 {FeaturesResources.overloads_})")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Method_SimpleWithOverload() { await TestInClassAsync( @"void Method() { Met$$hod(); } void Method(int i) { }", MainDescription($"void C.Method() (+ 1 {FeaturesResources.overload})")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Method_MoreOverloads() { await TestInClassAsync( @"void Method() { Met$$hod(null); } void Method(int i) { } void Method(DateTime dt) { } void Method(System.IO.FileInfo fileInfo) { }", MainDescription($"void C.Method(System.IO.FileInfo fileInfo) (+ 3 {FeaturesResources.overloads_})")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Method_SimpleInSameClass() { await TestInClassAsync( @"DateTime GetDate(System.IO.FileInfo ft) { Get$$Date(null); }", MainDescription("DateTime C.GetDate(System.IO.FileInfo ft)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Method_OptionalParameter() { await TestInClassAsync( @"void M() { Met$$hod(); } void Method(int i = 0) { }", MainDescription("void C.Method([int i = 0])")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Method_OptionalDecimalParameter() { await TestInClassAsync( @"void Goo(decimal x$$yz = 10) { }", MainDescription($"({FeaturesResources.parameter}) decimal xyz = 10")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Method_Generic() { // Generic method don't get the instantiation info yet. NOTE: We don't display // constraint info in Dev10. Should we? await TestInClassAsync( @"TOut Goo<TIn, TOut>(TIn arg) where TIn : IEquatable<TIn> { Go$$o<int, DateTime>(37); }", MainDescription("DateTime C.Goo<int, DateTime>(int arg)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Method_UnconstructedGeneric() { await TestInClassAsync( @"TOut Goo<TIn, TOut>(TIn arg) { Go$$o<TIn, TOut>(default(TIn); }", MainDescription("TOut C.Goo<TIn, TOut>(TIn arg)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Method_Inferred() { await TestInClassAsync( @"void Goo<TIn>(TIn arg) { Go$$o(42); }", MainDescription("void C.Goo<int>(int arg)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Method_MultipleParams() { await TestInClassAsync( @"void Goo(DateTime dt, System.IO.FileInfo fi, int number) { Go$$o(DateTime.Now, null, 32); }", MainDescription("void C.Goo(DateTime dt, System.IO.FileInfo fi, int number)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Method_OptionalParam() { // NOTE - Default values aren't actually returned by symbols yet. await TestInClassAsync( @"void Goo(int num = 42) { Go$$o(); }", MainDescription("void C.Goo([int num = 42])")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Method_ParameterModifiers() { // NOTE - Default values aren't actually returned by symbols yet. await TestInClassAsync( @"void Goo(ref DateTime dt, out System.IO.FileInfo fi, params int[] numbers) { Go$$o(DateTime.Now, null, 32); }", MainDescription("void C.Goo(ref DateTime dt, out System.IO.FileInfo fi, params int[] numbers)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Constructor() { await TestInClassAsync( @"public C() { } void M() { new C$$().ToString(); }", MainDescription("C.C()")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Constructor_Overloads() { await TestInClassAsync( @"public C() { } public C(DateTime dt) { } public C(int i) { } void M() { new C$$(DateTime.MaxValue).ToString(); }", MainDescription($"C.C(DateTime dt) (+ 2 {FeaturesResources.overloads_})")); } /// <summary> /// Regression for 3923 /// </summary> [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Constructor_OverloadFromStringLiteral() { await TestInMethodAsync( @"new InvalidOperatio$$nException("""");", MainDescription($"InvalidOperationException.InvalidOperationException(string message) (+ 2 {FeaturesResources.overloads_})")); } /// <summary> /// Regression for 3923 /// </summary> [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Constructor_UnknownType() { await TestInvalidTypeInClassAsync( @"void M() { new G$$oo(); }"); } /// <summary> /// Regression for 3923 /// </summary> [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Constructor_OverloadFromProperty() { await TestInMethodAsync( @"new InvalidOperatio$$nException(this.GetType().Name);", MainDescription($"InvalidOperationException.InvalidOperationException(string message) (+ 2 {FeaturesResources.overloads_})")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Constructor_Metadata() { await TestInMethodAsync( @"new Argument$$NullException();", MainDescription($"ArgumentNullException.ArgumentNullException() (+ 3 {FeaturesResources.overloads_})")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Constructor_MetadataQualified() { await TestInMethodAsync(@"new System.IO.File$$Info(null);", MainDescription("System.IO.FileInfo.FileInfo(string fileName)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task InterfaceProperty() { await TestInMethodAsync( @"interface I { string Name$$ { get; set; } }", MainDescription("string I.Name { get; set; }")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ExplicitInterfacePropertyImplementation() { await TestInMethodAsync( @"interface I { string Name { get; set; } } class C : I { string IEmployee.Name$$ { get { return """"; } set { } } }", MainDescription("string C.Name { get; set; }")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Operator() { await TestInClassAsync( @"public static C operator +(C left, C right) { return null; } void M(C left, C right) { return left +$$ right; }", MainDescription("C C.operator +(C left, C right)")); } #pragma warning disable CA2243 // Attribute string literals should parse correctly [WorkItem(792629, "generic type parameter constraints for methods in quick info")] #pragma warning restore CA2243 // Attribute string literals should parse correctly [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task GenericMethodWithConstraintsAtDeclaration() { await TestInClassAsync( @"TOut G$$oo<TIn, TOut>(TIn arg) where TIn : IEquatable<TIn> { }", MainDescription("TOut C.Goo<TIn, TOut>(TIn arg) where TIn : IEquatable<TIn>")); } #pragma warning disable CA2243 // Attribute string literals should parse correctly [WorkItem(792629, "generic type parameter constraints for methods in quick info")] #pragma warning restore CA2243 // Attribute string literals should parse correctly [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task GenericMethodWithMultipleConstraintsAtDeclaration() { await TestInClassAsync( @"TOut Goo<TIn, TOut>(TIn arg) where TIn : Employee, new() { Go$$o<TIn, TOut>(default(TIn); }", MainDescription("TOut C.Goo<TIn, TOut>(TIn arg) where TIn : Employee, new()")); } #pragma warning disable CA2243 // Attribute string literals should parse correctly [WorkItem(792629, "generic type parameter constraints for methods in quick info")] #pragma warning restore CA2243 // Attribute string literals should parse correctly [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task UnConstructedGenericMethodWithConstraintsAtInvocation() { await TestInClassAsync( @"TOut Goo<TIn, TOut>(TIn arg) where TIn : Employee { Go$$o<TIn, TOut>(default(TIn); }", MainDescription("TOut C.Goo<TIn, TOut>(TIn arg) where TIn : Employee")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task GenericTypeWithConstraintsAtDeclaration() { await TestAsync( @"public class Employee : IComparable<Employee> { public int CompareTo(Employee other) { throw new NotImplementedException(); } } class Emplo$$yeeList<T> : IEnumerable<T> where T : Employee, System.IComparable<T>, new() { }", MainDescription("class EmployeeList<T> where T : Employee, System.IComparable<T>, new()")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task GenericType() { await TestAsync( @"class T1<T11> { $$T11 i; }", MainDescription($"T11 {FeaturesResources.in_} T1<T11>")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task GenericMethod() { await TestInClassAsync( @"static void Meth1<T1>(T1 i) where T1 : struct { $$T1 i; }", MainDescription($"T1 {FeaturesResources.in_} C.Meth1<T1> where T1 : struct")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Var() { await TestInMethodAsync( @"var x = new Exception(); var y = $$x;", MainDescription($"({FeaturesResources.local_variable}) Exception x")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NullableReference() { await TestWithOptionsAsync( Options.Regular.WithLanguageVersion(LanguageVersion.CSharp8), @"class A<T> { } class B { static void M() { A<B?>? x = null!; var y = x; $$y.ToString(); } }", // https://github.com/dotnet/roslyn/issues/26198 public API should show inferred nullability MainDescription($"({FeaturesResources.local_variable}) A<B?> y")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(26648, "https://github.com/dotnet/roslyn/issues/26648")] public async Task NullableReference_InMethod() { var code = @" class G { void M() { C c; c.Go$$o(); } } public class C { public string? Goo(IEnumerable<object?> arg) { } }"; await TestWithOptionsAsync( Options.Regular.WithLanguageVersion(LanguageVersion.CSharp8), code, MainDescription("string? C.Goo(IEnumerable<object?> arg)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NestedInGeneric() { await TestInMethodAsync( @"List<int>.Enu$$merator e;", MainDescription("struct System.Collections.Generic.List<T>.Enumerator"), TypeParameterMap($"\r\nT {FeaturesResources.is_} int")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NestedGenericInGeneric() { await TestAsync( @"class Outer<T> { class Inner<U> { } static void M() { Outer<int>.I$$nner<string> e; } }", MainDescription("class Outer<T>.Inner<U>"), TypeParameterMap( Lines($"\r\nT {FeaturesResources.is_} int", $"U {FeaturesResources.is_} string"))); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ObjectInitializer1() { await TestInClassAsync( @"void M() { var x = new test() { $$z = 5 }; } class test { public int z; }", MainDescription($"({FeaturesResources.field}) int test.z")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ObjectInitializer2() { await TestInMethodAsync( @"class C { void M() { var x = new test() { z = $$5 }; } class test { public int z; } }", MainDescription("struct System.Int32")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(537880, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537880")] public async Task TypeArgument() { await TestAsync( @"class C<T, Y> { void M() { C<int, DateTime> variable; $$variable = new C<int, DateTime>(); } }", MainDescription($"({FeaturesResources.local_variable}) C<int, DateTime> variable")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ForEachLoop_1() { await TestInMethodAsync( @"int bb = 555; bb = bb + 1; foreach (int cc in new int[]{ 1,2,3}){ c$$c = 1; bb = bb + 21; }", MainDescription($"({FeaturesResources.local_variable}) int cc")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TryCatchFinally_1() { await TestInMethodAsync( @"try { int aa = 555; a$$a = aa + 1; } catch (Exception ex) { } finally { }", MainDescription($"({FeaturesResources.local_variable}) int aa")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TryCatchFinally_2() { await TestInMethodAsync( @"try { } catch (Exception ex) { var y = e$$x; var z = y; } finally { }", MainDescription($"({FeaturesResources.local_variable}) Exception ex")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TryCatchFinally_3() { await TestInMethodAsync( @"try { } catch (Exception ex) { var aa = 555; aa = a$$a + 1; } finally { }", MainDescription($"({FeaturesResources.local_variable}) int aa")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TryCatchFinally_4() { await TestInMethodAsync( @"try { } catch (Exception ex) { } finally { int aa = 555; aa = a$$a + 1; }", MainDescription($"({FeaturesResources.local_variable}) int aa")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task GenericVariable() { await TestAsync( @"class C<T, Y> { void M() { C<int, DateTime> variable; var$$iable = new C<int, DateTime>(); } }", MainDescription($"({FeaturesResources.local_variable}) C<int, DateTime> variable")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestInstantiation() { await TestAsync( @"using System.Collections.Generic; class Program<T> { static void Main(string[] args) { var p = new Dictio$$nary<int, string>(); } }", MainDescription($"Dictionary<int, string>.Dictionary() (+ 5 {FeaturesResources.overloads_})")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestUsingAlias_Bug4141() { await TestAsync( @"using X = A.C; class A { public class C { } } class D : X$$ { }", MainDescription(@"class A.C")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestFieldOnDeclaration() { await TestInClassAsync( @"DateTime fie$$ld;", MainDescription($"({FeaturesResources.field}) DateTime C.field")); } [WorkItem(538767, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538767")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestGenericErrorFieldOnDeclaration() { await TestInClassAsync( @"NonExistentType<int> fi$$eld;", MainDescription($"({FeaturesResources.field}) NonExistentType<int> C.field")); } [WorkItem(538822, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538822")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestDelegateType() { await TestInClassAsync( @"Fun$$c<int, string> field;", MainDescription("delegate TResult System.Func<in T, out TResult>(T arg)"), TypeParameterMap( Lines($"\r\nT {FeaturesResources.is_} int", $"TResult {FeaturesResources.is_} string"))); } [WorkItem(538824, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538824")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestOnDelegateInvocation() { await TestAsync( @"class Program { delegate void D1(); static void Main() { D1 d = Main; $$d(); } }", MainDescription($"({FeaturesResources.local_variable}) D1 d")); } [WorkItem(539240, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539240")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestOnArrayCreation1() { await TestAsync( @"class Program { static void Main() { int[] a = n$$ew int[0]; } }", MainDescription("int[]")); } [WorkItem(539240, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539240")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestOnArrayCreation2() { await TestAsync( @"class Program { static void Main() { int[] a = new i$$nt[0]; } }", MainDescription("struct System.Int32")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Constructor_ImplicitObjectCreation() { await TestAsync( @"class C { static void Main() { C c = ne$$w(); } } ", MainDescription("C.C()")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Constructor_ImplicitObjectCreation_WithParameters() { await TestAsync( @"class C { C(int i) { } C(string s) { } static void Main() { C c = ne$$w(1); } } ", MainDescription($"C.C(int i) (+ 1 {FeaturesResources.overload})")); } [WorkItem(539841, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539841")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestIsNamedTypeAccessibleForErrorTypes() { await TestAsync( @"sealed class B<T1, T2> : A<B<T1, T2>> { protected sealed override B<A<T>, A$$<T>> N() { } } internal class A<T> { }", MainDescription("class A<T>")); } [WorkItem(540075, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540075")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestErrorType() { await TestAsync( @"using Goo = Goo; class C { void Main() { $$Goo } }", MainDescription("Goo")); } [WorkItem(16662, "https://github.com/dotnet/roslyn/issues/16662")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestShortDiscardInAssignment() { await TestAsync( @"class C { int M() { $$_ = M(); } }", MainDescription($"({FeaturesResources.discard}) int _")); } [WorkItem(16662, "https://github.com/dotnet/roslyn/issues/16662")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestUnderscoreLocalInAssignment() { await TestAsync( @"class C { int M() { var $$_ = M(); } }", MainDescription($"({FeaturesResources.local_variable}) int _")); } [WorkItem(16662, "https://github.com/dotnet/roslyn/issues/16662")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestShortDiscardInOutVar() { await TestAsync( @"class C { void M(out int i) { M(out $$_); i = 0; } }", MainDescription($"({FeaturesResources.discard}) int _")); } [WorkItem(16667, "https://github.com/dotnet/roslyn/issues/16667")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestDiscardInOutVar() { await TestAsync( @"class C { void M(out int i) { M(out var $$_); i = 0; } }"); // No quick info (see issue #16667) } [WorkItem(16667, "https://github.com/dotnet/roslyn/issues/16667")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestDiscardInIsPattern() { await TestAsync( @"class C { void M() { if (3 is int $$_) { } } }"); // No quick info (see issue #16667) } [WorkItem(16667, "https://github.com/dotnet/roslyn/issues/16667")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestDiscardInSwitchPattern() { await TestAsync( @"class C { void M() { switch (3) { case int $$_: return; } } }"); // No quick info (see issue #16667) } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestLambdaDiscardParameter_FirstDiscard() { await TestAsync( @"class C { void M() { System.Func<string, int, int> f = ($$_, _) => 1; } }", MainDescription($"({FeaturesResources.discard}) string _")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestLambdaDiscardParameter_SecondDiscard() { await TestAsync( @"class C { void M() { System.Func<string, int, int> f = (_, $$_) => 1; } }", MainDescription($"({FeaturesResources.discard}) int _")); } [WorkItem(540871, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540871")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestLiterals() { await TestAsync( @"class MyClass { MyClass() : this($$10) { intI = 2; } public MyClass(int i) { } static int intI = 1; public static int Main() { return 1; } }", MainDescription("struct System.Int32")); } [WorkItem(541444, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541444")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestErrorInForeach() { await TestAsync( @"class C { void Main() { foreach (int cc in null) { $$cc = 1; } } }", MainDescription($"({FeaturesResources.local_variable}) int cc")); } [WorkItem(541678, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541678")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestQuickInfoOnEvent() { await TestAsync( @"using System; public class SampleEventArgs { public SampleEventArgs(string s) { Text = s; } public String Text { get; private set; } } public class Publisher { public delegate void SampleEventHandler(object sender, SampleEventArgs e); public event SampleEventHandler SampleEvent; protected virtual void RaiseSampleEvent() { if (Sam$$pleEvent != null) SampleEvent(this, new SampleEventArgs(""Hello"")); } }", MainDescription("SampleEventHandler Publisher.SampleEvent")); } [WorkItem(542157, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542157")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestEvent() { await TestInMethodAsync(@"System.Console.CancelKeyPres$$s += null;", MainDescription("ConsoleCancelEventHandler Console.CancelKeyPress")); } [WorkItem(542157, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542157")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestEventPlusEqualsOperator() { await TestInMethodAsync(@"System.Console.CancelKeyPress +$$= null;", MainDescription("void Console.CancelKeyPress.add")); } [WorkItem(542157, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542157")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestEventMinusEqualsOperator() { await TestInMethodAsync(@"System.Console.CancelKeyPress -$$= null;", MainDescription("void Console.CancelKeyPress.remove")); } [WorkItem(541885, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541885")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestQuickInfoOnExtensionMethod() { await TestWithOptionsAsync(Options.Regular, @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { int[] values = { 1 }; bool isArray = 7.I$$n(values); } } public static class MyExtensions { public static bool In<T>(this T o, IEnumerable<T> items) { return true; } }", MainDescription($"({CSharpFeaturesResources.extension}) bool int.In<int>(IEnumerable<int> items)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestQuickInfoOnExtensionMethodOverloads() { await TestWithOptionsAsync(Options.Regular, @"using System; using System.Linq; class Program { static void Main(string[] args) { ""1"".Test$$Ext(); } } public static class Ex { public static void TestExt<T>(this T ex) { } public static void TestExt<T>(this T ex, T arg) { } public static void TestExt(this string ex, int arg) { } }", MainDescription($"({CSharpFeaturesResources.extension}) void string.TestExt<string>() (+ 2 {FeaturesResources.overloads_})")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestQuickInfoOnExtensionMethodOverloads2() { await TestWithOptionsAsync(Options.Regular, @"using System; using System.Linq; class Program { static void Main(string[] args) { ""1"".Test$$Ext(); } } public static class Ex { public static void TestExt<T>(this T ex) { } public static void TestExt<T>(this T ex, T arg) { } public static void TestExt(this int ex, int arg) { } }", MainDescription($"({CSharpFeaturesResources.extension}) void string.TestExt<string>() (+ 1 {FeaturesResources.overload})")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Query1() { await TestAsync( @"using System.Linq; class C { void M() { var q = from n in new int[] { 1, 2, 3, 4, 5 } select $$n; } }", MainDescription($"({FeaturesResources.range_variable}) int n")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Query2() { await TestAsync( @"using System.Linq; class C { void M() { var q = from n$$ in new int[] { 1, 2, 3, 4, 5 } select n; } }", MainDescription($"({FeaturesResources.range_variable}) int n")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Query3() { await TestAsync( @"class C { void M() { var q = from n in new int[] { 1, 2, 3, 4, 5 } select $$n; } }", MainDescription($"({FeaturesResources.range_variable}) ? n")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Query4() { await TestAsync( @"class C { void M() { var q = from n$$ in new int[] { 1, 2, 3, 4, 5 } select n; } }", MainDescription($"({FeaturesResources.range_variable}) ? n")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Query5() { await TestAsync( @"using System.Collections.Generic; using System.Linq; class C { void M() { var q = from n in new List<object>() select $$n; } }", MainDescription($"({FeaturesResources.range_variable}) object n")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Query6() { await TestAsync( @"using System.Collections.Generic; using System.Linq; class C { void M() { var q = from n$$ in new List<object>() select n; } }", MainDescription($"({FeaturesResources.range_variable}) object n")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Query7() { await TestAsync( @"using System.Collections.Generic; using System.Linq; class C { void M() { var q = from int n in new List<object>() select $$n; } }", MainDescription($"({FeaturesResources.range_variable}) int n")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Query8() { await TestAsync( @"using System.Collections.Generic; using System.Linq; class C { void M() { var q = from int n$$ in new List<object>() select n; } }", MainDescription($"({FeaturesResources.range_variable}) int n")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Query9() { await TestAsync( @"using System.Collections.Generic; using System.Linq; class C { void M() { var q = from x$$ in new List<List<int>>() from y in x select y; } }", MainDescription($"({FeaturesResources.range_variable}) List<int> x")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Query10() { await TestAsync( @"using System.Collections.Generic; using System.Linq; class C { void M() { var q = from x in new List<List<int>>() from y in $$x select y; } }", MainDescription($"({FeaturesResources.range_variable}) List<int> x")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Query11() { await TestAsync( @"using System.Collections.Generic; using System.Linq; class C { void M() { var q = from x in new List<List<int>>() from y$$ in x select y; } }", MainDescription($"({FeaturesResources.range_variable}) int y")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Query12() { await TestAsync( @"using System.Collections.Generic; using System.Linq; class C { void M() { var q = from x in new List<List<int>>() from y in x select $$y; } }", MainDescription($"({FeaturesResources.range_variable}) int y")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoSelectMappedEnumerable() { await TestInMethodAsync( @" var q = from i in new int[0] $$select i; ", MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.Select<int, int>(Func<int, int> selector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoSelectMappedQueryable() { await TestInMethodAsync( @" var q = from i in new int[0].AsQueryable() $$select i; ", MainDescription($"({CSharpFeaturesResources.extension}) IQueryable<int> IQueryable<int>.Select<int, int>(System.Linq.Expressions.Expression<Func<int, int>> selector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoSelectMappedCustom() { await TestAsync( @" using System; using System.Linq; namespace N { public static class LazyExt { public static Lazy<U> Select<T, U>(this Lazy<T> source, Func<T, U> selector) => new Lazy<U>(() => selector(source.Value)); } public class C { public void M() { var lazy = new Lazy<object>(); var q = from i in lazy $$select i; } } } ", MainDescription($"({CSharpFeaturesResources.extension}) Lazy<object> Lazy<object>.Select<object, object>(Func<object, object> selector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoSelectNotMapped() { await TestInMethodAsync( @" var q = from i in new int[0] where true $$select i; "); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoLet() { await TestInMethodAsync( @" var q = from i in new int[0] $$let j = true select i; ", MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<'a> IEnumerable<int>.Select<int, 'a>(Func<int, 'a> selector)"), AnonymousTypes($@" {FeaturesResources.Anonymous_Types_colon} 'a {FeaturesResources.is_} new {{ int i, bool j }}")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoWhere() { await TestInMethodAsync( @" var q = from i in new int[0] $$where true select i; ", MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.Where<int>(Func<int, bool> predicate)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoOrderByOneProperty() { await TestInMethodAsync( @" var q = from i in new int[0] $$orderby i select i; ", MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable<int> IEnumerable<int>.OrderBy<int, int>(Func<int, int> keySelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoOrderByOnePropertyWithOrdering1() { await TestInMethodAsync( @" var q = from i in new int[0] orderby i $$ascending select i; ", MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable<int> IEnumerable<int>.OrderBy<int, int>(Func<int, int> keySelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoOrderByOnePropertyWithOrdering2() { await TestInMethodAsync( @" var q = from i in new int[0] $$orderby i ascending select i; "); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoOrderByTwoPropertiesWithComma1() { await TestInMethodAsync( @" var q = from i in new int[0] orderby i$$, i select i; ", MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable<int> IOrderedEnumerable<int>.ThenBy<int, int>(Func<int, int> keySelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoOrderByTwoPropertiesWithComma2() { await TestInMethodAsync( @" var q = from i in new int[0] $$orderby i, i select i; ", MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable<int> IEnumerable<int>.OrderBy<int, int>(Func<int, int> keySelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoOrderByTwoPropertiesWithOrdering1() { await TestInMethodAsync( @" var q = from i in new int[0] $$orderby i, i ascending select i; ", MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable<int> IEnumerable<int>.OrderBy<int, int>(Func<int, int> keySelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoOrderByTwoPropertiesWithOrdering2() { await TestInMethodAsync( @" var q = from i in new int[0] orderby i,$$ i ascending select i; "); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoOrderByTwoPropertiesWithOrdering3() { await TestInMethodAsync( @" var q = from i in new int[0] orderby i, i $$ascending select i; ", MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable<int> IOrderedEnumerable<int>.ThenBy<int, int>(Func<int, int> keySelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoOrderByTwoPropertiesWithOrderingOnEach1() { await TestInMethodAsync( @" var q = from i in new int[0] $$orderby i ascending, i ascending select i; "); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoOrderByTwoPropertiesWithOrderingOnEach2() { await TestInMethodAsync( @" var q = from i in new int[0] orderby i $$ascending, i ascending select i; ", MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable<int> IEnumerable<int>.OrderBy<int, int>(Func<int, int> keySelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoOrderByTwoPropertiesWithOrderingOnEach3() { await TestInMethodAsync( @" var q = from i in new int[0] orderby i ascending ,$$ i ascending select i; "); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoOrderByTwoPropertiesWithOrderingOnEach4() { await TestInMethodAsync( @" var q = from i in new int[0] orderby i ascending, i $$ascending select i; ", MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable<int> IOrderedEnumerable<int>.ThenBy<int, int>(Func<int, int> keySelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoOrderByIncomplete() { await TestInMethodAsync( @" var q = from i in new int[0] where i > 0 orderby$$ ", MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable<int> IEnumerable<int>.OrderBy<int, ?>(Func<int, ?> keySelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoSelectMany1() { await TestInMethodAsync( @" var q = from i1 in new int[0] $$from i2 in new int[0] select i1; ", MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.SelectMany<int, int, int>(Func<int, IEnumerable<int>> collectionSelector, Func<int, int, int> resultSelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoSelectMany2() { await TestInMethodAsync( @" var q = from i1 in new int[0] from i2 $$in new int[0] select i1; ", MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.SelectMany<int, int, int>(Func<int, IEnumerable<int>> collectionSelector, Func<int, int, int> resultSelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoGroupBy1() { await TestInMethodAsync( @" var q = from i in new int[0] $$group i by i; ", MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<IGrouping<int, int>> IEnumerable<int>.GroupBy<int, int>(Func<int, int> keySelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoGroupBy2() { await TestInMethodAsync( @" var q = from i in new int[0] group i $$by i; ", MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<IGrouping<int, int>> IEnumerable<int>.GroupBy<int, int>(Func<int, int> keySelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoGroupByInto() { await TestInMethodAsync( @" var q = from i in new int[0] $$group i by i into g select g; ", MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<IGrouping<int, int>> IEnumerable<int>.GroupBy<int, int>(Func<int, int> keySelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoJoin1() { await TestInMethodAsync( @" var q = from i1 in new int[0] $$join i2 in new int[0] on i1 equals i2 select i1; ", MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.Join<int, int, int, int>(IEnumerable<int> inner, Func<int, int> outerKeySelector, Func<int, int> innerKeySelector, Func<int, int, int> resultSelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoJoin2() { await TestInMethodAsync( @" var q = from i1 in new int[0] join i2 $$in new int[0] on i1 equals i2 select i1; ", MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.Join<int, int, int, int>(IEnumerable<int> inner, Func<int, int> outerKeySelector, Func<int, int> innerKeySelector, Func<int, int, int> resultSelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoJoin3() { await TestInMethodAsync( @" var q = from i1 in new int[0] join i2 in new int[0] $$on i1 equals i2 select i1; ", MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.Join<int, int, int, int>(IEnumerable<int> inner, Func<int, int> outerKeySelector, Func<int, int> innerKeySelector, Func<int, int, int> resultSelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoJoin4() { await TestInMethodAsync( @" var q = from i1 in new int[0] join i2 in new int[0] on i1 $$equals i2 select i1; ", MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.Join<int, int, int, int>(IEnumerable<int> inner, Func<int, int> outerKeySelector, Func<int, int> innerKeySelector, Func<int, int, int> resultSelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoJoinInto1() { await TestInMethodAsync( @" var q = from i1 in new int[0] $$join i2 in new int[0] on i1 equals i2 into g select g; ", MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<IEnumerable<int>> IEnumerable<int>.GroupJoin<int, int, int, IEnumerable<int>>(IEnumerable<int> inner, Func<int, int> outerKeySelector, Func<int, int> innerKeySelector, Func<int, IEnumerable<int>, IEnumerable<int>> resultSelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoJoinInto2() { await TestInMethodAsync( @" var q = from i1 in new int[0] join i2 in new int[0] on i1 equals i2 $$into g select g; "); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoFromMissing() { await TestInMethodAsync( @" var q = $$from i in new int[0] select i; "); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoRangeVariableSimple1() { await TestInMethodAsync( @" var q = $$from double i in new int[0] select i; ", MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<double> System.Collections.IEnumerable.Cast<double>()")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoRangeVariableSimple2() { await TestInMethodAsync( @" var q = from double i $$in new int[0] select i; ", MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<double> System.Collections.IEnumerable.Cast<double>()")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoRangeVariableSelectMany1() { await TestInMethodAsync( @" var q = from i in new int[0] $$from double d in new int[0] select i; ", MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.SelectMany<int, double, int>(Func<int, IEnumerable<double>> collectionSelector, Func<int, double, int> resultSelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoRangeVariableSelectMany2() { await TestInMethodAsync( @" var q = from i in new int[0] from double d $$in new int[0] select i; ", MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<double> System.Collections.IEnumerable.Cast<double>()")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoRangeVariableJoin1() { await TestInMethodAsync( @" var q = from i1 in new int[0] $$join int i2 in new double[0] on i1 equals i2 select i1; ", MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.Join<int, int, int, int>(IEnumerable<int> inner, Func<int, int> outerKeySelector, Func<int, int> innerKeySelector, Func<int, int, int> resultSelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoRangeVariableJoin2() { await TestInMethodAsync( @" var q = from i1 in new int[0] join int i2 $$in new double[0] on i1 equals i2 select i1; ", MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> System.Collections.IEnumerable.Cast<int>()")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoRangeVariableJoin3() { await TestInMethodAsync( @" var q = from i1 in new int[0] join int i2 in new double[0] $$on i1 equals i2 select i1; ", MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.Join<int, int, int, int>(IEnumerable<int> inner, Func<int, int> outerKeySelector, Func<int, int> innerKeySelector, Func<int, int, int> resultSelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoRangeVariableJoin4() { await TestInMethodAsync( @" var q = from i1 in new int[0] join int i2 in new double[0] on i1 $$equals i2 select i1; ", MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.Join<int, int, int, int>(IEnumerable<int> inner, Func<int, int> outerKeySelector, Func<int, int> innerKeySelector, Func<int, int, int> resultSelector)")); } [WorkItem(543205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543205")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestErrorGlobal() { await TestAsync( @"extern alias global; class myClass { static int Main() { $$global::otherClass oc = new global::otherClass(); return 0; } }", MainDescription("<global namespace>")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task DontRemoveAttributeSuffixAndProduceInvalidIdentifier1() { await TestAsync( @"using System; class classAttribute : Attribute { private classAttribute x$$; }", MainDescription($"({FeaturesResources.field}) classAttribute classAttribute.x")); } [WorkItem(544026, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544026")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task DontRemoveAttributeSuffix2() { await TestAsync( @"using System; class class1Attribute : Attribute { private class1Attribute x$$; }", MainDescription($"({FeaturesResources.field}) class1Attribute class1Attribute.x")); } [WorkItem(1696, "https://github.com/dotnet/roslyn/issues/1696")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task AttributeQuickInfoBindsToClassTest() { await TestAsync( @"using System; /// <summary> /// class comment /// </summary> [Some$$] class SomeAttribute : Attribute { /// <summary> /// ctor comment /// </summary> public SomeAttribute() { } }", Documentation("class comment")); } [WorkItem(1696, "https://github.com/dotnet/roslyn/issues/1696")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task AttributeConstructorQuickInfo() { await TestAsync( @"using System; /// <summary> /// class comment /// </summary> class SomeAttribute : Attribute { /// <summary> /// ctor comment /// </summary> public SomeAttribute() { var s = new Some$$Attribute(); } }", Documentation("ctor comment")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestLabel() { await TestInClassAsync( @"void M() { Goo: int Goo; goto Goo$$; }", MainDescription($"({FeaturesResources.label}) Goo")); } [WorkItem(542613, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542613")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestUnboundGeneric() { await TestAsync( @"using System; using System.Collections.Generic; class C { void M() { Type t = typeof(L$$ist<>); } }", MainDescription("class System.Collections.Generic.List<T>"), NoTypeParameterMap); } [WorkItem(543113, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543113")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestAnonymousTypeNew1() { await TestAsync( @"class C { void M() { var v = $$new { }; } }", MainDescription(@"AnonymousType 'a"), NoTypeParameterMap, AnonymousTypes( $@" {FeaturesResources.Anonymous_Types_colon} 'a {FeaturesResources.is_} new {{ }}")); } [WorkItem(543873, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543873")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestNestedAnonymousType() { // verify nested anonymous types are listed in the same order for different properties // verify first property await TestInMethodAsync( @"var x = new[] { new { Name = ""BillG"", Address = new { Street = ""1 Microsoft Way"", Zip = ""98052"" } } }; x[0].$$Address", MainDescription(@"'b 'a.Address { get; }"), NoTypeParameterMap, AnonymousTypes( $@" {FeaturesResources.Anonymous_Types_colon} 'a {FeaturesResources.is_} new {{ string Name, 'b Address }} 'b {FeaturesResources.is_} new {{ string Street, string Zip }}")); // verify second property await TestInMethodAsync( @"var x = new[] { new { Name = ""BillG"", Address = new { Street = ""1 Microsoft Way"", Zip = ""98052"" } } }; x[0].$$Name", MainDescription(@"string 'a.Name { get; }"), NoTypeParameterMap, AnonymousTypes( $@" {FeaturesResources.Anonymous_Types_colon} 'a {FeaturesResources.is_} new {{ string Name, 'b Address }} 'b {FeaturesResources.is_} new {{ string Street, string Zip }}")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(543183, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543183")] public async Task TestAssignmentOperatorInAnonymousType() { await TestAsync( @"class C { void M() { var a = new { A $$= 0 }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(10731, "DevDiv_Projects/Roslyn")] public async Task TestErrorAnonymousTypeDoesntShow() { await TestInMethodAsync( @"var a = new { new { N = 0 }.N, new { } }.$$N;", MainDescription(@"int 'a.N { get; }"), NoTypeParameterMap, AnonymousTypes( $@" {FeaturesResources.Anonymous_Types_colon} 'a {FeaturesResources.is_} new {{ int N }}")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(543553, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543553")] public async Task TestArrayAssignedToVar() { await TestAsync( @"class C { static void M(string[] args) { v$$ar a = args; } }", MainDescription("string[]")); } [WorkItem(529139, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529139")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ColorColorRangeVariable() { await TestAsync( @"using System.Collections.Generic; using System.Linq; namespace N1 { class yield { public static IEnumerable<yield> Bar() { foreach (yield yield in from yield in new yield[0] select y$$ield) { yield return yield; } } } }", MainDescription($"({FeaturesResources.range_variable}) N1.yield yield")); } [WorkItem(543550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543550")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task QuickInfoOnOperator() { await TestAsync( @"using System.Collections.Generic; class Program { static void Main(string[] args) { var v = new Program() $$+ string.Empty; } public static implicit operator Program(string s) { return null; } public static IEnumerable<Program> operator +(Program p1, Program p2) { yield return p1; yield return p2; } }", MainDescription("IEnumerable<Program> Program.operator +(Program p1, Program p2)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestConstantField() { await TestAsync( @"class C { const int $$F = 1;", MainDescription($"({FeaturesResources.constant}) int C.F = 1")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestMultipleConstantFields() { await TestAsync( @"class C { public const double X = 1.0, Y = 2.0, $$Z = 3.5;", MainDescription($"({FeaturesResources.constant}) double C.Z = 3.5")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestConstantDependencies() { await TestAsync( @"class A { public const int $$X = B.Z + 1; public const int Y = 10; } class B { public const int Z = A.Y + 1; }", MainDescription($"({FeaturesResources.constant}) int A.X = B.Z + 1")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestConstantCircularDependencies() { await TestAsync( @"class A { public const int X = B.Z + 1; } class B { public const int Z$$ = A.X + 1; }", MainDescription($"({FeaturesResources.constant}) int B.Z = A.X + 1")); } [WorkItem(544620, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544620")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestConstantOverflow() { await TestAsync( @"class B { public const int Z$$ = int.MaxValue + 1; }", MainDescription($"({FeaturesResources.constant}) int B.Z = int.MaxValue + 1")); } [WorkItem(544620, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544620")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestConstantOverflowInUncheckedContext() { await TestAsync( @"class B { public const int Z$$ = unchecked(int.MaxValue + 1); }", MainDescription($"({FeaturesResources.constant}) int B.Z = unchecked(int.MaxValue + 1)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestEnumInConstantField() { await TestAsync( @"public class EnumTest { enum Days { Sun, Mon, Tue, Wed, Thu, Fri, Sat }; static void Main() { const int $$x = (int)Days.Sun; } }", MainDescription($"({FeaturesResources.local_constant}) int x = (int)Days.Sun")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestConstantInDefaultExpression() { await TestAsync( @"public class EnumTest { enum Days { Sun, Mon, Tue, Wed, Thu, Fri, Sat }; static void Main() { const Days $$x = default(Days); } }", MainDescription($"({FeaturesResources.local_constant}) Days x = default(Days)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestConstantParameter() { await TestAsync( @"class C { void Bar(int $$b = 1); }", MainDescription($"({FeaturesResources.parameter}) int b = 1")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestConstantLocal() { await TestAsync( @"class C { void Bar() { const int $$loc = 1; }", MainDescription($"({FeaturesResources.local_constant}) int loc = 1")); } [WorkItem(544416, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544416")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestErrorType1() { await TestInMethodAsync( @"var $$v1 = new Goo();", MainDescription($"({FeaturesResources.local_variable}) Goo v1")); } [WorkItem(544416, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544416")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestErrorType2() { await TestInMethodAsync( @"var $$v1 = v1;", MainDescription($"({FeaturesResources.local_variable}) var v1")); } [WorkItem(544416, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544416")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestErrorType3() { await TestInMethodAsync( @"var $$v1 = new Goo<Bar>();", MainDescription($"({FeaturesResources.local_variable}) Goo<Bar> v1")); } [WorkItem(544416, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544416")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestErrorType4() { await TestInMethodAsync( @"var $$v1 = &(x => x);", MainDescription($"({FeaturesResources.local_variable}) ?* v1")); } [WorkItem(544416, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544416")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestErrorType5() { await TestInMethodAsync("var $$v1 = &v1", MainDescription($"({FeaturesResources.local_variable}) var* v1")); } [WorkItem(544416, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544416")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestErrorType6() { await TestInMethodAsync("var $$v1 = new Goo[1]", MainDescription($"({FeaturesResources.local_variable}) Goo[] v1")); } [WorkItem(544416, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544416")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestErrorType7() { await TestInClassAsync( @"class C { void Method() { } void Goo() { var $$v1 = MethodGroup; } }", MainDescription($"({FeaturesResources.local_variable}) ? v1")); } [WorkItem(544416, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544416")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestErrorType8() { await TestInMethodAsync("var $$v1 = Unknown", MainDescription($"({FeaturesResources.local_variable}) ? v1")); } [WorkItem(545072, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545072")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestDelegateSpecialTypes() { await TestAsync( @"delegate void $$F(int x);", MainDescription("delegate void F(int x)")); } [WorkItem(545108, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545108")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestNullPointerParameter() { await TestAsync( @"class C { unsafe void $$Goo(int* x = null) { } }", MainDescription("void C.Goo([int* x = null])")); } [WorkItem(545098, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545098")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestLetIdentifier1() { await TestInMethodAsync("var q = from e in \"\" let $$y = 1 let a = new { y } select a;", MainDescription($"({FeaturesResources.range_variable}) int y")); } [WorkItem(545295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545295")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestNullableDefaultValue() { await TestAsync( @"class Test { void $$Method(int? t1 = null) { } }", MainDescription("void Test.Method([int? t1 = null])")); } [WorkItem(529586, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529586")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestInvalidParameterInitializer() { await TestAsync( @"class Program { void M1(float $$j1 = ""Hello"" + ""World"") { } }", MainDescription($@"({FeaturesResources.parameter}) float j1 = ""Hello"" + ""World""")); } [WorkItem(545230, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545230")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestComplexConstLocal() { await TestAsync( @"class Program { void Main() { const int MEGABYTE = 1024 * 1024 + true; Blah($$MEGABYTE); } }", MainDescription($@"({FeaturesResources.local_constant}) int MEGABYTE = 1024 * 1024 + true")); } [WorkItem(545230, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545230")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestComplexConstField() { await TestAsync( @"class Program { const int a = true - false; void Main() { Goo($$a); } }", MainDescription($"({FeaturesResources.constant}) int Program.a = true - false")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestTypeParameterCrefDoesNotHaveQuickInfo() { await TestAsync( @"class C<T> { /// <see cref=""C{X$$}""/> static void Main(string[] args) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestCref1() { await TestAsync( @"class Program { /// <see cref=""Mai$$n""/> static void Main(string[] args) { } }", MainDescription(@"void Program.Main(string[] args)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestCref2() { await TestAsync( @"class Program { /// <see cref=""$$Main""/> static void Main(string[] args) { } }", MainDescription(@"void Program.Main(string[] args)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestCref3() { await TestAsync( @"class Program { /// <see cref=""Main""$$/> static void Main(string[] args) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestCref4() { await TestAsync( @"class Program { /// <see cref=""Main$$""/> static void Main(string[] args) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestCref5() { await TestAsync( @"class Program { /// <see cref=""Main""$$/> static void Main(string[] args) { } }"); } [WorkItem(546849, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546849")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestIndexedProperty() { var markup = @"class Program { void M() { CCC c = new CCC(); c.Index$$Prop[0] = ""s""; } }"; // Note that <COMImport> is required by compiler. Bug 17013 tracks enabling indexed property for non-COM types. var referencedCode = @"Imports System.Runtime.InteropServices <ComImport()> <GuidAttribute(CCC.ClassId)> Public Class CCC #Region ""COM GUIDs"" Public Const ClassId As String = ""9d965fd2-1514-44f6-accd-257ce77c46b0"" Public Const InterfaceId As String = ""a9415060-fdf0-47e3-bc80-9c18f7f39cf6"" Public Const EventsId As String = ""c6a866a5-5f97-4b53-a5df-3739dc8ff1bb"" # End Region ''' <summary> ''' An index property from VB ''' </summary> ''' <param name=""p1"">p1 is an integer index</param> ''' <returns>A string</returns> Public Property IndexProp(ByVal p1 As Integer, Optional ByVal p2 As Integer = 0) As String Get Return Nothing End Get Set(ByVal value As String) End Set End Property End Class"; await TestWithReferenceAsync(sourceCode: markup, referencedCode: referencedCode, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.VisualBasic, expectedResults: MainDescription("string CCC.IndexProp[int p1, [int p2 = 0]] { get; set; }")); } [WorkItem(546918, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546918")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestUnconstructedGeneric() { await TestAsync( @"class A<T> { enum SortOrder { Ascending, Descending, None } void Goo() { var b = $$SortOrder.Ascending; } }", MainDescription(@"enum A<T>.SortOrder")); } [WorkItem(546970, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546970")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestUnconstructedGenericInCRef() { await TestAsync( @"/// <see cref=""$$C{T}"" /> class C<T> { }", MainDescription(@"class C<T>")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestAwaitableMethod() { var markup = @"using System.Threading.Tasks; class C { async Task Goo() { Go$$o(); } }"; var description = $"({CSharpFeaturesResources.awaitable}) Task C.Goo()"; await VerifyWithMscorlib45Async(markup, new[] { MainDescription(description) }); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ObsoleteItem() { var markup = @" using System; class Program { [Obsolete] public void goo() { go$$o(); } }"; await TestAsync(markup, MainDescription($"[{CSharpFeaturesResources.deprecated}] void Program.goo()")); } [WorkItem(751070, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/751070")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task DynamicOperator() { var markup = @" public class Test { public delegate void NoParam(); static int Main() { dynamic x = new object(); if (((System.Func<dynamic>)(() => (x =$$= null)))()) return 0; return 1; } }"; await TestAsync(markup, MainDescription("dynamic dynamic.operator ==(dynamic left, dynamic right)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TextOnlyDocComment() { await TestAsync( @"/// <summary> ///goo /// </summary> class C$$ { }", Documentation("goo")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestTrimConcatMultiLine() { await TestAsync( @"/// <summary> /// goo /// bar /// </summary> class C$$ { }", Documentation("goo bar")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestCref() { await TestAsync( @"/// <summary> /// <see cref=""C""/> /// <seealso cref=""C""/> /// </summary> class C$$ { }", Documentation("C C")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ExcludeTextOutsideSummaryBlock() { await TestAsync( @"/// red /// <summary> /// green /// </summary> /// yellow class C$$ { }", Documentation("green")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NewlineAfterPara() { await TestAsync( @"/// <summary> /// <para>goo</para> /// </summary> class C$$ { }", Documentation("goo")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TextOnlyDocComment_Metadata() { var referenced = @" /// <summary> ///goo /// </summary> public class C { }"; var code = @" class G { void goo() { C$$ c; } }"; await TestWithMetadataReferenceHelperAsync(code, referenced, "C#", "C#", Documentation("goo")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestTrimConcatMultiLine_Metadata() { var referenced = @" /// <summary> /// goo /// bar /// </summary> public class C { }"; var code = @" class G { void goo() { C$$ c; } }"; await TestWithMetadataReferenceHelperAsync(code, referenced, "C#", "C#", Documentation("goo bar")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestCref_Metadata() { var code = @" class G { void goo() { C$$ c; } }"; var referenced = @"/// <summary> /// <see cref=""C""/> /// <seealso cref=""C""/> /// </summary> public class C { }"; await TestWithMetadataReferenceHelperAsync(code, referenced, "C#", "C#", Documentation("C C")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ExcludeTextOutsideSummaryBlock_Metadata() { var code = @" class G { void goo() { C$$ c; } }"; var referenced = @" /// red /// <summary> /// green /// </summary> /// yellow public class C { }"; await TestWithMetadataReferenceHelperAsync(code, referenced, "C#", "C#", Documentation("green")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Param() { await TestAsync( @"/// <summary></summary> public class C { /// <typeparam name=""T"">A type parameter of <see cref=""goo{ T} (string[], T)""/></typeparam> /// <param name=""args"">First parameter of <see cref=""Goo{T} (string[], T)""/></param> /// <param name=""otherParam"">Another parameter of <see cref=""Goo{T}(string[], T)""/></param> public void Goo<T>(string[] arg$$s, T otherParam) { } }", Documentation("First parameter of C.Goo<T>(string[], T)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Param_Metadata() { var code = @" class G { void goo() { C c; c.Goo<int>(arg$$s: new string[] { }, 1); } }"; var referenced = @" /// <summary></summary> public class C { /// <typeparam name=""T"">A type parameter of <see cref=""goo{ T} (string[], T)""/></typeparam> /// <param name=""args"">First parameter of <see cref=""Goo{T} (string[], T)""/></param> /// <param name=""otherParam"">Another parameter of <see cref=""Goo{T}(string[], T)""/></param> public void Goo<T>(string[] args, T otherParam) { } }"; await TestWithMetadataReferenceHelperAsync(code, referenced, "C#", "C#", Documentation("First parameter of C.Goo<T>(string[], T)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Param2() { await TestAsync( @"/// <summary></summary> public class C { /// <typeparam name=""T"">A type parameter of <see cref=""goo{ T} (string[], T)""/></typeparam> /// <param name=""args"">First parameter of <see cref=""Goo{T} (string[], T)""/></param> /// <param name=""otherParam"">Another parameter of <see cref=""Goo{T}(string[], T)""/></param> public void Goo<T>(string[] args, T oth$$erParam) { } }", Documentation("Another parameter of C.Goo<T>(string[], T)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Param2_Metadata() { var code = @" class G { void goo() { C c; c.Goo<int>(args: new string[] { }, other$$Param: 1); } }"; var referenced = @" /// <summary></summary> public class C { /// <typeparam name=""T"">A type parameter of <see cref=""goo{ T} (string[], T)""/></typeparam> /// <param name=""args"">First parameter of <see cref=""Goo{T} (string[], T)""/></param> /// <param name=""otherParam"">Another parameter of <see cref=""Goo{T}(string[], T)""/></param> public void Goo<T>(string[] args, T otherParam) { } }"; await TestWithMetadataReferenceHelperAsync(code, referenced, "C#", "C#", Documentation("Another parameter of C.Goo<T>(string[], T)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TypeParam() { await TestAsync( @"/// <summary></summary> public class C { /// <typeparam name=""T"">A type parameter of <see cref=""Goo{T} (string[], T)""/></typeparam> /// <param name=""args"">First parameter of <see cref=""Goo{T} (string[], T)""/></param> /// <param name=""otherParam"">Another parameter of <see cref=""Goo{T}(string[], T)""/></param> public void Goo<T$$>(string[] args, T otherParam) { } }", Documentation("A type parameter of C.Goo<T>(string[], T)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task UnboundCref() { await TestAsync( @"/// <summary></summary> public class C { /// <typeparam name=""T"">A type parameter of <see cref=""goo{T}(string[], T)""/></typeparam> /// <param name=""args"">First parameter of <see cref=""Goo{T} (string[], T)""/></param> /// <param name=""otherParam"">Another parameter of <see cref=""Goo{T}(string[], T)""/></param> public void Goo<T$$>(string[] args, T otherParam) { } }", Documentation("A type parameter of goo<T>(string[], T)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task CrefInConstructor() { await TestAsync( @"public class TestClass { /// <summary> /// This sample shows how to specify the <see cref=""TestClass""/> constructor as a cref attribute. /// </summary> public TestClass$$() { } }", Documentation("This sample shows how to specify the TestClass constructor as a cref attribute.")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task CrefInConstructorOverloaded() { await TestAsync( @"public class TestClass { /// <summary> /// This sample shows how to specify the <see cref=""TestClass""/> constructor as a cref attribute. /// </summary> public TestClass() { } /// <summary> /// This sample shows how to specify the <see cref=""TestClass(int)""/> constructor as a cref attribute. /// </summary> public TestC$$lass(int value) { } }", Documentation("This sample shows how to specify the TestClass(int) constructor as a cref attribute.")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task CrefInGenericMethod1() { await TestAsync( @"public class TestClass { /// <summary> /// The GetGenericValue method. /// <para>This sample shows how to specify the <see cref=""GetGenericValue""/> method as a cref attribute.</para> /// </summary> public static T GetGenericVa$$lue<T>(T para) { return para; } }", Documentation("The GetGenericValue method.\r\n\r\nThis sample shows how to specify the TestClass.GetGenericValue<T>(T) method as a cref attribute.")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task CrefInGenericMethod2() { await TestAsync( @"public class TestClass { /// <summary> /// The GetGenericValue method. /// <para>This sample shows how to specify the <see cref=""GetGenericValue{T}(T)""/> method as a cref attribute.</para> /// </summary> public static T GetGenericVa$$lue<T>(T para) { return para; } }", Documentation("The GetGenericValue method.\r\n\r\nThis sample shows how to specify the TestClass.GetGenericValue<T>(T) method as a cref attribute.")); } [WorkItem(813350, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/813350")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task CrefInMethodOverloading1() { await TestAsync( @"public class TestClass { public static int GetZero() { GetGenericValu$$e(); GetGenericValue(5); } /// <summary> /// This sample shows how to call the <see cref=""GetGenericValue{T}(T)""/> method /// </summary> public static T GetGenericValue<T>(T para) { return para; } /// <summary> /// This sample shows how to specify the <see cref=""GetGenericValue""/> method as a cref attribute. /// </summary> public static void GetGenericValue() { } }", Documentation("This sample shows how to specify the TestClass.GetGenericValue() method as a cref attribute.")); } [WorkItem(813350, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/813350")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task CrefInMethodOverloading2() { await TestAsync( @"public class TestClass { public static int GetZero() { GetGenericValue(); GetGenericVal$$ue(5); } /// <summary> /// This sample shows how to call the <see cref=""GetGenericValue{T}(T)""/> method /// </summary> public static T GetGenericValue<T>(T para) { return para; } /// <summary> /// This sample shows how to specify the <see cref=""GetGenericValue""/> method as a cref attribute. /// </summary> public static void GetGenericValue() { } }", Documentation("This sample shows how to call the TestClass.GetGenericValue<T>(T) method")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task CrefInGenericType() { await TestAsync( @"/// <summary> /// <remarks>This example shows how to specify the <see cref=""GenericClass{T}""/> cref.</remarks> /// </summary> class Generic$$Class<T> { }", Documentation("This example shows how to specify the GenericClass<T> cref.", ExpectedClassifications( Text("This example shows how to specify the"), WhiteSpace(" "), Class("GenericClass"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, WhiteSpace(" "), Text("cref.")))); } [WorkItem(812720, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/812720")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ClassificationOfCrefsFromMetadata() { var code = @" class G { void goo() { C c; c.Go$$o(); } }"; var referenced = @" /// <summary></summary> public class C { /// <summary> /// See <see cref=""Goo""/> method /// </summary> public void Goo() { } }"; await TestWithMetadataReferenceHelperAsync(code, referenced, "C#", "C#", Documentation("See C.Goo() method", ExpectedClassifications( Text("See"), WhiteSpace(" "), Class("C"), Punctuation.Text("."), Identifier("Goo"), Punctuation.OpenParen, Punctuation.CloseParen, WhiteSpace(" "), Text("method")))); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task FieldAvailableInBothLinkedFiles() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1""> <Document FilePath=""SourceDocument""><![CDATA[ class C { int x; void goo() { x$$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; await VerifyWithReferenceWorkerAsync(markup, new[] { MainDescription($"({FeaturesResources.field}) int C.x"), Usage("") }); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task FieldUnavailableInOneLinkedFile() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""GOO""> <Document FilePath=""SourceDocument""><![CDATA[ class C { #if GOO int x; #endif void goo() { x$$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; var expectedDescription = Usage($"\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}", expectsWarningGlyph: true); await VerifyWithReferenceWorkerAsync(markup, new[] { expectedDescription }); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(37097, "https://github.com/dotnet/roslyn/issues/37097")] public async Task BindSymbolInOtherFile() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1""> <Document FilePath=""SourceDocument""><![CDATA[ class C { #if GOO int x; #endif void goo() { x$$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""GOO""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; var expectedDescription = Usage($"\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Not_Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}", expectsWarningGlyph: true); await VerifyWithReferenceWorkerAsync(markup, new[] { expectedDescription }); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task FieldUnavailableInTwoLinkedFiles() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""GOO""> <Document FilePath=""SourceDocument""><![CDATA[ class C { #if GOO int x; #endif void goo() { x$$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj3""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; var expectedDescription = Usage( $"\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Not_Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj3", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}", expectsWarningGlyph: true); await VerifyWithReferenceWorkerAsync(markup, new[] { expectedDescription }); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ExcludeFilesWithInactiveRegions() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""GOO,BAR""> <Document FilePath=""SourceDocument""><![CDATA[ class C { #if GOO int x; #endif #if BAR void goo() { x$$ } #endif } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument"" /> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj3"" PreprocessorSymbols=""BAR""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; var expectedDescription = Usage($"\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj3", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}", expectsWarningGlyph: true); await VerifyWithReferenceWorkerAsync(markup, new[] { expectedDescription }); } [WorkItem(962353, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/962353")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NoValidSymbolsInLinkedDocuments() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1""> <Document FilePath=""SourceDocument""><![CDATA[ class C { void goo() { B$$ar(); } #if B void Bar() { } #endif } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; await VerifyWithReferenceWorkerAsync(markup); } [WorkItem(1020944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1020944")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task LocalsValidInLinkedDocuments() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1""> <Document FilePath=""SourceDocument""><![CDATA[ class C { void M() { int x$$; } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; await VerifyWithReferenceWorkerAsync(markup, new[] { MainDescription($"({FeaturesResources.local_variable}) int x"), Usage("") }); } [WorkItem(1020944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1020944")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task LocalWarningInLinkedDocuments() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""PROJ1""> <Document FilePath=""SourceDocument""><![CDATA[ class C { void M() { #if PROJ1 int x; #endif int y = x$$; } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; await VerifyWithReferenceWorkerAsync(markup, new[] { MainDescription($"({FeaturesResources.local_variable}) int x"), Usage($"\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}", expectsWarningGlyph: true) }); } [WorkItem(1020944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1020944")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task LabelsValidInLinkedDocuments() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1""> <Document FilePath=""SourceDocument""><![CDATA[ class C { void M() { $$LABEL: goto LABEL; } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; await VerifyWithReferenceWorkerAsync(markup, new[] { MainDescription($"({FeaturesResources.label}) LABEL"), Usage("") }); } [WorkItem(1020944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1020944")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task RangeVariablesValidInLinkedDocuments() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1""> <Document FilePath=""SourceDocument""><![CDATA[ using System.Linq; class C { void M() { var x = from y in new[] {1, 2, 3} select $$y; } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; await VerifyWithReferenceWorkerAsync(markup, new[] { MainDescription($"({FeaturesResources.range_variable}) int y"), Usage("") }); } [WorkItem(1019766, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1019766")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task PointerAccessibility() { var markup = @"class C { unsafe static void Main() { void* p = null; void* q = null; dynamic d = true; var x = p =$$= q == d; } }"; await TestAsync(markup, MainDescription("bool void*.operator ==(void* left, void* right)")); } [WorkItem(1114300, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1114300")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task AwaitingTaskOfArrayType() { var markup = @" using System.Threading.Tasks; class Program { async Task<int[]> M() { awa$$it M(); } }"; await TestAsync(markup, MainDescription(string.Format(FeaturesResources.Awaited_task_returns_0, "int[]"))); } [WorkItem(1114300, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1114300")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task AwaitingTaskOfDynamic() { var markup = @" using System.Threading.Tasks; class Program { async Task<dynamic> M() { awa$$it M(); } }"; await TestAsync(markup, MainDescription(string.Format(FeaturesResources.Awaited_task_returns_0, "dynamic"))); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MethodOverloadDifferencesIgnored() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""ONE""> <Document FilePath=""SourceDocument""><![CDATA[ class C { #if ONE void Do(int x){} #endif #if TWO void Do(string x){} #endif void Shared() { this.Do$$ } }]]></Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""TWO""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; var expectedDescription = $"void C.Do(int x)"; await VerifyWithReferenceWorkerAsync(markup, MainDescription(expectedDescription)); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MethodOverloadDifferencesIgnored_ContainingType() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""ONE""> <Document FilePath=""SourceDocument""><![CDATA[ class C { void Shared() { var x = GetThing().Do$$(); } #if ONE private Methods1 GetThing() { return new Methods1(); } #endif #if TWO private Methods2 GetThing() { return new Methods2(); } #endif } #if ONE public class Methods1 { public void Do(string x) { } } #endif #if TWO public class Methods2 { public void Do(string x) { } } #endif ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""TWO""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; var expectedDescription = $"void Methods1.Do(string x)"; await VerifyWithReferenceWorkerAsync(markup, MainDescription(expectedDescription)); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(4868, "https://github.com/dotnet/roslyn/issues/4868")] public async Task QuickInfoExceptions() { await TestAsync( @"using System; namespace MyNs { class MyException1 : Exception { } class MyException2 : Exception { } class TestClass { /// <exception cref=""MyException1""></exception> /// <exception cref=""T:MyNs.MyException2""></exception> /// <exception cref=""System.Int32""></exception> /// <exception cref=""double""></exception> /// <exception cref=""Not_A_Class_But_Still_Displayed""></exception> void M() { M$$(); } } }", Exceptions($"\r\n{WorkspacesResources.Exceptions_colon}\r\n MyException1\r\n MyException2\r\n int\r\n double\r\n Not_A_Class_But_Still_Displayed")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23307, "https://github.com/dotnet/roslyn/issues/23307")] public async Task QuickInfoCapturesOnLocalFunction() { await TestAsync(@" class C { void M() { int i; local$$(); void local() { i++; this.M(); } } }", Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this, i")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23307, "https://github.com/dotnet/roslyn/issues/23307")] public async Task QuickInfoCapturesOnLocalFunction2() { await TestAsync(@" class C { void M() { int i; local$$(i); void local(int j) { j++; M(); } } }", Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23307, "https://github.com/dotnet/roslyn/issues/23307")] public async Task QuickInfoCapturesOnLocalFunction3() { await TestAsync(@" class C { public void M(int @this) { int i = 0; local$$(); void local() { M(1); i++; @this++; } } }", Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this, @this, i")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(26101, "https://github.com/dotnet/roslyn/issues/26101")] public async Task QuickInfoCapturesOnLocalFunction4() { await TestAsync(@" class C { int field; void M() { void OuterLocalFunction$$() { int local = 0; int InnerLocalFunction() { field++; return local; } } } }", Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(26101, "https://github.com/dotnet/roslyn/issues/26101")] public async Task QuickInfoCapturesOnLocalFunction5() { await TestAsync(@" class C { int field; void M() { void OuterLocalFunction() { int local = 0; int InnerLocalFunction$$() { field++; return local; } } } }", Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this, local")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(26101, "https://github.com/dotnet/roslyn/issues/26101")] public async Task QuickInfoCapturesOnLocalFunction6() { await TestAsync(@" class C { int field; void M() { int local1 = 0; int local2 = 0; void OuterLocalFunction$$() { _ = local1; void InnerLocalFunction() { _ = local2; } } } }", Captures($"\r\n{WorkspacesResources.Variables_captured_colon} local1, local2")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(26101, "https://github.com/dotnet/roslyn/issues/26101")] public async Task QuickInfoCapturesOnLocalFunction7() { await TestAsync(@" class C { int field; void M() { int local1 = 0; int local2 = 0; void OuterLocalFunction() { _ = local1; void InnerLocalFunction$$() { _ = local2; } } } }", Captures($"\r\n{WorkspacesResources.Variables_captured_colon} local2")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23307, "https://github.com/dotnet/roslyn/issues/23307")] public async Task QuickInfoCapturesOnLambda() { await TestAsync(@" class C { void M() { int i; System.Action a = () =$$> { i++; M(); }; } }", Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this, i")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23307, "https://github.com/dotnet/roslyn/issues/23307")] public async Task QuickInfoCapturesOnLambda2() { await TestAsync(@" class C { void M() { int i; System.Action<int> a = j =$$> { i++; j++; M(); }; } }", Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this, i")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23307, "https://github.com/dotnet/roslyn/issues/23307")] public async Task QuickInfoCapturesOnLambda2_DifferentOrder() { await TestAsync(@" class C { void M(int j) { int i; System.Action a = () =$$> { M(); i++; j++; }; } }", Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this, j, i")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23307, "https://github.com/dotnet/roslyn/issues/23307")] public async Task QuickInfoCapturesOnLambda3() { await TestAsync(@" class C { void M() { int i; int @this; N(() =$$> { M(); @this++; }, () => { i++; }); } void N(System.Action x, System.Action y) { } }", Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this, @this")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23307, "https://github.com/dotnet/roslyn/issues/23307")] public async Task QuickInfoCapturesOnLambda4() { await TestAsync(@" class C { void M() { int i; N(() => { M(); }, () =$$> { i++; }); } void N(System.Action x, System.Action y) { } }", Captures($"\r\n{WorkspacesResources.Variables_captured_colon} i")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(26101, "https://github.com/dotnet/roslyn/issues/26101")] public async Task QuickInfoCapturesOnLambda5() { await TestAsync(@" class C { int field; void M() { System.Action a = () =$$> { int local = 0; System.Func<int> b = () => { field++; return local; }; }; } }", Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(26101, "https://github.com/dotnet/roslyn/issues/26101")] public async Task QuickInfoCapturesOnLambda6() { await TestAsync(@" class C { int field; void M() { System.Action a = () => { int local = 0; System.Func<int> b = () =$$> { field++; return local; }; }; } }", Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this, local")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(26101, "https://github.com/dotnet/roslyn/issues/26101")] public async Task QuickInfoCapturesOnLambda7() { await TestAsync(@" class C { int field; void M() { int local1 = 0; int local2 = 0; System.Action a = () =$$> { _ = local1; System.Action b = () => { _ = local2; }; }; } }", Captures($"\r\n{WorkspacesResources.Variables_captured_colon} local1, local2")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(26101, "https://github.com/dotnet/roslyn/issues/26101")] public async Task QuickInfoCapturesOnLambda8() { await TestAsync(@" class C { int field; void M() { int local1 = 0; int local2 = 0; System.Action a = () => { _ = local1; System.Action b = () =$$> { _ = local2; }; }; } }", Captures($"\r\n{WorkspacesResources.Variables_captured_colon} local2")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23307, "https://github.com/dotnet/roslyn/issues/23307")] public async Task QuickInfoCapturesOnDelegate() { await TestAsync(@" class C { void M() { int i; System.Func<bool, int> f = dele$$gate(bool b) { i++; return 1; }; } }", Captures($"\r\n{WorkspacesResources.Variables_captured_colon} i")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(1516, "https://github.com/dotnet/roslyn/issues/1516")] public async Task QuickInfoWithNonStandardSeeAttributesAppear() { await TestAsync( @"class C { /// <summary> /// <see cref=""System.String"" /> /// <see href=""http://microsoft.com"" /> /// <see langword=""null"" /> /// <see unsupported-attribute=""cat"" /> /// </summary> void M() { M$$(); } }", Documentation(@"string http://microsoft.com null cat")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(6657, "https://github.com/dotnet/roslyn/issues/6657")] public async Task OptionalParameterFromPreviousSubmission() { const string workspaceDefinition = @" <Workspace> <Submission Language=""C#"" CommonReferences=""true""> void M(int x = 1) { } </Submission> <Submission Language=""C#"" CommonReferences=""true""> M(x$$: 2) </Submission> </Workspace> "; using var workspace = TestWorkspace.Create(XElement.Parse(workspaceDefinition), workspaceKind: WorkspaceKind.Interactive); await TestWithOptionsAsync(workspace, MainDescription($"({ FeaturesResources.parameter }) int x = 1")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TupleProperty() { await TestInMethodAsync( @"interface I { (int, int) Name { get; set; } } class C : I { (int, int) I.Name$$ { get { throw new System.Exception(); } set { } } }", MainDescription("(int, int) C.Name { get; set; }")); } [WorkItem(18311, "https://github.com/dotnet/roslyn/issues/18311")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ValueTupleWithArity0VariableName() { await TestAsync( @" using System; public class C { void M() { var y$$ = ValueTuple.Create(); } } ", MainDescription($"({ FeaturesResources.local_variable }) ValueTuple y")); } [WorkItem(18311, "https://github.com/dotnet/roslyn/issues/18311")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ValueTupleWithArity0ImplicitVar() { await TestAsync( @" using System; public class C { void M() { var$$ y = ValueTuple.Create(); } } ", MainDescription("struct System.ValueTuple")); } [WorkItem(18311, "https://github.com/dotnet/roslyn/issues/18311")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ValueTupleWithArity1VariableName() { await TestAsync( @" using System; public class C { void M() { var y$$ = ValueTuple.Create(1); } } ", MainDescription($"({ FeaturesResources.local_variable }) ValueTuple<int> y")); } [WorkItem(18311, "https://github.com/dotnet/roslyn/issues/18311")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ValueTupleWithArity1ImplicitVar() { await TestAsync( @" using System; public class C { void M() { var$$ y = ValueTuple.Create(1); } } ", MainDescription("struct System.ValueTuple<System.Int32>")); } [WorkItem(18311, "https://github.com/dotnet/roslyn/issues/18311")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ValueTupleWithArity2VariableName() { await TestAsync( @" using System; public class C { void M() { var y$$ = ValueTuple.Create(1, 1); } } ", MainDescription($"({ FeaturesResources.local_variable }) (int, int) y")); } [WorkItem(18311, "https://github.com/dotnet/roslyn/issues/18311")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ValueTupleWithArity2ImplicitVar() { await TestAsync( @" using System; public class C { void M() { var$$ y = ValueTuple.Create(1, 1); } } ", MainDescription("(System.Int32, System.Int32)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestRefMethod() { await TestInMethodAsync( @"using System; class Program { static void Main(string[] args) { ref int i = ref $$goo(); } private static ref int goo() { throw new NotImplementedException(); } }", MainDescription("ref int Program.goo()")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestRefLocal() { await TestInMethodAsync( @"using System; class Program { static void Main(string[] args) { ref int $$i = ref goo(); } private static ref int goo() { throw new NotImplementedException(); } }", MainDescription($"({FeaturesResources.local_variable}) ref int i")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(410932, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?id=410932")] public async Task TestGenericMethodInDocComment() { await TestAsync( @" class Test { T F<T>() { F<T>(); } /// <summary> /// <see cref=""F$${T}()""/> /// </summary> void S() { } } ", MainDescription("T Test.F<T>()")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(403665, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=403665&_a=edit")] public async Task TestExceptionWithCrefToConstructorDoesNotCrash() { await TestAsync( @" class Test { /// <summary> /// </summary> /// <exception cref=""Test.Test""/> public Test$$() {} } ", MainDescription("Test.Test()")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestRefStruct() { var markup = "ref struct X$$ {}"; await TestAsync(markup, MainDescription("ref struct X")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestRefStruct_Nested() { var markup = @" namespace Nested { ref struct X$$ {} }"; await TestAsync(markup, MainDescription("ref struct Nested.X")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestReadOnlyStruct() { var markup = "readonly struct X$$ {}"; await TestAsync(markup, MainDescription("readonly struct X")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestReadOnlyStruct_Nested() { var markup = @" namespace Nested { readonly struct X$$ {} }"; await TestAsync(markup, MainDescription("readonly struct Nested.X")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestReadOnlyRefStruct() { var markup = "readonly ref struct X$$ {}"; await TestAsync(markup, MainDescription("readonly ref struct X")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestReadOnlyRefStruct_Nested() { var markup = @" namespace Nested { readonly ref struct X$$ {} }"; await TestAsync(markup, MainDescription("readonly ref struct Nested.X")); } [WorkItem(22450, "https://github.com/dotnet/roslyn/issues/22450")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestRefLikeTypesNoDeprecated() { var xmlString = @" <Workspace> <Project Language=""C#"" LanguageVersion=""7.2"" CommonReferences=""true""> <MetadataReferenceFromSource Language=""C#"" LanguageVersion=""7.2"" CommonReferences=""true""> <Document FilePath=""ReferencedDocument""> public ref struct TestRef { } </Document> </MetadataReferenceFromSource> <Document FilePath=""SourceDocument""> ref struct Test { private $$TestRef _field; } </Document> </Project> </Workspace>"; // There should be no [deprecated] attribute displayed. await VerifyWithReferenceWorkerAsync(xmlString, MainDescription($"ref struct TestRef")); } [WorkItem(2644, "https://github.com/dotnet/roslyn/issues/2644")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task PropertyWithSameNameAsOtherType() { await TestAsync( @"namespace ConsoleApplication1 { class Program { static A B { get; set; } static B A { get; set; } static void Main(string[] args) { B = ConsoleApplication1.B$$.F(); } } class A { } class B { public static A F() => null; } }", MainDescription($"ConsoleApplication1.A ConsoleApplication1.B.F()")); } [WorkItem(2644, "https://github.com/dotnet/roslyn/issues/2644")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task PropertyWithSameNameAsOtherType2() { await TestAsync( @"using System.Collections.Generic; namespace ConsoleApplication1 { class Program { public static List<Bar> Bar { get; set; } static void Main(string[] args) { Tes$$t<Bar>(); } static void Test<T>() { } } class Bar { } }", MainDescription($"void Program.Test<Bar>()")); } [WorkItem(23883, "https://github.com/dotnet/roslyn/issues/23883")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task InMalformedEmbeddedStatement_01() { await TestAsync( @" class Program { void method1() { if (method2()) .Any(b => b.Content$$Type, out var chars) { } } } "); } [WorkItem(23883, "https://github.com/dotnet/roslyn/issues/23883")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task InMalformedEmbeddedStatement_02() { await TestAsync( @" class Program { void method1() { if (method2()) .Any(b => b$$.ContentType, out var chars) { } } } ", MainDescription($"({ FeaturesResources.parameter }) ? b")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task EnumConstraint() { await TestInMethodAsync( @" class X<T> where T : System.Enum { private $$T x; }", MainDescription($"T {FeaturesResources.in_} X<T> where T : Enum")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task DelegateConstraint() { await TestInMethodAsync( @" class X<T> where T : System.Delegate { private $$T x; }", MainDescription($"T {FeaturesResources.in_} X<T> where T : Delegate")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task MulticastDelegateConstraint() { await TestInMethodAsync( @" class X<T> where T : System.MulticastDelegate { private $$T x; }", MainDescription($"T {FeaturesResources.in_} X<T> where T : MulticastDelegate")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task UnmanagedConstraint_Type() { await TestAsync( @" class $$X<T> where T : unmanaged { }", MainDescription("class X<T> where T : unmanaged")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task UnmanagedConstraint_Method() { await TestAsync( @" class X { void $$M<T>() where T : unmanaged { } }", MainDescription("void X.M<T>() where T : unmanaged")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task UnmanagedConstraint_Delegate() { await TestAsync( "delegate void $$D<T>() where T : unmanaged;", MainDescription("delegate void D<T>() where T : unmanaged")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task UnmanagedConstraint_LocalFunction() { await TestAsync( @" class X { void N() { void $$M<T>() where T : unmanaged { } } }", MainDescription("void M<T>() where T : unmanaged")); } [WorkItem(29703, "https://github.com/dotnet/roslyn/issues/29703")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestGetAccessorDocumentation() { await TestAsync( @" class X { /// <summary>Summary for property Goo</summary> int Goo { g$$et; set; } }", Documentation("Summary for property Goo")); } [WorkItem(29703, "https://github.com/dotnet/roslyn/issues/29703")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestSetAccessorDocumentation() { await TestAsync( @" class X { /// <summary>Summary for property Goo</summary> int Goo { get; s$$et; } }", Documentation("Summary for property Goo")); } [WorkItem(29703, "https://github.com/dotnet/roslyn/issues/29703")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestEventAddDocumentation1() { await TestAsync( @" using System; class X { /// <summary>Summary for event Goo</summary> event EventHandler<EventArgs> Goo { a$$dd => throw null; remove => throw null; } }", Documentation("Summary for event Goo")); } [WorkItem(29703, "https://github.com/dotnet/roslyn/issues/29703")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestEventAddDocumentation2() { await TestAsync( @" using System; class X { /// <summary>Summary for event Goo</summary> event EventHandler<EventArgs> Goo; void M() => Goo +$$= null; }", Documentation("Summary for event Goo")); } [WorkItem(29703, "https://github.com/dotnet/roslyn/issues/29703")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestEventRemoveDocumentation1() { await TestAsync( @" using System; class X { /// <summary>Summary for event Goo</summary> event EventHandler<EventArgs> Goo { add => throw null; r$$emove => throw null; } }", Documentation("Summary for event Goo")); } [WorkItem(29703, "https://github.com/dotnet/roslyn/issues/29703")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestEventRemoveDocumentation2() { await TestAsync( @" using System; class X { /// <summary>Summary for event Goo</summary> event EventHandler<EventArgs> Goo; void M() => Goo -$$= null; }", Documentation("Summary for event Goo")); } [WorkItem(30642, "https://github.com/dotnet/roslyn/issues/30642")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task BuiltInOperatorWithUserDefinedEquivalent() { await TestAsync( @" class X { void N(string a, string b) { var v = a $$== b; } }", MainDescription("bool string.operator ==(string a, string b)"), SymbolGlyph(Glyph.Operator)); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NotNullConstraint_Type() { await TestAsync( @" class $$X<T> where T : notnull { }", MainDescription("class X<T> where T : notnull")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NotNullConstraint_Method() { await TestAsync( @" class X { void $$M<T>() where T : notnull { } }", MainDescription("void X.M<T>() where T : notnull")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NotNullConstraint_Delegate() { await TestAsync( "delegate void $$D<T>() where T : notnull;", MainDescription("delegate void D<T>() where T : notnull")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NotNullConstraint_LocalFunction() { await TestAsync( @" class X { void N() { void $$M<T>() where T : notnull { } } }", MainDescription("void M<T>() where T : notnull")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NullableParameterThatIsMaybeNull() { await TestWithOptionsAsync(TestOptions.Regular8, @"#nullable enable class X { void N(string? s) { string s2 = $$s; } }", MainDescription($"({FeaturesResources.parameter}) string? s"), NullabilityAnalysis(string.Format(FeaturesResources._0_may_be_null_here, "s"))); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NullableParameterThatIsNotNull() { await TestWithOptionsAsync(TestOptions.Regular8, @"#nullable enable class X { void N(string? s) { s = """"; string s2 = $$s; } }", MainDescription($"({FeaturesResources.parameter}) string? s"), NullabilityAnalysis(string.Format(FeaturesResources._0_is_not_null_here, "s"))); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NullableFieldThatIsMaybeNull() { await TestWithOptionsAsync(TestOptions.Regular8, @"#nullable enable class X { string? s = null; void N() { string s2 = $$s; } }", MainDescription($"({FeaturesResources.field}) string? X.s"), NullabilityAnalysis(string.Format(FeaturesResources._0_may_be_null_here, "s"))); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NullableFieldThatIsNotNull() { await TestWithOptionsAsync(TestOptions.Regular8, @"#nullable enable class X { string? s = null; void N() { s = """"; string s2 = $$s; } }", MainDescription($"({FeaturesResources.field}) string? X.s"), NullabilityAnalysis(string.Format(FeaturesResources._0_is_not_null_here, "s"))); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NullablePropertyThatIsMaybeNull() { await TestWithOptionsAsync(TestOptions.Regular8, @"#nullable enable class X { string? S { get; set; } void N() { string s2 = $$S; } }", MainDescription("string? X.S { get; set; }"), NullabilityAnalysis(string.Format(FeaturesResources._0_may_be_null_here, "S"))); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NullablePropertyThatIsNotNull() { await TestWithOptionsAsync(TestOptions.Regular8, @"#nullable enable class X { string? S { get; set; } void N() { S = """"; string s2 = $$S; } }", MainDescription("string? X.S { get; set; }"), NullabilityAnalysis(string.Format(FeaturesResources._0_is_not_null_here, "S"))); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NullableRangeVariableThatIsMaybeNull() { await TestWithOptionsAsync(TestOptions.Regular8, @"#nullable enable using System.Collections.Generic; class X { void N() { IEnumerable<string?> enumerable; foreach (var s in enumerable) { string s2 = $$s; } } }", MainDescription($"({FeaturesResources.local_variable}) string? s"), NullabilityAnalysis(string.Format(FeaturesResources._0_may_be_null_here, "s"))); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NullableRangeVariableThatIsNotNull() { await TestWithOptionsAsync(TestOptions.Regular8, @"#nullable enable using System.Collections.Generic; class X { void N() { IEnumerable<string> enumerable; foreach (var s in enumerable) { string s2 = $$s; } } }", MainDescription($"({FeaturesResources.local_variable}) string? s"), NullabilityAnalysis(string.Format(FeaturesResources._0_is_not_null_here, "s"))); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NullableLocalThatIsMaybeNull() { await TestWithOptionsAsync(TestOptions.Regular8, @"#nullable enable using System.Collections.Generic; class X { void N() { string? s = null; string s2 = $$s; } }", MainDescription($"({FeaturesResources.local_variable}) string? s"), NullabilityAnalysis(string.Format(FeaturesResources._0_may_be_null_here, "s"))); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NullableLocalThatIsNotNull() { await TestWithOptionsAsync(TestOptions.Regular8, @"#nullable enable using System.Collections.Generic; class X { void N() { string? s = """"; string s2 = $$s; } }", MainDescription($"({FeaturesResources.local_variable}) string? s"), NullabilityAnalysis(string.Format(FeaturesResources._0_is_not_null_here, "s"))); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NullableNotShownPriorToLanguageVersion8() { await TestWithOptionsAsync(TestOptions.Regular7_3, @"#nullable enable using System.Collections.Generic; class X { void N() { string s = """"; string s2 = $$s; } }", MainDescription($"({FeaturesResources.local_variable}) string s"), NullabilityAnalysis("")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NullableNotShownInNullableDisable() { await TestWithOptionsAsync(TestOptions.Regular8, @"#nullable disable using System.Collections.Generic; class X { void N() { string s = """"; string s2 = $$s; } }", MainDescription($"({FeaturesResources.local_variable}) string s"), NullabilityAnalysis("")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NullableShownWhenEnabledGlobally() { await TestWithOptionsAsync(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, nullableContextOptions: NullableContextOptions.Enable), @"using System.Collections.Generic; class X { void N() { string s = """"; string s2 = $$s; } }", MainDescription($"({FeaturesResources.local_variable}) string s"), NullabilityAnalysis(string.Format(FeaturesResources._0_is_not_null_here, "s"))); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NullableNotShownForValueType() { await TestWithOptionsAsync(TestOptions.Regular8, @"#nullable enable using System.Collections.Generic; class X { void N() { int a = 0; int b = $$a; } }", MainDescription($"({FeaturesResources.local_variable}) int a"), NullabilityAnalysis("")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NullableNotShownForConst() { await TestWithOptionsAsync(TestOptions.Regular8, @"#nullable enable using System.Collections.Generic; class X { void N() { const string? s = null; string? s2 = $$s; } }", MainDescription($"({FeaturesResources.local_constant}) string? s = null"), NullabilityAnalysis("")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestInheritdocInlineSummary() { var markup = @" /// <summary>Summary documentation</summary> /// <remarks>Remarks documentation</remarks> void M(int x) { } /// <summary><inheritdoc cref=""M(int)""/></summary> void $$M(int x, int y) { }"; await TestInClassAsync(markup, MainDescription("void C.M(int x, int y)"), Documentation("Summary documentation")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestInheritdocTwoLevels1() { var markup = @" /// <summary>Summary documentation</summary> /// <remarks>Remarks documentation</remarks> void M() { } /// <inheritdoc cref=""M()""/> void M(int x) { } /// <inheritdoc cref=""M(int)""/> void $$M(int x, int y) { }"; await TestInClassAsync(markup, MainDescription("void C.M(int x, int y)"), Documentation("Summary documentation")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestInheritdocTwoLevels2() { var markup = @" /// <summary>Summary documentation</summary> /// <remarks>Remarks documentation</remarks> void M() { } /// <summary><inheritdoc cref=""M()""/></summary> void M(int x) { } /// <summary><inheritdoc cref=""M(int)""/></summary> void $$M(int x, int y) { }"; await TestInClassAsync(markup, MainDescription("void C.M(int x, int y)"), Documentation("Summary documentation")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestInheritdocWithTypeParamRef() { var markup = @" public class Program { public static void Main() => _ = new Test<int>().$$Clone(); } public class Test<T> : ICloneable<Test<T>> { /// <inheritdoc/> public Test<T> Clone() => new(); } /// <summary>A type that has clonable instances.</summary> /// <typeparam name=""T"">The type of instances that can be cloned.</typeparam> public interface ICloneable<T> { /// <summary>Clones a <typeparamref name=""T""/>.</summary> /// <returns>A clone of the <typeparamref name=""T""/>.</returns> public T Clone(); }"; await TestInClassAsync(markup, MainDescription("Test<int> Test<int>.Clone()"), Documentation("Clones a Test<T>.")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestInheritdocCycle1() { var markup = @" /// <inheritdoc cref=""M(int, int)""/> void M(int x) { } /// <inheritdoc cref=""M(int)""/> void $$M(int x, int y) { }"; await TestInClassAsync(markup, MainDescription("void C.M(int x, int y)"), Documentation("")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestInheritdocCycle2() { var markup = @" /// <inheritdoc cref=""M(int)""/> void $$M(int x) { }"; await TestInClassAsync(markup, MainDescription("void C.M(int x)"), Documentation("")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestInheritdocCycle3() { var markup = @" /// <inheritdoc cref=""M""/> void $$M(int x) { }"; await TestInClassAsync(markup, MainDescription("void C.M(int x)"), Documentation("")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(38794, "https://github.com/dotnet/roslyn/issues/38794")] public async Task TestLinqGroupVariableDeclaration() { var code = @" void M(string[] a) { var v = from x in a group x by x.Length into $$g select g; }"; await TestInClassAsync(code, MainDescription($"({FeaturesResources.range_variable}) IGrouping<int, string> g")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(38283, "https://github.com/dotnet/roslyn/issues/38283")] public async Task QuickInfoOnIndexerCloseBracket() { await TestAsync(@" class C { public int this[int x] { get { return 1; } } void M() { var x = new C()[5$$]; } }", MainDescription("int C.this[int x] { get; }")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(38283, "https://github.com/dotnet/roslyn/issues/38283")] public async Task QuickInfoOnIndexerOpenBracket() { await TestAsync(@" class C { public int this[int x] { get { return 1; } } void M() { var x = new C()$$[5]; } }", MainDescription("int C.this[int x] { get; }")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(38283, "https://github.com/dotnet/roslyn/issues/38283")] public async Task QuickInfoOnIndexer_NotOnArrayAccess() { await TestAsync(@" class Program { void M() { int[] x = new int[4]; int y = x[3$$]; } }", MainDescription("struct System.Int32")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(31618, "https://github.com/dotnet/roslyn/issues/31618")] public async Task QuickInfoWithRemarksOnMethod() { await TestAsync(@" class Program { /// <summary> /// Summary text /// </summary> /// <remarks> /// Remarks text /// </remarks> int M() { return $$M(); } }", MainDescription("int Program.M()"), Documentation("Summary text"), Remarks("\r\nRemarks text")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(31618, "https://github.com/dotnet/roslyn/issues/31618")] public async Task QuickInfoWithRemarksOnPropertyAccessor() { await TestAsync(@" class Program { /// <summary> /// Summary text /// </summary> /// <remarks> /// Remarks text /// </remarks> int M { $$get; } }", MainDescription("int Program.M.get"), Documentation("Summary text"), Remarks("\r\nRemarks text")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(31618, "https://github.com/dotnet/roslyn/issues/31618")] public async Task QuickInfoWithReturnsOnMethod() { await TestAsync(@" class Program { /// <summary> /// Summary text /// </summary> /// <returns> /// Returns text /// </returns> int M() { return $$M(); } }", MainDescription("int Program.M()"), Documentation("Summary text"), Returns($"\r\n{FeaturesResources.Returns_colon}\r\n Returns text")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(31618, "https://github.com/dotnet/roslyn/issues/31618")] public async Task QuickInfoWithReturnsOnPropertyAccessor() { await TestAsync(@" class Program { /// <summary> /// Summary text /// </summary> /// <returns> /// Returns text /// </returns> int M { $$get; } }", MainDescription("int Program.M.get"), Documentation("Summary text"), Returns($"\r\n{FeaturesResources.Returns_colon}\r\n Returns text")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(31618, "https://github.com/dotnet/roslyn/issues/31618")] public async Task QuickInfoWithValueOnMethod() { await TestAsync(@" class Program { /// <summary> /// Summary text /// </summary> /// <value> /// Value text /// </value> int M() { return $$M(); } }", MainDescription("int Program.M()"), Documentation("Summary text"), Value($"\r\n{FeaturesResources.Value_colon}\r\n Value text")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(31618, "https://github.com/dotnet/roslyn/issues/31618")] public async Task QuickInfoWithValueOnPropertyAccessor() { await TestAsync(@" class Program { /// <summary> /// Summary text /// </summary> /// <value> /// Value text /// </value> int M { $$get; } }", MainDescription("int Program.M.get"), Documentation("Summary text"), Value($"\r\n{FeaturesResources.Value_colon}\r\n Value text")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")] public async Task QuickInfoNotPattern1() { await TestAsync(@" class Person { void Goo(object o) { if (o is not $$Person p) { } } }", MainDescription("class Person")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")] public async Task QuickInfoNotPattern2() { await TestAsync(@" class Person { void Goo(object o) { if (o is $$not Person p) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")] public async Task QuickInfoOrPattern1() { await TestAsync(@" class Person { void Goo(object o) { if (o is $$Person or int) { } } }", MainDescription("class Person")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")] public async Task QuickInfoOrPattern2() { await TestAsync(@" class Person { void Goo(object o) { if (o is Person or $$int) { } } }", MainDescription("struct System.Int32")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")] public async Task QuickInfoOrPattern3() { await TestAsync(@" class Person { void Goo(object o) { if (o is Person $$or int) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task QuickInfoRecord() { await TestWithOptionsAsync( Options.Regular.WithLanguageVersion(LanguageVersion.CSharp9), @"record Person(string First, string Last) { void M($$Person p) { } }", MainDescription("record Person")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task QuickInfoDerivedRecord() { await TestWithOptionsAsync( Options.Regular.WithLanguageVersion(LanguageVersion.CSharp9), @"record Person(string First, string Last) { } record Student(string Id) { void M($$Student p) { } } ", MainDescription("record Student")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(44904, "https://github.com/dotnet/roslyn/issues/44904")] public async Task QuickInfoRecord_BaseTypeList() { await TestAsync(@" record Person(string First, string Last); record Student(int Id) : $$Person(null, null); ", MainDescription("Person.Person(string First, string Last)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task QuickInfo_BaseConstructorInitializer() { await TestAsync(@" public class Person { public Person(int id) { } } public class Student : Person { public Student() : $$base(0) { } } ", MainDescription("Person.Person(int id)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task QuickInfoRecordClass() { await TestWithOptionsAsync( Options.Regular.WithLanguageVersion(LanguageVersion.CSharp9), @"record class Person(string First, string Last) { void M($$Person p) { } }", MainDescription("record Person")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task QuickInfoRecordStruct() { await TestWithOptionsAsync( Options.Regular.WithLanguageVersion(LanguageVersion.CSharp9), @"record struct Person(string First, string Last) { void M($$Person p) { } }", MainDescription("record struct Person")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task QuickInfoReadOnlyRecordStruct() { await TestWithOptionsAsync( Options.Regular.WithLanguageVersion(LanguageVersion.CSharp9), @"readonly record struct Person(string First, string Last) { void M($$Person p) { } }", MainDescription("readonly record struct Person")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(51615, "https://github.com/dotnet/roslyn/issues/51615")] public async Task TestVarPatternOnVarKeyword() { await TestAsync( @"class C { string M() { } void M2() { if (M() is va$$r x && x.Length > 0) { } } }", MainDescription("class System.String")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestVarPatternOnVariableItself() { await TestAsync( @"class C { string M() { } void M2() { if (M() is var x$$ && x.Length > 0) { } } }", MainDescription($"({FeaturesResources.local_variable}) string? x")); } [WorkItem(53135, "https://github.com/dotnet/roslyn/issues/53135")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestDocumentationCData() { var markup = @"using I$$ = IGoo; /// <summary> /// summary for interface IGoo /// <code><![CDATA[ /// List<string> y = null; /// ]]></code> /// </summary> interface IGoo { }"; await TestAsync(markup, MainDescription("interface IGoo"), Documentation(@"summary for interface IGoo List<string> y = null;")); } [WorkItem(37503, "https://github.com/dotnet/roslyn/issues/37503")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task DoNotNormalizeWhitespaceForCode() { var markup = @"using I$$ = IGoo; /// <summary> /// Normalize this, and <c>Also this</c> /// <code> /// line 1 /// line 2 /// </code> /// </summary> interface IGoo { }"; await TestAsync(markup, MainDescription("interface IGoo"), Documentation(@"Normalize this, and Also this line 1 line 2")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestStaticAbstract_ImplicitImplementation() { var code = @" interface I1 { /// <summary>Summary text</summary> static abstract void M1(); } class C1_1 : I1 { public static void $$M1() { } } "; await TestAsync( code, MainDescription("void C1_1.M1()"), Documentation("Summary text")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestStaticAbstract_ImplicitImplementation_FromReference() { var code = @" interface I1 { /// <summary>Summary text</summary> static abstract void M1(); } class C1_1 : I1 { public static void M1() { } } class R { public static void M() { C1_1.$$M1(); } } "; await TestAsync( code, MainDescription("void C1_1.M1()"), Documentation("Summary text")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestStaticAbstract_FromTypeParameterReference() { var code = @" interface I1 { /// <summary>Summary text</summary> static abstract void M1(); } class R { public static void M<T>() where T : I1 { T.$$M1(); } } "; await TestAsync( code, MainDescription("void I1.M1()"), Documentation("Summary text")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestStaticAbstract_ExplicitInheritdoc_ImplicitImplementation() { var code = @" interface I1 { /// <summary>Summary text</summary> static abstract void M1(); } class C1_1 : I1 { /// <inheritdoc/> public static void $$M1() { } } "; await TestAsync( code, MainDescription("void C1_1.M1()"), Documentation("Summary text")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestStaticAbstract_ExplicitImplementation() { var code = @" interface I1 { /// <summary>Summary text</summary> static abstract void M1(); } class C1_1 : I1 { static void I1.$$M1() { } } "; await TestAsync( code, MainDescription("void C1_1.M1()"), Documentation("Summary text")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestStaticAbstract_ExplicitInheritdoc_ExplicitImplementation() { var code = @" interface I1 { /// <summary>Summary text</summary> static abstract void M1(); } class C1_1 : I1 { /// <inheritdoc/> static void I1.$$M1() { } } "; await TestAsync( code, MainDescription("void C1_1.M1()"), Documentation("Summary text")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task QuickInfoLambdaReturnType_01() { await TestWithOptionsAsync( Options.Regular.WithLanguageVersion(LanguageVersion.CSharp9), @"class Program { System.Delegate D = bo$$ol () => true; }", MainDescription("struct System.Boolean")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task QuickInfoLambdaReturnType_02() { await TestWithOptionsAsync( Options.Regular.WithLanguageVersion(LanguageVersion.CSharp9), @"class A { struct B { } System.Delegate D = A.B$$ () => null; }", MainDescription("struct A.B")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task QuickInfoLambdaReturnType_03() { await TestWithOptionsAsync( Options.Regular.WithLanguageVersion(LanguageVersion.CSharp9), @"class A<T> { } struct B { System.Delegate D = A<B$$> () => null; }", MainDescription("struct B")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestNormalFuncSynthesizedLambdaType() { await TestAsync( @"class C { void M() { $$var v = (int i) => i.ToString(); } }", MainDescription("delegate TResult System.Func<in T, out TResult>(T arg)"), TypeParameterMap($@" T {FeaturesResources.is_} int TResult {FeaturesResources.is_} string")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestAnonymousSynthesizedLambdaType() { await TestAsync( @"class C { void M() { $$var v = (ref int i) => i.ToString(); } }", MainDescription("delegate string <anonymous delegate>(ref int)")); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; using System.Security; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Editor.UnitTests.QuickInfo; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.QuickInfo; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using static Microsoft.CodeAnalysis.Editor.UnitTests.Classification.FormattedClassifications; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.QuickInfo { public class SemanticQuickInfoSourceTests : AbstractSemanticQuickInfoSourceTests { private static async Task TestWithOptionsAsync(CSharpParseOptions options, string markup, params Action<QuickInfoItem>[] expectedResults) { using var workspace = TestWorkspace.CreateCSharp(markup, options); await TestWithOptionsAsync(workspace, expectedResults); } private static async Task TestWithOptionsAsync(CSharpCompilationOptions options, string markup, params Action<QuickInfoItem>[] expectedResults) { using var workspace = TestWorkspace.CreateCSharp(markup, compilationOptions: options); await TestWithOptionsAsync(workspace, expectedResults); } private static async Task TestWithOptionsAsync(TestWorkspace workspace, params Action<QuickInfoItem>[] expectedResults) { var testDocument = workspace.DocumentWithCursor; var position = testDocument.CursorPosition.GetValueOrDefault(); var documentId = workspace.GetDocumentId(testDocument); var document = workspace.CurrentSolution.GetDocument(documentId); var service = QuickInfoService.GetService(document); await TestWithOptionsAsync(document, service, position, expectedResults); // speculative semantic model if (await CanUseSpeculativeSemanticModelAsync(document, position)) { var buffer = testDocument.GetTextBuffer(); using (var edit = buffer.CreateEdit()) { var currentSnapshot = buffer.CurrentSnapshot; edit.Replace(0, currentSnapshot.Length, currentSnapshot.GetText()); edit.Apply(); } await TestWithOptionsAsync(document, service, position, expectedResults); } } private static async Task TestWithOptionsAsync(Document document, QuickInfoService service, int position, Action<QuickInfoItem>[] expectedResults) { var info = await service.GetQuickInfoAsync(document, position, cancellationToken: CancellationToken.None); if (expectedResults.Length == 0) { Assert.Null(info); } else { Assert.NotNull(info); foreach (var expected in expectedResults) { expected(info); } } } private static async Task VerifyWithMscorlib45Async(string markup, Action<QuickInfoItem>[] expectedResults) { var xmlString = string.Format(@" <Workspace> <Project Language=""C#"" CommonReferencesNet45=""true""> <Document FilePath=""SourceDocument""> {0} </Document> </Project> </Workspace>", SecurityElement.Escape(markup)); using var workspace = TestWorkspace.Create(xmlString); var position = workspace.Documents.Single(d => d.Name == "SourceDocument").CursorPosition.Value; var documentId = workspace.Documents.Where(d => d.Name == "SourceDocument").Single().Id; var document = workspace.CurrentSolution.GetDocument(documentId); var service = QuickInfoService.GetService(document); var info = await service.GetQuickInfoAsync(document, position, cancellationToken: CancellationToken.None); if (expectedResults.Length == 0) { Assert.Null(info); } else { Assert.NotNull(info); foreach (var expected in expectedResults) { expected(info); } } } protected override async Task TestAsync(string markup, params Action<QuickInfoItem>[] expectedResults) { await TestWithOptionsAsync(Options.Regular, markup, expectedResults); await TestWithOptionsAsync(Options.Script, markup, expectedResults); } private async Task TestWithUsingsAsync(string markup, params Action<QuickInfoItem>[] expectedResults) { var markupWithUsings = @"using System; using System.Collections.Generic; using System.Linq; " + markup; await TestAsync(markupWithUsings, expectedResults); } private Task TestInClassAsync(string markup, params Action<QuickInfoItem>[] expectedResults) { var markupInClass = "class C { " + markup + " }"; return TestWithUsingsAsync(markupInClass, expectedResults); } private Task TestInMethodAsync(string markup, params Action<QuickInfoItem>[] expectedResults) { var markupInMethod = "class C { void M() { " + markup + " } }"; return TestWithUsingsAsync(markupInMethod, expectedResults); } private static async Task TestWithReferenceAsync(string sourceCode, string referencedCode, string sourceLanguage, string referencedLanguage, params Action<QuickInfoItem>[] expectedResults) { await TestWithMetadataReferenceHelperAsync(sourceCode, referencedCode, sourceLanguage, referencedLanguage, expectedResults); await TestWithProjectReferenceHelperAsync(sourceCode, referencedCode, sourceLanguage, referencedLanguage, expectedResults); // Multi-language projects are not supported. if (sourceLanguage == referencedLanguage) { await TestInSameProjectHelperAsync(sourceCode, referencedCode, sourceLanguage, expectedResults); } } private static async Task TestWithMetadataReferenceHelperAsync( string sourceCode, string referencedCode, string sourceLanguage, string referencedLanguage, params Action<QuickInfoItem>[] expectedResults) { var xmlString = string.Format(@" <Workspace> <Project Language=""{0}"" CommonReferences=""true""> <Document FilePath=""SourceDocument""> {1} </Document> <MetadataReferenceFromSource Language=""{2}"" CommonReferences=""true"" IncludeXmlDocComments=""true""> <Document FilePath=""ReferencedDocument""> {3} </Document> </MetadataReferenceFromSource> </Project> </Workspace>", sourceLanguage, SecurityElement.Escape(sourceCode), referencedLanguage, SecurityElement.Escape(referencedCode)); await VerifyWithReferenceWorkerAsync(xmlString, expectedResults); } private static async Task TestWithProjectReferenceHelperAsync( string sourceCode, string referencedCode, string sourceLanguage, string referencedLanguage, params Action<QuickInfoItem>[] expectedResults) { var xmlString = string.Format(@" <Workspace> <Project Language=""{0}"" CommonReferences=""true""> <ProjectReference>ReferencedProject</ProjectReference> <Document FilePath=""SourceDocument""> {1} </Document> </Project> <Project Language=""{2}"" CommonReferences=""true"" AssemblyName=""ReferencedProject""> <Document FilePath=""ReferencedDocument""> {3} </Document> </Project> </Workspace>", sourceLanguage, SecurityElement.Escape(sourceCode), referencedLanguage, SecurityElement.Escape(referencedCode)); await VerifyWithReferenceWorkerAsync(xmlString, expectedResults); } private static async Task TestInSameProjectHelperAsync( string sourceCode, string referencedCode, string sourceLanguage, params Action<QuickInfoItem>[] expectedResults) { var xmlString = string.Format(@" <Workspace> <Project Language=""{0}"" CommonReferences=""true""> <Document FilePath=""SourceDocument""> {1} </Document> <Document FilePath=""ReferencedDocument""> {2} </Document> </Project> </Workspace>", sourceLanguage, SecurityElement.Escape(sourceCode), SecurityElement.Escape(referencedCode)); await VerifyWithReferenceWorkerAsync(xmlString, expectedResults); } private static async Task VerifyWithReferenceWorkerAsync(string xmlString, params Action<QuickInfoItem>[] expectedResults) { using var workspace = TestWorkspace.Create(xmlString); var position = workspace.Documents.First(d => d.Name == "SourceDocument").CursorPosition.Value; var documentId = workspace.Documents.First(d => d.Name == "SourceDocument").Id; var document = workspace.CurrentSolution.GetDocument(documentId); var service = QuickInfoService.GetService(document); var info = await service.GetQuickInfoAsync(document, position, cancellationToken: CancellationToken.None); if (expectedResults.Length == 0) { Assert.Null(info); } else { Assert.NotNull(info); foreach (var expected in expectedResults) { expected(info); } } } protected async Task TestInvalidTypeInClassAsync(string code) { var codeInClass = "class C { " + code + " }"; await TestAsync(codeInClass); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestNamespaceInUsingDirective() { await TestAsync( @"using $$System;", MainDescription("namespace System")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestNamespaceInUsingDirective2() { await TestAsync( @"using System.Coll$$ections.Generic;", MainDescription("namespace System.Collections")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestNamespaceInUsingDirective3() { await TestAsync( @"using System.L$$inq;", MainDescription("namespace System.Linq")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestNamespaceInUsingDirectiveWithAlias() { await TestAsync( @"using Goo = Sys$$tem.Console;", MainDescription("namespace System")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestTypeInUsingDirectiveWithAlias() { await TestAsync( @"using Goo = System.Con$$sole;", MainDescription("class System.Console")); } [WorkItem(991466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991466")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestDocumentationInUsingDirectiveWithAlias() { var markup = @"using I$$ = IGoo; ///<summary>summary for interface IGoo</summary> interface IGoo { }"; await TestAsync(markup, MainDescription("interface IGoo"), Documentation("summary for interface IGoo")); } [WorkItem(991466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991466")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestDocumentationInUsingDirectiveWithAlias2() { var markup = @"using I = IGoo; ///<summary>summary for interface IGoo</summary> interface IGoo { } class C : I$$ { }"; await TestAsync(markup, MainDescription("interface IGoo"), Documentation("summary for interface IGoo")); } [WorkItem(991466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991466")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestDocumentationInUsingDirectiveWithAlias3() { var markup = @"using I = IGoo; ///<summary>summary for interface IGoo</summary> interface IGoo { void Goo(); } class C : I$$ { }"; await TestAsync(markup, MainDescription("interface IGoo"), Documentation("summary for interface IGoo")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestThis() { var markup = @" ///<summary>summary for Class C</summary> class C { string M() { return thi$$s.ToString(); } }"; await TestWithUsingsAsync(markup, MainDescription("class C"), Documentation("summary for Class C")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestClassWithDocComment() { var markup = @" ///<summary>Hello!</summary> class C { void M() { $$C obj; } }"; await TestAsync(markup, MainDescription("class C"), Documentation("Hello!")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestSingleLineDocComments() { // Tests chosen to maximize code coverage in DocumentationCommentCompiler.WriteFormattedSingleLineComment // SingleLine doc comment with leading whitespace await TestAsync( @"///<summary>Hello!</summary> class C { void M() { $$C obj; } }", MainDescription("class C"), Documentation("Hello!")); // SingleLine doc comment with space before opening tag await TestAsync( @"/// <summary>Hello!</summary> class C { void M() { $$C obj; } }", MainDescription("class C"), Documentation("Hello!")); // SingleLine doc comment with space before opening tag and leading whitespace await TestAsync( @"/// <summary>Hello!</summary> class C { void M() { $$C obj; } }", MainDescription("class C"), Documentation("Hello!")); // SingleLine doc comment with leading whitespace and blank line await TestAsync( @"///<summary>Hello! ///</summary> class C { void M() { $$C obj; } }", MainDescription("class C"), Documentation("Hello!")); // SingleLine doc comment with '\r' line separators await TestAsync("///<summary>Hello!\r///</summary>\rclass C { void M() { $$C obj; } }", MainDescription("class C"), Documentation("Hello!")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestMultiLineDocComments() { // Tests chosen to maximize code coverage in DocumentationCommentCompiler.WriteFormattedMultiLineComment // Multiline doc comment with leading whitespace await TestAsync( @"/**<summary>Hello!</summary>*/ class C { void M() { $$C obj; } }", MainDescription("class C"), Documentation("Hello!")); // Multiline doc comment with space before opening tag await TestAsync( @"/** <summary>Hello!</summary> **/ class C { void M() { $$C obj; } }", MainDescription("class C"), Documentation("Hello!")); // Multiline doc comment with space before opening tag and leading whitespace await TestAsync( @"/** ** <summary>Hello!</summary> **/ class C { void M() { $$C obj; } }", MainDescription("class C"), Documentation("Hello!")); // Multiline doc comment with no per-line prefix await TestAsync( @"/** <summary> Hello! </summary> */ class C { void M() { $$C obj; } }", MainDescription("class C"), Documentation("Hello!")); // Multiline doc comment with inconsistent per-line prefix await TestAsync( @"/** ** <summary> Hello!</summary> ** **/ class C { void M() { $$C obj; } }", MainDescription("class C"), Documentation("Hello!")); // Multiline doc comment with closing comment on final line await TestAsync( @"/** <summary>Hello! </summary>*/ class C { void M() { $$C obj; } }", MainDescription("class C"), Documentation("Hello!")); // Multiline doc comment with '\r' line separators await TestAsync("/**\r* <summary>\r* Hello!\r* </summary>\r*/\rclass C { void M() { $$C obj; } }", MainDescription("class C"), Documentation("Hello!")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestMethodWithDocComment() { var markup = @" ///<summary>Hello!</summary> void M() { M$$() }"; await TestInClassAsync(markup, MainDescription("void C.M()"), Documentation("Hello!")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestInt32() { await TestInClassAsync( @"$$Int32 i;", MainDescription("struct System.Int32")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestBuiltInInt() { await TestInClassAsync( @"$$int i;", MainDescription("struct System.Int32")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestString() { await TestInClassAsync( @"$$String s;", MainDescription("class System.String")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestBuiltInString() { await TestInClassAsync( @"$$string s;", MainDescription("class System.String")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestBuiltInStringAtEndOfToken() { await TestInClassAsync( @"string$$ s;", MainDescription("class System.String")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestBoolean() { await TestInClassAsync( @"$$Boolean b;", MainDescription("struct System.Boolean")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestBuiltInBool() { await TestInClassAsync( @"$$bool b;", MainDescription("struct System.Boolean")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestSingle() { await TestInClassAsync( @"$$Single s;", MainDescription("struct System.Single")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestBuiltInFloat() { await TestInClassAsync( @"$$float f;", MainDescription("struct System.Single")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestVoidIsInvalid() { await TestInvalidTypeInClassAsync( @"$$void M() { }"); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestInvalidPointer1_931958() { await TestInvalidTypeInClassAsync( @"$$T* i;"); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestInvalidPointer2_931958() { await TestInvalidTypeInClassAsync( @"T$$* i;"); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestInvalidPointer3_931958() { await TestInvalidTypeInClassAsync( @"T*$$ i;"); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestListOfString() { await TestInClassAsync( @"$$List<string> l;", MainDescription("class System.Collections.Generic.List<T>"), TypeParameterMap($"\r\nT {FeaturesResources.is_} string")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestListOfSomethingFromSource() { var markup = @" ///<summary>Generic List</summary> public class GenericList<T> { Generic$$List<int> t; }"; await TestAsync(markup, MainDescription("class GenericList<T>"), Documentation("Generic List"), TypeParameterMap($"\r\nT {FeaturesResources.is_} int")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestListOfT() { await TestInMethodAsync( @"class C<T> { $$List<T> l; }", MainDescription("class System.Collections.Generic.List<T>")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestDictionaryOfIntAndString() { await TestInClassAsync( @"$$Dictionary<int, string> d;", MainDescription("class System.Collections.Generic.Dictionary<TKey, TValue>"), TypeParameterMap( Lines($"\r\nTKey {FeaturesResources.is_} int", $"TValue {FeaturesResources.is_} string"))); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestDictionaryOfTAndU() { await TestInMethodAsync( @"class C<T, U> { $$Dictionary<T, U> d; }", MainDescription("class System.Collections.Generic.Dictionary<TKey, TValue>"), TypeParameterMap( Lines($"\r\nTKey {FeaturesResources.is_} T", $"TValue {FeaturesResources.is_} U"))); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestIEnumerableOfInt() { await TestInClassAsync( @"$$IEnumerable<int> M() { yield break; }", MainDescription("interface System.Collections.Generic.IEnumerable<out T>"), TypeParameterMap($"\r\nT {FeaturesResources.is_} int")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestEventHandler() { await TestInClassAsync( @"event $$EventHandler e;", MainDescription("delegate void System.EventHandler(object sender, System.EventArgs e)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestTypeParameter() { await TestAsync( @"class C<T> { $$T t; }", MainDescription($"T {FeaturesResources.in_} C<T>")); } [WorkItem(538636, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538636")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestTypeParameterWithDocComment() { var markup = @" ///<summary>Hello!</summary> ///<typeparam name=""T"">T is Type Parameter</typeparam> class C<T> { $$T t; }"; await TestAsync(markup, MainDescription($"T {FeaturesResources.in_} C<T>"), Documentation("T is Type Parameter")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestTypeParameter1_Bug931949() { await TestAsync( @"class T1<T11> { $$T11 t; }", MainDescription($"T11 {FeaturesResources.in_} T1<T11>")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestTypeParameter2_Bug931949() { await TestAsync( @"class T1<T11> { T$$11 t; }", MainDescription($"T11 {FeaturesResources.in_} T1<T11>")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestTypeParameter3_Bug931949() { await TestAsync( @"class T1<T11> { T1$$1 t; }", MainDescription($"T11 {FeaturesResources.in_} T1<T11>")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestTypeParameter4_Bug931949() { await TestAsync( @"class T1<T11> { T11$$ t; }", MainDescription($"T11 {FeaturesResources.in_} T1<T11>")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestNullableOfInt() { await TestInClassAsync(@"$$Nullable<int> i; }", MainDescription("struct System.Nullable<T> where T : struct"), TypeParameterMap($"\r\nT {FeaturesResources.is_} int")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestGenericTypeDeclaredOnMethod1_Bug1946() { await TestAsync( @"class C { static void Meth1<T1>($$T1 i) where T1 : struct { T1 i; } }", MainDescription($"T1 {FeaturesResources.in_} C.Meth1<T1> where T1 : struct")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestGenericTypeDeclaredOnMethod2_Bug1946() { await TestAsync( @"class C { static void Meth1<T1>(T1 i) where $$T1 : struct { T1 i; } }", MainDescription($"T1 {FeaturesResources.in_} C.Meth1<T1> where T1 : struct")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestGenericTypeDeclaredOnMethod3_Bug1946() { await TestAsync( @"class C { static void Meth1<T1>(T1 i) where T1 : struct { $$T1 i; } }", MainDescription($"T1 {FeaturesResources.in_} C.Meth1<T1> where T1 : struct")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestGenericTypeParameterConstraint_Class() { await TestAsync( @"class C<T> where $$T : class { }", MainDescription($"T {FeaturesResources.in_} C<T> where T : class")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestGenericTypeParameterConstraint_Struct() { await TestAsync( @"struct S<T> where $$T : class { }", MainDescription($"T {FeaturesResources.in_} S<T> where T : class")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestGenericTypeParameterConstraint_Interface() { await TestAsync( @"interface I<T> where $$T : class { }", MainDescription($"T {FeaturesResources.in_} I<T> where T : class")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestGenericTypeParameterConstraint_Delegate() { await TestAsync( @"delegate void D<T>() where $$T : class;", MainDescription($"T {FeaturesResources.in_} D<T> where T : class")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestMinimallyQualifiedConstraint() { await TestAsync(@"class C<T> where $$T : IEnumerable<int>", MainDescription($"T {FeaturesResources.in_} C<T> where T : IEnumerable<int>")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task FullyQualifiedConstraint() { await TestAsync(@"class C<T> where $$T : System.Collections.Generic.IEnumerable<int>", MainDescription($"T {FeaturesResources.in_} C<T> where T : System.Collections.Generic.IEnumerable<int>")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestMethodReferenceInSameMethod() { await TestAsync( @"class C { void M() { M$$(); } }", MainDescription("void C.M()")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestMethodReferenceInSameMethodWithDocComment() { var markup = @" ///<summary>Hello World</summary> void M() { M$$(); }"; await TestInClassAsync(markup, MainDescription("void C.M()"), Documentation("Hello World")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestFieldInMethodBuiltIn() { var markup = @"int field; void M() { field$$ }"; await TestInClassAsync(markup, MainDescription($"({FeaturesResources.field}) int C.field")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestFieldInMethodBuiltIn2() { await TestInClassAsync( @"int field; void M() { int f = field$$; }", MainDescription($"({FeaturesResources.field}) int C.field")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestFieldInMethodBuiltInWithFieldInitializer() { await TestInClassAsync( @"int field = 1; void M() { int f = field $$; }"); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestOperatorBuiltIn() { await TestInMethodAsync( @"int x; x = x$$+1;", MainDescription("int int.operator +(int left, int right)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestOperatorBuiltIn1() { await TestInMethodAsync( @"int x; x = x$$ + 1;", MainDescription($"({FeaturesResources.local_variable}) int x")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestOperatorBuiltIn2() { await TestInMethodAsync( @"int x; x = x+$$x;", MainDescription($"({FeaturesResources.local_variable}) int x")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestOperatorBuiltIn3() { await TestInMethodAsync( @"int x; x = x +$$ x;", MainDescription("int int.operator +(int left, int right)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestOperatorBuiltIn4() { await TestInMethodAsync( @"int x; x = x + $$x;", MainDescription($"({FeaturesResources.local_variable}) int x")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestOperatorCustomTypeBuiltIn() { var markup = @"class C { static void M() { C c; c = c +$$ c; } }"; await TestAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestOperatorCustomTypeOverload() { var markup = @"class C { static void M() { C c; c = c +$$ c; } static C operator+(C a, C b) { return a; } }"; await TestAsync(markup, MainDescription("C C.operator +(C a, C b)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestFieldInMethodMinimal() { var markup = @"DateTime field; void M() { field$$ }"; await TestInClassAsync(markup, MainDescription($"({FeaturesResources.field}) DateTime C.field")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestFieldInMethodQualified() { var markup = @"System.IO.FileInfo file; void M() { file$$ }"; await TestInClassAsync(markup, MainDescription($"({FeaturesResources.field}) System.IO.FileInfo C.file")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestMemberOfStructFromSource() { var markup = @"struct MyStruct { public static int SomeField; } static class Test { int a = MyStruct.Some$$Field; }"; await TestAsync(markup, MainDescription($"({FeaturesResources.field}) static int MyStruct.SomeField")); } [WorkItem(538638, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538638")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestMemberOfStructFromSourceWithDocComment() { var markup = @"struct MyStruct { ///<summary>My Field</summary> public static int SomeField; } static class Test { int a = MyStruct.Some$$Field; }"; await TestAsync(markup, MainDescription($"({FeaturesResources.field}) static int MyStruct.SomeField"), Documentation("My Field")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestMemberOfStructInsideMethodFromSource() { var markup = @"struct MyStruct { public static int SomeField; } static class Test { static void Method() { int a = MyStruct.Some$$Field; } }"; await TestAsync(markup, MainDescription($"({FeaturesResources.field}) static int MyStruct.SomeField")); } [WorkItem(538638, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538638")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestMemberOfStructInsideMethodFromSourceWithDocComment() { var markup = @"struct MyStruct { ///<summary>My Field</summary> public static int SomeField; } static class Test { static void Method() { int a = MyStruct.Some$$Field; } }"; await TestAsync(markup, MainDescription($"({FeaturesResources.field}) static int MyStruct.SomeField"), Documentation("My Field")); } [WorkItem(538638, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538638")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestPartialMethodDocComment_01() { var markup = @"partial class MyClass { ///<summary>My Method Definition</summary> public partial void MyMethod(); ///<summary>My Method Implementation</summary> public partial void MyMethod() { } } static class Test { static void Method() { MyClass.My$$Method(); } }"; await TestAsync(markup, MainDescription($"void MyClass.MyMethod()"), Documentation("My Method Implementation")); } [WorkItem(538638, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538638")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestPartialMethodDocComment_02() { var markup = @"partial class MyClass { ///<summary>My Method Definition</summary> public partial void MyMethod(); public partial void MyMethod() { } } static class Test { static void Method() { MyClass.My$$Method(); } }"; await TestAsync(markup, MainDescription($"void MyClass.MyMethod()"), Documentation("My Method Definition")); } [WorkItem(538638, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538638")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestPartialMethodDocComment_03() { var markup = @"partial class MyClass { public partial void MyMethod(); ///<summary>My Method Implementation</summary> public partial void MyMethod() { } } static class Test { static void Method() { MyClass.My$$Method(); } }"; await TestAsync(markup, MainDescription($"void MyClass.MyMethod()"), Documentation("My Method Implementation")); } [WorkItem(538638, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538638")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestPartialMethodDocComment_04() { var markup = @"partial class MyClass { ///<summary>My Method Definition</summary> public partial void MyMethod(); } static class Test { static void Method() { MyClass.My$$Method(); } }"; await TestAsync(markup, MainDescription($"void MyClass.MyMethod()"), Documentation("My Method Definition")); } [WorkItem(538638, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538638")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestPartialMethodDocComment_05() { var markup = @"partial class MyClass { ///<summary>My Method Implementation</summary> public partial void MyMethod() { } } static class Test { static void Method() { MyClass.My$$Method(); } }"; await TestAsync(markup, MainDescription($"void MyClass.MyMethod()"), Documentation("My Method Implementation")); } [WorkItem(538638, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538638")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestPartialMethodDocComment_06() { var markup = @"partial class MyClass { ///<summary>My Method Definition</summary> partial void MyMethod(); partial void MyMethod() { } } static class Test { static void Method() { MyClass.My$$Method(); } }"; await TestAsync(markup, MainDescription($"void MyClass.MyMethod()"), Documentation("My Method Definition")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestMetadataFieldMinimal() { await TestInMethodAsync(@"DateTime dt = DateTime.MaxValue$$", MainDescription($"({FeaturesResources.field}) static readonly DateTime DateTime.MaxValue")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestMetadataFieldQualified1() { // NOTE: we qualify the field type, but not the type that contains the field in Dev10 var markup = @"class C { void M() { DateTime dt = System.DateTime.MaxValue$$ } }"; await TestAsync(markup, MainDescription($"({FeaturesResources.field}) static readonly System.DateTime System.DateTime.MaxValue")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestMetadataFieldQualified2() { await TestAsync( @"class C { void M() { DateTime dt = System.DateTime.MaxValue$$ } }", MainDescription($"({FeaturesResources.field}) static readonly System.DateTime System.DateTime.MaxValue")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestMetadataFieldQualified3() { await TestAsync( @"using System; class C { void M() { DateTime dt = System.DateTime.MaxValue$$ } }", MainDescription($"({FeaturesResources.field}) static readonly DateTime DateTime.MaxValue")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ConstructedGenericField() { await TestAsync( @"class C<T> { public T Field; } class D { void M() { new C<int>().Fi$$eld.ToString(); } }", MainDescription($"({FeaturesResources.field}) int C<int>.Field")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task UnconstructedGenericField() { await TestAsync( @"class C<T> { public T Field; void M() { Fi$$eld.ToString(); } }", MainDescription($"({FeaturesResources.field}) T C<T>.Field")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestIntegerLiteral() { await TestInMethodAsync(@"int f = 37$$", MainDescription("struct System.Int32")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestTrueKeyword() { await TestInMethodAsync(@"bool f = true$$", MainDescription("struct System.Boolean")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestFalseKeyword() { await TestInMethodAsync(@"bool f = false$$", MainDescription("struct System.Boolean")); } [WorkItem(26027, "https://github.com/dotnet/roslyn/issues/26027")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestNullLiteral() { await TestInMethodAsync(@"string f = null$$", MainDescription("class System.String")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestNullLiteralWithVar() => await TestInMethodAsync(@"var f = null$$"); [WorkItem(26027, "https://github.com/dotnet/roslyn/issues/26027")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestDefaultLiteral() { await TestInMethodAsync(@"string f = default$$", MainDescription("class System.String")); } [WorkItem(756226, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756226")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestAwaitKeywordOnGenericTaskReturningAsync() { var markup = @"using System.Threading.Tasks; class C { public async Task<int> Calc() { aw$$ait Calc(); return 5; } }"; await TestAsync(markup, MainDescription(string.Format(FeaturesResources.Awaited_task_returns_0, "struct System.Int32"))); } [WorkItem(756226, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756226")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestAwaitKeywordInDeclarationStatement() { var markup = @"using System.Threading.Tasks; class C { public async Task<int> Calc() { var x = $$await Calc(); return 5; } }"; await TestAsync(markup, MainDescription(string.Format(FeaturesResources.Awaited_task_returns_0, "struct System.Int32"))); } [WorkItem(756226, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756226")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestAwaitKeywordOnTaskReturningAsync() { var markup = @"using System.Threading.Tasks; class C { public async void Calc() { aw$$ait Task.Delay(100); } }"; await TestAsync(markup, MainDescription(FeaturesResources.Awaited_task_returns_no_value)); } [WorkItem(756226, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756226"), WorkItem(756337, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756337")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestNestedAwaitKeywords1() { var markup = @"using System; using System.Threading.Tasks; class AsyncExample2 { async Task<Task<int>> AsyncMethod() { return NewMethod(); } private static Task<int> NewMethod() { int hours = 24; return hours; } async Task UseAsync() { Func<Task<int>> lambda = async () => { return await await AsyncMethod(); }; int result = await await AsyncMethod(); Task<Task<int>> resultTask = AsyncMethod(); result = await awa$$it resultTask; result = await lambda(); } }"; await TestAsync(markup, MainDescription(string.Format(FeaturesResources.Awaited_task_returns_0, $"({CSharpFeaturesResources.awaitable}) class System.Threading.Tasks.Task<TResult>")), TypeParameterMap($"\r\nTResult {FeaturesResources.is_} int")); } [WorkItem(756226, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756226")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestNestedAwaitKeywords2() { var markup = @"using System; using System.Threading.Tasks; class AsyncExample2 { async Task<Task<int>> AsyncMethod() { return NewMethod(); } private static Task<int> NewMethod() { int hours = 24; return hours; } async Task UseAsync() { Func<Task<int>> lambda = async () => { return await await AsyncMethod(); }; int result = await await AsyncMethod(); Task<Task<int>> resultTask = AsyncMethod(); result = awa$$it await resultTask; result = await lambda(); } }"; await TestAsync(markup, MainDescription(string.Format(FeaturesResources.Awaited_task_returns_0, "struct System.Int32"))); } [WorkItem(756226, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756226"), WorkItem(756337, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756337")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestAwaitablePrefixOnCustomAwaiter() { var markup = @"using System; using System.Runtime.CompilerServices; using System.Threading.Tasks; using Z = $$C; class C { public MyAwaiter GetAwaiter() { throw new NotImplementedException(); } } class MyAwaiter : INotifyCompletion { public void OnCompleted(Action continuation) { throw new NotImplementedException(); } public bool IsCompleted { get { throw new NotImplementedException(); } } public void GetResult() { } }"; await TestAsync(markup, MainDescription($"({CSharpFeaturesResources.awaitable}) class C")); } [WorkItem(756226, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756226"), WorkItem(756337, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756337")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestTaskType() { var markup = @"using System.Threading.Tasks; class C { public void Calc() { Task$$ v1; } }"; await TestAsync(markup, MainDescription($"({CSharpFeaturesResources.awaitable}) class System.Threading.Tasks.Task")); } [WorkItem(756226, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756226"), WorkItem(756337, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756337")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestTaskOfTType() { var markup = @"using System; using System.Threading.Tasks; class C { public void Calc() { Task$$<int> v1; } }"; await TestAsync(markup, MainDescription($"({CSharpFeaturesResources.awaitable}) class System.Threading.Tasks.Task<TResult>"), TypeParameterMap($"\r\nTResult {FeaturesResources.is_} int")); } [WorkItem(7100, "https://github.com/dotnet/roslyn/issues/7100")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestDynamicIsntAwaitable() { var markup = @" class C { dynamic D() { return null; } void M() { D$$(); } } "; await TestAsync(markup, MainDescription("dynamic C.D()")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestStringLiteral() { await TestInMethodAsync(@"string f = ""Goo""$$", MainDescription("class System.String")); } [WorkItem(1280, "https://github.com/dotnet/roslyn/issues/1280")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestVerbatimStringLiteral() { await TestInMethodAsync(@"string f = @""cat""$$", MainDescription("class System.String")); } [WorkItem(1280, "https://github.com/dotnet/roslyn/issues/1280")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestInterpolatedStringLiteral() { await TestInMethodAsync(@"string f = $""cat""$$", MainDescription("class System.String")); await TestInMethodAsync(@"string f = $""c$$at""", MainDescription("class System.String")); await TestInMethodAsync(@"string f = $""$$cat""", MainDescription("class System.String")); await TestInMethodAsync(@"string f = $""cat {1$$ + 2} dog""", MainDescription("struct System.Int32")); } [WorkItem(1280, "https://github.com/dotnet/roslyn/issues/1280")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestVerbatimInterpolatedStringLiteral() { await TestInMethodAsync(@"string f = $@""cat""$$", MainDescription("class System.String")); await TestInMethodAsync(@"string f = $@""c$$at""", MainDescription("class System.String")); await TestInMethodAsync(@"string f = $@""$$cat""", MainDescription("class System.String")); await TestInMethodAsync(@"string f = $@""cat {1$$ + 2} dog""", MainDescription("struct System.Int32")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestCharLiteral() { await TestInMethodAsync(@"string f = 'x'$$", MainDescription("struct System.Char")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task DynamicKeyword() { await TestInMethodAsync( @"dyn$$amic dyn;", MainDescription("dynamic"), Documentation(FeaturesResources.Represents_an_object_whose_operations_will_be_resolved_at_runtime)); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task DynamicField() { await TestInClassAsync( @"dynamic dyn; void M() { d$$yn.Goo(); }", MainDescription($"({FeaturesResources.field}) dynamic C.dyn")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task LocalProperty_Minimal() { await TestInClassAsync( @"DateTime Prop { get; set; } void M() { P$$rop.ToString(); }", MainDescription("DateTime C.Prop { get; set; }")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task LocalProperty_Minimal_PrivateSet() { await TestInClassAsync( @"public DateTime Prop { get; private set; } void M() { P$$rop.ToString(); }", MainDescription("DateTime C.Prop { get; private set; }")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task LocalProperty_Minimal_PrivateSet1() { await TestInClassAsync( @"protected internal int Prop { get; private set; } void M() { P$$rop.ToString(); }", MainDescription("int C.Prop { get; private set; }")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task LocalProperty_Qualified() { await TestInClassAsync( @"System.IO.FileInfo Prop { get; set; } void M() { P$$rop.ToString(); }", MainDescription("System.IO.FileInfo C.Prop { get; set; }")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NonLocalProperty_Minimal() { await TestInMethodAsync(@"DateTime.No$$w.ToString();", MainDescription("DateTime DateTime.Now { get; }")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NonLocalProperty_Qualified() { await TestInMethodAsync( @"System.IO.FileInfo f; f.Att$$ributes.ToString();", MainDescription("System.IO.FileAttributes System.IO.FileSystemInfo.Attributes { get; set; }")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ConstructedGenericProperty() { await TestAsync( @"class C<T> { public T Property { get; set } } class D { void M() { new C<int>().Pro$$perty.ToString(); } }", MainDescription("int C<int>.Property { get; set; }")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task UnconstructedGenericProperty() { await TestAsync( @"class C<T> { public T Property { get; set} void M() { Pro$$perty.ToString(); } }", MainDescription("T C<T>.Property { get; set; }")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ValueInProperty() { await TestInClassAsync( @"public DateTime Property { set { goo = val$$ue; } }", MainDescription($"({FeaturesResources.parameter}) DateTime value")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task EnumTypeName() { await TestInMethodAsync(@"Consol$$eColor c", MainDescription("enum System.ConsoleColor")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(52490, "https://github.com/dotnet/roslyn/issues/52490")] public async Task EnumNonDefaultUnderlyingType_Definition() { await TestInClassAsync(@"enum E$$ : byte { A, B }", MainDescription("enum C.E : byte")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(52490, "https://github.com/dotnet/roslyn/issues/52490")] public async Task EnumNonDefaultUnderlyingType_AsField() { await TestInClassAsync(@" enum E : byte { A, B } private E$$ _E; ", MainDescription("enum C.E : byte")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(52490, "https://github.com/dotnet/roslyn/issues/52490")] public async Task EnumNonDefaultUnderlyingType_AsProperty() { await TestInClassAsync(@" enum E : byte { A, B } private E$$ E{ get; set; }; ", MainDescription("enum C.E : byte")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(52490, "https://github.com/dotnet/roslyn/issues/52490")] public async Task EnumNonDefaultUnderlyingType_AsParameter() { await TestInClassAsync(@" enum E : byte { A, B } private void M(E$$ e) { } ", MainDescription("enum C.E : byte")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(52490, "https://github.com/dotnet/roslyn/issues/52490")] public async Task EnumNonDefaultUnderlyingType_AsReturnType() { await TestInClassAsync(@" enum E : byte { A, B } private E$$ M() { } ", MainDescription("enum C.E : byte")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(52490, "https://github.com/dotnet/roslyn/issues/52490")] public async Task EnumNonDefaultUnderlyingType_AsLocal() { await TestInClassAsync(@" enum E : byte { A, B } private void M() { E$$ e = default; } ", MainDescription("enum C.E : byte")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(52490, "https://github.com/dotnet/roslyn/issues/52490")] public async Task EnumNonDefaultUnderlyingType_OnMemberAccessOnType() { await TestInClassAsync(@" enum E : byte { A, B } private void M() { var ea = E$$.A; } ", MainDescription("enum C.E : byte")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(52490, "https://github.com/dotnet/roslyn/issues/52490")] public async Task EnumNonDefaultUnderlyingType_NotOnMemberAccessOnMember() { await TestInClassAsync(@" enum E : byte { A, B } private void M() { var ea = E.A$$; } ", MainDescription("E.A = 0")); } [Theory, WorkItem(52490, "https://github.com/dotnet/roslyn/issues/52490")] [InlineData("byte", "byte")] [InlineData("byte", "System.Byte")] [InlineData("sbyte", "sbyte")] [InlineData("sbyte", "System.SByte")] [InlineData("short", "short")] [InlineData("short", "System.Int16")] [InlineData("ushort", "ushort")] [InlineData("ushort", "System.UInt16")] // int is the default type and is not shown [InlineData("uint", "uint")] [InlineData("uint", "System.UInt32")] [InlineData("long", "long")] [InlineData("long", "System.Int64")] [InlineData("ulong", "ulong")] [InlineData("ulong", "System.UInt64")] public async Task EnumNonDefaultUnderlyingType_ShowForNonDefaultTypes(string displayTypeName, string underlyingTypeName) { await TestInClassAsync(@$" enum E$$ : {underlyingTypeName} {{ A, B }}", MainDescription($"enum C.E : {displayTypeName}")); } [Theory, WorkItem(52490, "https://github.com/dotnet/roslyn/issues/52490")] [InlineData("")] [InlineData(": int")] [InlineData(": System.Int32")] public async Task EnumNonDefaultUnderlyingType_DontShowForDefaultType(string defaultType) { await TestInClassAsync(@$" enum E$$ {defaultType} {{ A, B }}", MainDescription("enum C.E")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task EnumMemberNameFromMetadata() { await TestInMethodAsync(@"ConsoleColor c = ConsoleColor.Bla$$ck", MainDescription("ConsoleColor.Black = 0")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task FlagsEnumMemberNameFromMetadata1() { await TestInMethodAsync(@"AttributeTargets a = AttributeTargets.Cl$$ass", MainDescription("AttributeTargets.Class = 4")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task FlagsEnumMemberNameFromMetadata2() { await TestInMethodAsync(@"AttributeTargets a = AttributeTargets.A$$ll", MainDescription("AttributeTargets.All = AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Parameter | AttributeTargets.Delegate | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task EnumMemberNameFromSource1() { await TestAsync( @"enum E { A = 1 << 0, B = 1 << 1, C = 1 << 2 } class C { void M() { var e = E.B$$; } }", MainDescription("E.B = 1 << 1")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task EnumMemberNameFromSource2() { await TestAsync( @"enum E { A, B, C } class C { void M() { var e = E.B$$; } }", MainDescription("E.B = 1")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Parameter_InMethod_Minimal() { await TestInClassAsync( @"void M(DateTime dt) { d$$t.ToString();", MainDescription($"({FeaturesResources.parameter}) DateTime dt")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Parameter_InMethod_Qualified() { await TestInClassAsync( @"void M(System.IO.FileInfo fileInfo) { file$$Info.ToString();", MainDescription($"({FeaturesResources.parameter}) System.IO.FileInfo fileInfo")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Parameter_FromReferenceToNamedParameter() { await TestInMethodAsync(@"Console.WriteLine(va$$lue: ""Hi"");", MainDescription($"({FeaturesResources.parameter}) string value")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Parameter_DefaultValue() { // NOTE: Dev10 doesn't show the default value, but it would be nice if we did. // NOTE: The "DefaultValue" property isn't implemented yet. await TestInClassAsync( @"void M(int param = 42) { para$$m.ToString(); }", MainDescription($"({FeaturesResources.parameter}) int param = 42")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Parameter_Params() { await TestInClassAsync( @"void M(params DateTime[] arg) { ar$$g.ToString(); }", MainDescription($"({FeaturesResources.parameter}) params DateTime[] arg")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Parameter_Ref() { await TestInClassAsync( @"void M(ref DateTime arg) { ar$$g.ToString(); }", MainDescription($"({FeaturesResources.parameter}) ref DateTime arg")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Parameter_Out() { await TestInClassAsync( @"void M(out DateTime arg) { ar$$g.ToString(); }", MainDescription($"({FeaturesResources.parameter}) out DateTime arg")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Local_Minimal() { await TestInMethodAsync( @"DateTime dt; d$$t.ToString();", MainDescription($"({FeaturesResources.local_variable}) DateTime dt")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Local_Qualified() { await TestInMethodAsync( @"System.IO.FileInfo fileInfo; file$$Info.ToString();", MainDescription($"({FeaturesResources.local_variable}) System.IO.FileInfo fileInfo")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Method_MetadataOverload() { await TestInMethodAsync("Console.Write$$Line();", MainDescription($"void Console.WriteLine() (+ 18 {FeaturesResources.overloads_})")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Method_SimpleWithOverload() { await TestInClassAsync( @"void Method() { Met$$hod(); } void Method(int i) { }", MainDescription($"void C.Method() (+ 1 {FeaturesResources.overload})")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Method_MoreOverloads() { await TestInClassAsync( @"void Method() { Met$$hod(null); } void Method(int i) { } void Method(DateTime dt) { } void Method(System.IO.FileInfo fileInfo) { }", MainDescription($"void C.Method(System.IO.FileInfo fileInfo) (+ 3 {FeaturesResources.overloads_})")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Method_SimpleInSameClass() { await TestInClassAsync( @"DateTime GetDate(System.IO.FileInfo ft) { Get$$Date(null); }", MainDescription("DateTime C.GetDate(System.IO.FileInfo ft)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Method_OptionalParameter() { await TestInClassAsync( @"void M() { Met$$hod(); } void Method(int i = 0) { }", MainDescription("void C.Method([int i = 0])")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Method_OptionalDecimalParameter() { await TestInClassAsync( @"void Goo(decimal x$$yz = 10) { }", MainDescription($"({FeaturesResources.parameter}) decimal xyz = 10")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Method_Generic() { // Generic method don't get the instantiation info yet. NOTE: We don't display // constraint info in Dev10. Should we? await TestInClassAsync( @"TOut Goo<TIn, TOut>(TIn arg) where TIn : IEquatable<TIn> { Go$$o<int, DateTime>(37); }", MainDescription("DateTime C.Goo<int, DateTime>(int arg)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Method_UnconstructedGeneric() { await TestInClassAsync( @"TOut Goo<TIn, TOut>(TIn arg) { Go$$o<TIn, TOut>(default(TIn); }", MainDescription("TOut C.Goo<TIn, TOut>(TIn arg)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Method_Inferred() { await TestInClassAsync( @"void Goo<TIn>(TIn arg) { Go$$o(42); }", MainDescription("void C.Goo<int>(int arg)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Method_MultipleParams() { await TestInClassAsync( @"void Goo(DateTime dt, System.IO.FileInfo fi, int number) { Go$$o(DateTime.Now, null, 32); }", MainDescription("void C.Goo(DateTime dt, System.IO.FileInfo fi, int number)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Method_OptionalParam() { // NOTE - Default values aren't actually returned by symbols yet. await TestInClassAsync( @"void Goo(int num = 42) { Go$$o(); }", MainDescription("void C.Goo([int num = 42])")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Method_ParameterModifiers() { // NOTE - Default values aren't actually returned by symbols yet. await TestInClassAsync( @"void Goo(ref DateTime dt, out System.IO.FileInfo fi, params int[] numbers) { Go$$o(DateTime.Now, null, 32); }", MainDescription("void C.Goo(ref DateTime dt, out System.IO.FileInfo fi, params int[] numbers)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Constructor() { await TestInClassAsync( @"public C() { } void M() { new C$$().ToString(); }", MainDescription("C.C()")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Constructor_Overloads() { await TestInClassAsync( @"public C() { } public C(DateTime dt) { } public C(int i) { } void M() { new C$$(DateTime.MaxValue).ToString(); }", MainDescription($"C.C(DateTime dt) (+ 2 {FeaturesResources.overloads_})")); } /// <summary> /// Regression for 3923 /// </summary> [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Constructor_OverloadFromStringLiteral() { await TestInMethodAsync( @"new InvalidOperatio$$nException("""");", MainDescription($"InvalidOperationException.InvalidOperationException(string message) (+ 2 {FeaturesResources.overloads_})")); } /// <summary> /// Regression for 3923 /// </summary> [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Constructor_UnknownType() { await TestInvalidTypeInClassAsync( @"void M() { new G$$oo(); }"); } /// <summary> /// Regression for 3923 /// </summary> [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Constructor_OverloadFromProperty() { await TestInMethodAsync( @"new InvalidOperatio$$nException(this.GetType().Name);", MainDescription($"InvalidOperationException.InvalidOperationException(string message) (+ 2 {FeaturesResources.overloads_})")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Constructor_Metadata() { await TestInMethodAsync( @"new Argument$$NullException();", MainDescription($"ArgumentNullException.ArgumentNullException() (+ 3 {FeaturesResources.overloads_})")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Constructor_MetadataQualified() { await TestInMethodAsync(@"new System.IO.File$$Info(null);", MainDescription("System.IO.FileInfo.FileInfo(string fileName)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task InterfaceProperty() { await TestInMethodAsync( @"interface I { string Name$$ { get; set; } }", MainDescription("string I.Name { get; set; }")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ExplicitInterfacePropertyImplementation() { await TestInMethodAsync( @"interface I { string Name { get; set; } } class C : I { string IEmployee.Name$$ { get { return """"; } set { } } }", MainDescription("string C.Name { get; set; }")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Operator() { await TestInClassAsync( @"public static C operator +(C left, C right) { return null; } void M(C left, C right) { return left +$$ right; }", MainDescription("C C.operator +(C left, C right)")); } #pragma warning disable CA2243 // Attribute string literals should parse correctly [WorkItem(792629, "generic type parameter constraints for methods in quick info")] #pragma warning restore CA2243 // Attribute string literals should parse correctly [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task GenericMethodWithConstraintsAtDeclaration() { await TestInClassAsync( @"TOut G$$oo<TIn, TOut>(TIn arg) where TIn : IEquatable<TIn> { }", MainDescription("TOut C.Goo<TIn, TOut>(TIn arg) where TIn : IEquatable<TIn>")); } #pragma warning disable CA2243 // Attribute string literals should parse correctly [WorkItem(792629, "generic type parameter constraints for methods in quick info")] #pragma warning restore CA2243 // Attribute string literals should parse correctly [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task GenericMethodWithMultipleConstraintsAtDeclaration() { await TestInClassAsync( @"TOut Goo<TIn, TOut>(TIn arg) where TIn : Employee, new() { Go$$o<TIn, TOut>(default(TIn); }", MainDescription("TOut C.Goo<TIn, TOut>(TIn arg) where TIn : Employee, new()")); } #pragma warning disable CA2243 // Attribute string literals should parse correctly [WorkItem(792629, "generic type parameter constraints for methods in quick info")] #pragma warning restore CA2243 // Attribute string literals should parse correctly [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task UnConstructedGenericMethodWithConstraintsAtInvocation() { await TestInClassAsync( @"TOut Goo<TIn, TOut>(TIn arg) where TIn : Employee { Go$$o<TIn, TOut>(default(TIn); }", MainDescription("TOut C.Goo<TIn, TOut>(TIn arg) where TIn : Employee")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task GenericTypeWithConstraintsAtDeclaration() { await TestAsync( @"public class Employee : IComparable<Employee> { public int CompareTo(Employee other) { throw new NotImplementedException(); } } class Emplo$$yeeList<T> : IEnumerable<T> where T : Employee, System.IComparable<T>, new() { }", MainDescription("class EmployeeList<T> where T : Employee, System.IComparable<T>, new()")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task GenericType() { await TestAsync( @"class T1<T11> { $$T11 i; }", MainDescription($"T11 {FeaturesResources.in_} T1<T11>")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task GenericMethod() { await TestInClassAsync( @"static void Meth1<T1>(T1 i) where T1 : struct { $$T1 i; }", MainDescription($"T1 {FeaturesResources.in_} C.Meth1<T1> where T1 : struct")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Var() { await TestInMethodAsync( @"var x = new Exception(); var y = $$x;", MainDescription($"({FeaturesResources.local_variable}) Exception x")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NullableReference() { await TestWithOptionsAsync( Options.Regular.WithLanguageVersion(LanguageVersion.CSharp8), @"class A<T> { } class B { static void M() { A<B?>? x = null!; var y = x; $$y.ToString(); } }", // https://github.com/dotnet/roslyn/issues/26198 public API should show inferred nullability MainDescription($"({FeaturesResources.local_variable}) A<B?> y")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(26648, "https://github.com/dotnet/roslyn/issues/26648")] public async Task NullableReference_InMethod() { var code = @" class G { void M() { C c; c.Go$$o(); } } public class C { public string? Goo(IEnumerable<object?> arg) { } }"; await TestWithOptionsAsync( Options.Regular.WithLanguageVersion(LanguageVersion.CSharp8), code, MainDescription("string? C.Goo(IEnumerable<object?> arg)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NestedInGeneric() { await TestInMethodAsync( @"List<int>.Enu$$merator e;", MainDescription("struct System.Collections.Generic.List<T>.Enumerator"), TypeParameterMap($"\r\nT {FeaturesResources.is_} int")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NestedGenericInGeneric() { await TestAsync( @"class Outer<T> { class Inner<U> { } static void M() { Outer<int>.I$$nner<string> e; } }", MainDescription("class Outer<T>.Inner<U>"), TypeParameterMap( Lines($"\r\nT {FeaturesResources.is_} int", $"U {FeaturesResources.is_} string"))); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ObjectInitializer1() { await TestInClassAsync( @"void M() { var x = new test() { $$z = 5 }; } class test { public int z; }", MainDescription($"({FeaturesResources.field}) int test.z")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ObjectInitializer2() { await TestInMethodAsync( @"class C { void M() { var x = new test() { z = $$5 }; } class test { public int z; } }", MainDescription("struct System.Int32")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(537880, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537880")] public async Task TypeArgument() { await TestAsync( @"class C<T, Y> { void M() { C<int, DateTime> variable; $$variable = new C<int, DateTime>(); } }", MainDescription($"({FeaturesResources.local_variable}) C<int, DateTime> variable")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ForEachLoop_1() { await TestInMethodAsync( @"int bb = 555; bb = bb + 1; foreach (int cc in new int[]{ 1,2,3}){ c$$c = 1; bb = bb + 21; }", MainDescription($"({FeaturesResources.local_variable}) int cc")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TryCatchFinally_1() { await TestInMethodAsync( @"try { int aa = 555; a$$a = aa + 1; } catch (Exception ex) { } finally { }", MainDescription($"({FeaturesResources.local_variable}) int aa")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TryCatchFinally_2() { await TestInMethodAsync( @"try { } catch (Exception ex) { var y = e$$x; var z = y; } finally { }", MainDescription($"({FeaturesResources.local_variable}) Exception ex")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TryCatchFinally_3() { await TestInMethodAsync( @"try { } catch (Exception ex) { var aa = 555; aa = a$$a + 1; } finally { }", MainDescription($"({FeaturesResources.local_variable}) int aa")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TryCatchFinally_4() { await TestInMethodAsync( @"try { } catch (Exception ex) { } finally { int aa = 555; aa = a$$a + 1; }", MainDescription($"({FeaturesResources.local_variable}) int aa")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task GenericVariable() { await TestAsync( @"class C<T, Y> { void M() { C<int, DateTime> variable; var$$iable = new C<int, DateTime>(); } }", MainDescription($"({FeaturesResources.local_variable}) C<int, DateTime> variable")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestInstantiation() { await TestAsync( @"using System.Collections.Generic; class Program<T> { static void Main(string[] args) { var p = new Dictio$$nary<int, string>(); } }", MainDescription($"Dictionary<int, string>.Dictionary() (+ 5 {FeaturesResources.overloads_})")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestUsingAlias_Bug4141() { await TestAsync( @"using X = A.C; class A { public class C { } } class D : X$$ { }", MainDescription(@"class A.C")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestFieldOnDeclaration() { await TestInClassAsync( @"DateTime fie$$ld;", MainDescription($"({FeaturesResources.field}) DateTime C.field")); } [WorkItem(538767, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538767")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestGenericErrorFieldOnDeclaration() { await TestInClassAsync( @"NonExistentType<int> fi$$eld;", MainDescription($"({FeaturesResources.field}) NonExistentType<int> C.field")); } [WorkItem(538822, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538822")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestDelegateType() { await TestInClassAsync( @"Fun$$c<int, string> field;", MainDescription("delegate TResult System.Func<in T, out TResult>(T arg)"), TypeParameterMap( Lines($"\r\nT {FeaturesResources.is_} int", $"TResult {FeaturesResources.is_} string"))); } [WorkItem(538824, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538824")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestOnDelegateInvocation() { await TestAsync( @"class Program { delegate void D1(); static void Main() { D1 d = Main; $$d(); } }", MainDescription($"({FeaturesResources.local_variable}) D1 d")); } [WorkItem(539240, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539240")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestOnArrayCreation1() { await TestAsync( @"class Program { static void Main() { int[] a = n$$ew int[0]; } }", MainDescription("int[]")); } [WorkItem(539240, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539240")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestOnArrayCreation2() { await TestAsync( @"class Program { static void Main() { int[] a = new i$$nt[0]; } }", MainDescription("struct System.Int32")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Constructor_ImplicitObjectCreation() { await TestAsync( @"class C { static void Main() { C c = ne$$w(); } } ", MainDescription("C.C()")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Constructor_ImplicitObjectCreation_WithParameters() { await TestAsync( @"class C { C(int i) { } C(string s) { } static void Main() { C c = ne$$w(1); } } ", MainDescription($"C.C(int i) (+ 1 {FeaturesResources.overload})")); } [WorkItem(539841, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539841")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestIsNamedTypeAccessibleForErrorTypes() { await TestAsync( @"sealed class B<T1, T2> : A<B<T1, T2>> { protected sealed override B<A<T>, A$$<T>> N() { } } internal class A<T> { }", MainDescription("class A<T>")); } [WorkItem(540075, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540075")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestErrorType() { await TestAsync( @"using Goo = Goo; class C { void Main() { $$Goo } }", MainDescription("Goo")); } [WorkItem(16662, "https://github.com/dotnet/roslyn/issues/16662")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestShortDiscardInAssignment() { await TestAsync( @"class C { int M() { $$_ = M(); } }", MainDescription($"({FeaturesResources.discard}) int _")); } [WorkItem(16662, "https://github.com/dotnet/roslyn/issues/16662")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestUnderscoreLocalInAssignment() { await TestAsync( @"class C { int M() { var $$_ = M(); } }", MainDescription($"({FeaturesResources.local_variable}) int _")); } [WorkItem(16662, "https://github.com/dotnet/roslyn/issues/16662")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestShortDiscardInOutVar() { await TestAsync( @"class C { void M(out int i) { M(out $$_); i = 0; } }", MainDescription($"({FeaturesResources.discard}) int _")); } [WorkItem(16667, "https://github.com/dotnet/roslyn/issues/16667")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestDiscardInOutVar() { await TestAsync( @"class C { void M(out int i) { M(out var $$_); i = 0; } }"); // No quick info (see issue #16667) } [WorkItem(16667, "https://github.com/dotnet/roslyn/issues/16667")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestDiscardInIsPattern() { await TestAsync( @"class C { void M() { if (3 is int $$_) { } } }"); // No quick info (see issue #16667) } [WorkItem(16667, "https://github.com/dotnet/roslyn/issues/16667")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestDiscardInSwitchPattern() { await TestAsync( @"class C { void M() { switch (3) { case int $$_: return; } } }"); // No quick info (see issue #16667) } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestLambdaDiscardParameter_FirstDiscard() { await TestAsync( @"class C { void M() { System.Func<string, int, int> f = ($$_, _) => 1; } }", MainDescription($"({FeaturesResources.discard}) string _")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestLambdaDiscardParameter_SecondDiscard() { await TestAsync( @"class C { void M() { System.Func<string, int, int> f = (_, $$_) => 1; } }", MainDescription($"({FeaturesResources.discard}) int _")); } [WorkItem(540871, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540871")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestLiterals() { await TestAsync( @"class MyClass { MyClass() : this($$10) { intI = 2; } public MyClass(int i) { } static int intI = 1; public static int Main() { return 1; } }", MainDescription("struct System.Int32")); } [WorkItem(541444, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541444")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestErrorInForeach() { await TestAsync( @"class C { void Main() { foreach (int cc in null) { $$cc = 1; } } }", MainDescription($"({FeaturesResources.local_variable}) int cc")); } [WorkItem(541678, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541678")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestQuickInfoOnEvent() { await TestAsync( @"using System; public class SampleEventArgs { public SampleEventArgs(string s) { Text = s; } public String Text { get; private set; } } public class Publisher { public delegate void SampleEventHandler(object sender, SampleEventArgs e); public event SampleEventHandler SampleEvent; protected virtual void RaiseSampleEvent() { if (Sam$$pleEvent != null) SampleEvent(this, new SampleEventArgs(""Hello"")); } }", MainDescription("SampleEventHandler Publisher.SampleEvent")); } [WorkItem(542157, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542157")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestEvent() { await TestInMethodAsync(@"System.Console.CancelKeyPres$$s += null;", MainDescription("ConsoleCancelEventHandler Console.CancelKeyPress")); } [WorkItem(542157, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542157")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestEventPlusEqualsOperator() { await TestInMethodAsync(@"System.Console.CancelKeyPress +$$= null;", MainDescription("void Console.CancelKeyPress.add")); } [WorkItem(542157, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542157")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestEventMinusEqualsOperator() { await TestInMethodAsync(@"System.Console.CancelKeyPress -$$= null;", MainDescription("void Console.CancelKeyPress.remove")); } [WorkItem(541885, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541885")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestQuickInfoOnExtensionMethod() { await TestWithOptionsAsync(Options.Regular, @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { int[] values = { 1 }; bool isArray = 7.I$$n(values); } } public static class MyExtensions { public static bool In<T>(this T o, IEnumerable<T> items) { return true; } }", MainDescription($"({CSharpFeaturesResources.extension}) bool int.In<int>(IEnumerable<int> items)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestQuickInfoOnExtensionMethodOverloads() { await TestWithOptionsAsync(Options.Regular, @"using System; using System.Linq; class Program { static void Main(string[] args) { ""1"".Test$$Ext(); } } public static class Ex { public static void TestExt<T>(this T ex) { } public static void TestExt<T>(this T ex, T arg) { } public static void TestExt(this string ex, int arg) { } }", MainDescription($"({CSharpFeaturesResources.extension}) void string.TestExt<string>() (+ 2 {FeaturesResources.overloads_})")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestQuickInfoOnExtensionMethodOverloads2() { await TestWithOptionsAsync(Options.Regular, @"using System; using System.Linq; class Program { static void Main(string[] args) { ""1"".Test$$Ext(); } } public static class Ex { public static void TestExt<T>(this T ex) { } public static void TestExt<T>(this T ex, T arg) { } public static void TestExt(this int ex, int arg) { } }", MainDescription($"({CSharpFeaturesResources.extension}) void string.TestExt<string>() (+ 1 {FeaturesResources.overload})")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Query1() { await TestAsync( @"using System.Linq; class C { void M() { var q = from n in new int[] { 1, 2, 3, 4, 5 } select $$n; } }", MainDescription($"({FeaturesResources.range_variable}) int n")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Query2() { await TestAsync( @"using System.Linq; class C { void M() { var q = from n$$ in new int[] { 1, 2, 3, 4, 5 } select n; } }", MainDescription($"({FeaturesResources.range_variable}) int n")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Query3() { await TestAsync( @"class C { void M() { var q = from n in new int[] { 1, 2, 3, 4, 5 } select $$n; } }", MainDescription($"({FeaturesResources.range_variable}) ? n")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Query4() { await TestAsync( @"class C { void M() { var q = from n$$ in new int[] { 1, 2, 3, 4, 5 } select n; } }", MainDescription($"({FeaturesResources.range_variable}) ? n")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Query5() { await TestAsync( @"using System.Collections.Generic; using System.Linq; class C { void M() { var q = from n in new List<object>() select $$n; } }", MainDescription($"({FeaturesResources.range_variable}) object n")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Query6() { await TestAsync( @"using System.Collections.Generic; using System.Linq; class C { void M() { var q = from n$$ in new List<object>() select n; } }", MainDescription($"({FeaturesResources.range_variable}) object n")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Query7() { await TestAsync( @"using System.Collections.Generic; using System.Linq; class C { void M() { var q = from int n in new List<object>() select $$n; } }", MainDescription($"({FeaturesResources.range_variable}) int n")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Query8() { await TestAsync( @"using System.Collections.Generic; using System.Linq; class C { void M() { var q = from int n$$ in new List<object>() select n; } }", MainDescription($"({FeaturesResources.range_variable}) int n")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Query9() { await TestAsync( @"using System.Collections.Generic; using System.Linq; class C { void M() { var q = from x$$ in new List<List<int>>() from y in x select y; } }", MainDescription($"({FeaturesResources.range_variable}) List<int> x")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Query10() { await TestAsync( @"using System.Collections.Generic; using System.Linq; class C { void M() { var q = from x in new List<List<int>>() from y in $$x select y; } }", MainDescription($"({FeaturesResources.range_variable}) List<int> x")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Query11() { await TestAsync( @"using System.Collections.Generic; using System.Linq; class C { void M() { var q = from x in new List<List<int>>() from y$$ in x select y; } }", MainDescription($"({FeaturesResources.range_variable}) int y")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Query12() { await TestAsync( @"using System.Collections.Generic; using System.Linq; class C { void M() { var q = from x in new List<List<int>>() from y in x select $$y; } }", MainDescription($"({FeaturesResources.range_variable}) int y")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoSelectMappedEnumerable() { await TestInMethodAsync( @" var q = from i in new int[0] $$select i; ", MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.Select<int, int>(Func<int, int> selector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoSelectMappedQueryable() { await TestInMethodAsync( @" var q = from i in new int[0].AsQueryable() $$select i; ", MainDescription($"({CSharpFeaturesResources.extension}) IQueryable<int> IQueryable<int>.Select<int, int>(System.Linq.Expressions.Expression<Func<int, int>> selector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoSelectMappedCustom() { await TestAsync( @" using System; using System.Linq; namespace N { public static class LazyExt { public static Lazy<U> Select<T, U>(this Lazy<T> source, Func<T, U> selector) => new Lazy<U>(() => selector(source.Value)); } public class C { public void M() { var lazy = new Lazy<object>(); var q = from i in lazy $$select i; } } } ", MainDescription($"({CSharpFeaturesResources.extension}) Lazy<object> Lazy<object>.Select<object, object>(Func<object, object> selector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoSelectNotMapped() { await TestInMethodAsync( @" var q = from i in new int[0] where true $$select i; "); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoLet() { await TestInMethodAsync( @" var q = from i in new int[0] $$let j = true select i; ", MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<'a> IEnumerable<int>.Select<int, 'a>(Func<int, 'a> selector)"), AnonymousTypes($@" {FeaturesResources.Anonymous_Types_colon} 'a {FeaturesResources.is_} new {{ int i, bool j }}")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoWhere() { await TestInMethodAsync( @" var q = from i in new int[0] $$where true select i; ", MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.Where<int>(Func<int, bool> predicate)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoOrderByOneProperty() { await TestInMethodAsync( @" var q = from i in new int[0] $$orderby i select i; ", MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable<int> IEnumerable<int>.OrderBy<int, int>(Func<int, int> keySelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoOrderByOnePropertyWithOrdering1() { await TestInMethodAsync( @" var q = from i in new int[0] orderby i $$ascending select i; ", MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable<int> IEnumerable<int>.OrderBy<int, int>(Func<int, int> keySelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoOrderByOnePropertyWithOrdering2() { await TestInMethodAsync( @" var q = from i in new int[0] $$orderby i ascending select i; "); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoOrderByTwoPropertiesWithComma1() { await TestInMethodAsync( @" var q = from i in new int[0] orderby i$$, i select i; ", MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable<int> IOrderedEnumerable<int>.ThenBy<int, int>(Func<int, int> keySelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoOrderByTwoPropertiesWithComma2() { await TestInMethodAsync( @" var q = from i in new int[0] $$orderby i, i select i; ", MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable<int> IEnumerable<int>.OrderBy<int, int>(Func<int, int> keySelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoOrderByTwoPropertiesWithOrdering1() { await TestInMethodAsync( @" var q = from i in new int[0] $$orderby i, i ascending select i; ", MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable<int> IEnumerable<int>.OrderBy<int, int>(Func<int, int> keySelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoOrderByTwoPropertiesWithOrdering2() { await TestInMethodAsync( @" var q = from i in new int[0] orderby i,$$ i ascending select i; "); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoOrderByTwoPropertiesWithOrdering3() { await TestInMethodAsync( @" var q = from i in new int[0] orderby i, i $$ascending select i; ", MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable<int> IOrderedEnumerable<int>.ThenBy<int, int>(Func<int, int> keySelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoOrderByTwoPropertiesWithOrderingOnEach1() { await TestInMethodAsync( @" var q = from i in new int[0] $$orderby i ascending, i ascending select i; "); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoOrderByTwoPropertiesWithOrderingOnEach2() { await TestInMethodAsync( @" var q = from i in new int[0] orderby i $$ascending, i ascending select i; ", MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable<int> IEnumerable<int>.OrderBy<int, int>(Func<int, int> keySelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoOrderByTwoPropertiesWithOrderingOnEach3() { await TestInMethodAsync( @" var q = from i in new int[0] orderby i ascending ,$$ i ascending select i; "); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoOrderByTwoPropertiesWithOrderingOnEach4() { await TestInMethodAsync( @" var q = from i in new int[0] orderby i ascending, i $$ascending select i; ", MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable<int> IOrderedEnumerable<int>.ThenBy<int, int>(Func<int, int> keySelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoOrderByIncomplete() { await TestInMethodAsync( @" var q = from i in new int[0] where i > 0 orderby$$ ", MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable<int> IEnumerable<int>.OrderBy<int, ?>(Func<int, ?> keySelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoSelectMany1() { await TestInMethodAsync( @" var q = from i1 in new int[0] $$from i2 in new int[0] select i1; ", MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.SelectMany<int, int, int>(Func<int, IEnumerable<int>> collectionSelector, Func<int, int, int> resultSelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoSelectMany2() { await TestInMethodAsync( @" var q = from i1 in new int[0] from i2 $$in new int[0] select i1; ", MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.SelectMany<int, int, int>(Func<int, IEnumerable<int>> collectionSelector, Func<int, int, int> resultSelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoGroupBy1() { await TestInMethodAsync( @" var q = from i in new int[0] $$group i by i; ", MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<IGrouping<int, int>> IEnumerable<int>.GroupBy<int, int>(Func<int, int> keySelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoGroupBy2() { await TestInMethodAsync( @" var q = from i in new int[0] group i $$by i; ", MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<IGrouping<int, int>> IEnumerable<int>.GroupBy<int, int>(Func<int, int> keySelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoGroupByInto() { await TestInMethodAsync( @" var q = from i in new int[0] $$group i by i into g select g; ", MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<IGrouping<int, int>> IEnumerable<int>.GroupBy<int, int>(Func<int, int> keySelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoJoin1() { await TestInMethodAsync( @" var q = from i1 in new int[0] $$join i2 in new int[0] on i1 equals i2 select i1; ", MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.Join<int, int, int, int>(IEnumerable<int> inner, Func<int, int> outerKeySelector, Func<int, int> innerKeySelector, Func<int, int, int> resultSelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoJoin2() { await TestInMethodAsync( @" var q = from i1 in new int[0] join i2 $$in new int[0] on i1 equals i2 select i1; ", MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.Join<int, int, int, int>(IEnumerable<int> inner, Func<int, int> outerKeySelector, Func<int, int> innerKeySelector, Func<int, int, int> resultSelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoJoin3() { await TestInMethodAsync( @" var q = from i1 in new int[0] join i2 in new int[0] $$on i1 equals i2 select i1; ", MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.Join<int, int, int, int>(IEnumerable<int> inner, Func<int, int> outerKeySelector, Func<int, int> innerKeySelector, Func<int, int, int> resultSelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoJoin4() { await TestInMethodAsync( @" var q = from i1 in new int[0] join i2 in new int[0] on i1 $$equals i2 select i1; ", MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.Join<int, int, int, int>(IEnumerable<int> inner, Func<int, int> outerKeySelector, Func<int, int> innerKeySelector, Func<int, int, int> resultSelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoJoinInto1() { await TestInMethodAsync( @" var q = from i1 in new int[0] $$join i2 in new int[0] on i1 equals i2 into g select g; ", MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<IEnumerable<int>> IEnumerable<int>.GroupJoin<int, int, int, IEnumerable<int>>(IEnumerable<int> inner, Func<int, int> outerKeySelector, Func<int, int> innerKeySelector, Func<int, IEnumerable<int>, IEnumerable<int>> resultSelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoJoinInto2() { await TestInMethodAsync( @" var q = from i1 in new int[0] join i2 in new int[0] on i1 equals i2 $$into g select g; "); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoFromMissing() { await TestInMethodAsync( @" var q = $$from i in new int[0] select i; "); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoRangeVariableSimple1() { await TestInMethodAsync( @" var q = $$from double i in new int[0] select i; ", MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<double> System.Collections.IEnumerable.Cast<double>()")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoRangeVariableSimple2() { await TestInMethodAsync( @" var q = from double i $$in new int[0] select i; ", MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<double> System.Collections.IEnumerable.Cast<double>()")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoRangeVariableSelectMany1() { await TestInMethodAsync( @" var q = from i in new int[0] $$from double d in new int[0] select i; ", MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.SelectMany<int, double, int>(Func<int, IEnumerable<double>> collectionSelector, Func<int, double, int> resultSelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoRangeVariableSelectMany2() { await TestInMethodAsync( @" var q = from i in new int[0] from double d $$in new int[0] select i; ", MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<double> System.Collections.IEnumerable.Cast<double>()")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoRangeVariableJoin1() { await TestInMethodAsync( @" var q = from i1 in new int[0] $$join int i2 in new double[0] on i1 equals i2 select i1; ", MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.Join<int, int, int, int>(IEnumerable<int> inner, Func<int, int> outerKeySelector, Func<int, int> innerKeySelector, Func<int, int, int> resultSelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoRangeVariableJoin2() { await TestInMethodAsync( @" var q = from i1 in new int[0] join int i2 $$in new double[0] on i1 equals i2 select i1; ", MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> System.Collections.IEnumerable.Cast<int>()")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoRangeVariableJoin3() { await TestInMethodAsync( @" var q = from i1 in new int[0] join int i2 in new double[0] $$on i1 equals i2 select i1; ", MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.Join<int, int, int, int>(IEnumerable<int> inner, Func<int, int> outerKeySelector, Func<int, int> innerKeySelector, Func<int, int, int> resultSelector)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")] public async Task QueryMethodinfoRangeVariableJoin4() { await TestInMethodAsync( @" var q = from i1 in new int[0] join int i2 in new double[0] on i1 $$equals i2 select i1; ", MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.Join<int, int, int, int>(IEnumerable<int> inner, Func<int, int> outerKeySelector, Func<int, int> innerKeySelector, Func<int, int, int> resultSelector)")); } [WorkItem(543205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543205")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestErrorGlobal() { await TestAsync( @"extern alias global; class myClass { static int Main() { $$global::otherClass oc = new global::otherClass(); return 0; } }", MainDescription("<global namespace>")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task DontRemoveAttributeSuffixAndProduceInvalidIdentifier1() { await TestAsync( @"using System; class classAttribute : Attribute { private classAttribute x$$; }", MainDescription($"({FeaturesResources.field}) classAttribute classAttribute.x")); } [WorkItem(544026, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544026")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task DontRemoveAttributeSuffix2() { await TestAsync( @"using System; class class1Attribute : Attribute { private class1Attribute x$$; }", MainDescription($"({FeaturesResources.field}) class1Attribute class1Attribute.x")); } [WorkItem(1696, "https://github.com/dotnet/roslyn/issues/1696")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task AttributeQuickInfoBindsToClassTest() { await TestAsync( @"using System; /// <summary> /// class comment /// </summary> [Some$$] class SomeAttribute : Attribute { /// <summary> /// ctor comment /// </summary> public SomeAttribute() { } }", Documentation("class comment")); } [WorkItem(1696, "https://github.com/dotnet/roslyn/issues/1696")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task AttributeConstructorQuickInfo() { await TestAsync( @"using System; /// <summary> /// class comment /// </summary> class SomeAttribute : Attribute { /// <summary> /// ctor comment /// </summary> public SomeAttribute() { var s = new Some$$Attribute(); } }", Documentation("ctor comment")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestLabel() { await TestInClassAsync( @"void M() { Goo: int Goo; goto Goo$$; }", MainDescription($"({FeaturesResources.label}) Goo")); } [WorkItem(542613, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542613")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestUnboundGeneric() { await TestAsync( @"using System; using System.Collections.Generic; class C { void M() { Type t = typeof(L$$ist<>); } }", MainDescription("class System.Collections.Generic.List<T>"), NoTypeParameterMap); } [WorkItem(543113, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543113")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestAnonymousTypeNew1() { await TestAsync( @"class C { void M() { var v = $$new { }; } }", MainDescription(@"AnonymousType 'a"), NoTypeParameterMap, AnonymousTypes( $@" {FeaturesResources.Anonymous_Types_colon} 'a {FeaturesResources.is_} new {{ }}")); } [WorkItem(543873, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543873")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestNestedAnonymousType() { // verify nested anonymous types are listed in the same order for different properties // verify first property await TestInMethodAsync( @"var x = new[] { new { Name = ""BillG"", Address = new { Street = ""1 Microsoft Way"", Zip = ""98052"" } } }; x[0].$$Address", MainDescription(@"'b 'a.Address { get; }"), NoTypeParameterMap, AnonymousTypes( $@" {FeaturesResources.Anonymous_Types_colon} 'a {FeaturesResources.is_} new {{ string Name, 'b Address }} 'b {FeaturesResources.is_} new {{ string Street, string Zip }}")); // verify second property await TestInMethodAsync( @"var x = new[] { new { Name = ""BillG"", Address = new { Street = ""1 Microsoft Way"", Zip = ""98052"" } } }; x[0].$$Name", MainDescription(@"string 'a.Name { get; }"), NoTypeParameterMap, AnonymousTypes( $@" {FeaturesResources.Anonymous_Types_colon} 'a {FeaturesResources.is_} new {{ string Name, 'b Address }} 'b {FeaturesResources.is_} new {{ string Street, string Zip }}")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(543183, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543183")] public async Task TestAssignmentOperatorInAnonymousType() { await TestAsync( @"class C { void M() { var a = new { A $$= 0 }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(10731, "DevDiv_Projects/Roslyn")] public async Task TestErrorAnonymousTypeDoesntShow() { await TestInMethodAsync( @"var a = new { new { N = 0 }.N, new { } }.$$N;", MainDescription(@"int 'a.N { get; }"), NoTypeParameterMap, AnonymousTypes( $@" {FeaturesResources.Anonymous_Types_colon} 'a {FeaturesResources.is_} new {{ int N }}")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(543553, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543553")] public async Task TestArrayAssignedToVar() { await TestAsync( @"class C { static void M(string[] args) { v$$ar a = args; } }", MainDescription("string[]")); } [WorkItem(529139, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529139")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ColorColorRangeVariable() { await TestAsync( @"using System.Collections.Generic; using System.Linq; namespace N1 { class yield { public static IEnumerable<yield> Bar() { foreach (yield yield in from yield in new yield[0] select y$$ield) { yield return yield; } } } }", MainDescription($"({FeaturesResources.range_variable}) N1.yield yield")); } [WorkItem(543550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543550")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task QuickInfoOnOperator() { await TestAsync( @"using System.Collections.Generic; class Program { static void Main(string[] args) { var v = new Program() $$+ string.Empty; } public static implicit operator Program(string s) { return null; } public static IEnumerable<Program> operator +(Program p1, Program p2) { yield return p1; yield return p2; } }", MainDescription("IEnumerable<Program> Program.operator +(Program p1, Program p2)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestConstantField() { await TestAsync( @"class C { const int $$F = 1;", MainDescription($"({FeaturesResources.constant}) int C.F = 1")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestMultipleConstantFields() { await TestAsync( @"class C { public const double X = 1.0, Y = 2.0, $$Z = 3.5;", MainDescription($"({FeaturesResources.constant}) double C.Z = 3.5")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestConstantDependencies() { await TestAsync( @"class A { public const int $$X = B.Z + 1; public const int Y = 10; } class B { public const int Z = A.Y + 1; }", MainDescription($"({FeaturesResources.constant}) int A.X = B.Z + 1")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestConstantCircularDependencies() { await TestAsync( @"class A { public const int X = B.Z + 1; } class B { public const int Z$$ = A.X + 1; }", MainDescription($"({FeaturesResources.constant}) int B.Z = A.X + 1")); } [WorkItem(544620, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544620")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestConstantOverflow() { await TestAsync( @"class B { public const int Z$$ = int.MaxValue + 1; }", MainDescription($"({FeaturesResources.constant}) int B.Z = int.MaxValue + 1")); } [WorkItem(544620, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544620")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestConstantOverflowInUncheckedContext() { await TestAsync( @"class B { public const int Z$$ = unchecked(int.MaxValue + 1); }", MainDescription($"({FeaturesResources.constant}) int B.Z = unchecked(int.MaxValue + 1)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestEnumInConstantField() { await TestAsync( @"public class EnumTest { enum Days { Sun, Mon, Tue, Wed, Thu, Fri, Sat }; static void Main() { const int $$x = (int)Days.Sun; } }", MainDescription($"({FeaturesResources.local_constant}) int x = (int)Days.Sun")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestConstantInDefaultExpression() { await TestAsync( @"public class EnumTest { enum Days { Sun, Mon, Tue, Wed, Thu, Fri, Sat }; static void Main() { const Days $$x = default(Days); } }", MainDescription($"({FeaturesResources.local_constant}) Days x = default(Days)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestConstantParameter() { await TestAsync( @"class C { void Bar(int $$b = 1); }", MainDescription($"({FeaturesResources.parameter}) int b = 1")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestConstantLocal() { await TestAsync( @"class C { void Bar() { const int $$loc = 1; }", MainDescription($"({FeaturesResources.local_constant}) int loc = 1")); } [WorkItem(544416, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544416")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestErrorType1() { await TestInMethodAsync( @"var $$v1 = new Goo();", MainDescription($"({FeaturesResources.local_variable}) Goo v1")); } [WorkItem(544416, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544416")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestErrorType2() { await TestInMethodAsync( @"var $$v1 = v1;", MainDescription($"({FeaturesResources.local_variable}) var v1")); } [WorkItem(544416, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544416")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestErrorType3() { await TestInMethodAsync( @"var $$v1 = new Goo<Bar>();", MainDescription($"({FeaturesResources.local_variable}) Goo<Bar> v1")); } [WorkItem(544416, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544416")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestErrorType4() { await TestInMethodAsync( @"var $$v1 = &(x => x);", MainDescription($"({FeaturesResources.local_variable}) ?* v1")); } [WorkItem(544416, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544416")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestErrorType5() { await TestInMethodAsync("var $$v1 = &v1", MainDescription($"({FeaturesResources.local_variable}) var* v1")); } [WorkItem(544416, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544416")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestErrorType6() { await TestInMethodAsync("var $$v1 = new Goo[1]", MainDescription($"({FeaturesResources.local_variable}) Goo[] v1")); } [WorkItem(544416, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544416")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestErrorType7() { await TestInClassAsync( @"class C { void Method() { } void Goo() { var $$v1 = MethodGroup; } }", MainDescription($"({FeaturesResources.local_variable}) ? v1")); } [WorkItem(544416, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544416")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestErrorType8() { await TestInMethodAsync("var $$v1 = Unknown", MainDescription($"({FeaturesResources.local_variable}) ? v1")); } [WorkItem(545072, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545072")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestDelegateSpecialTypes() { await TestAsync( @"delegate void $$F(int x);", MainDescription("delegate void F(int x)")); } [WorkItem(545108, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545108")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestNullPointerParameter() { await TestAsync( @"class C { unsafe void $$Goo(int* x = null) { } }", MainDescription("void C.Goo([int* x = null])")); } [WorkItem(545098, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545098")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestLetIdentifier1() { await TestInMethodAsync("var q = from e in \"\" let $$y = 1 let a = new { y } select a;", MainDescription($"({FeaturesResources.range_variable}) int y")); } [WorkItem(545295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545295")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestNullableDefaultValue() { await TestAsync( @"class Test { void $$Method(int? t1 = null) { } }", MainDescription("void Test.Method([int? t1 = null])")); } [WorkItem(529586, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529586")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestInvalidParameterInitializer() { await TestAsync( @"class Program { void M1(float $$j1 = ""Hello"" + ""World"") { } }", MainDescription($@"({FeaturesResources.parameter}) float j1 = ""Hello"" + ""World""")); } [WorkItem(545230, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545230")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestComplexConstLocal() { await TestAsync( @"class Program { void Main() { const int MEGABYTE = 1024 * 1024 + true; Blah($$MEGABYTE); } }", MainDescription($@"({FeaturesResources.local_constant}) int MEGABYTE = 1024 * 1024 + true")); } [WorkItem(545230, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545230")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestComplexConstField() { await TestAsync( @"class Program { const int a = true - false; void Main() { Goo($$a); } }", MainDescription($"({FeaturesResources.constant}) int Program.a = true - false")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestTypeParameterCrefDoesNotHaveQuickInfo() { await TestAsync( @"class C<T> { /// <see cref=""C{X$$}""/> static void Main(string[] args) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestCref1() { await TestAsync( @"class Program { /// <see cref=""Mai$$n""/> static void Main(string[] args) { } }", MainDescription(@"void Program.Main(string[] args)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestCref2() { await TestAsync( @"class Program { /// <see cref=""$$Main""/> static void Main(string[] args) { } }", MainDescription(@"void Program.Main(string[] args)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestCref3() { await TestAsync( @"class Program { /// <see cref=""Main""$$/> static void Main(string[] args) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestCref4() { await TestAsync( @"class Program { /// <see cref=""Main$$""/> static void Main(string[] args) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestCref5() { await TestAsync( @"class Program { /// <see cref=""Main""$$/> static void Main(string[] args) { } }"); } [WorkItem(546849, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546849")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestIndexedProperty() { var markup = @"class Program { void M() { CCC c = new CCC(); c.Index$$Prop[0] = ""s""; } }"; // Note that <COMImport> is required by compiler. Bug 17013 tracks enabling indexed property for non-COM types. var referencedCode = @"Imports System.Runtime.InteropServices <ComImport()> <GuidAttribute(CCC.ClassId)> Public Class CCC #Region ""COM GUIDs"" Public Const ClassId As String = ""9d965fd2-1514-44f6-accd-257ce77c46b0"" Public Const InterfaceId As String = ""a9415060-fdf0-47e3-bc80-9c18f7f39cf6"" Public Const EventsId As String = ""c6a866a5-5f97-4b53-a5df-3739dc8ff1bb"" # End Region ''' <summary> ''' An index property from VB ''' </summary> ''' <param name=""p1"">p1 is an integer index</param> ''' <returns>A string</returns> Public Property IndexProp(ByVal p1 As Integer, Optional ByVal p2 As Integer = 0) As String Get Return Nothing End Get Set(ByVal value As String) End Set End Property End Class"; await TestWithReferenceAsync(sourceCode: markup, referencedCode: referencedCode, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.VisualBasic, expectedResults: MainDescription("string CCC.IndexProp[int p1, [int p2 = 0]] { get; set; }")); } [WorkItem(546918, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546918")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestUnconstructedGeneric() { await TestAsync( @"class A<T> { enum SortOrder { Ascending, Descending, None } void Goo() { var b = $$SortOrder.Ascending; } }", MainDescription(@"enum A<T>.SortOrder")); } [WorkItem(546970, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546970")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestUnconstructedGenericInCRef() { await TestAsync( @"/// <see cref=""$$C{T}"" /> class C<T> { }", MainDescription(@"class C<T>")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestAwaitableMethod() { var markup = @"using System.Threading.Tasks; class C { async Task Goo() { Go$$o(); } }"; var description = $"({CSharpFeaturesResources.awaitable}) Task C.Goo()"; await VerifyWithMscorlib45Async(markup, new[] { MainDescription(description) }); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ObsoleteItem() { var markup = @" using System; class Program { [Obsolete] public void goo() { go$$o(); } }"; await TestAsync(markup, MainDescription($"[{CSharpFeaturesResources.deprecated}] void Program.goo()")); } [WorkItem(751070, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/751070")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task DynamicOperator() { var markup = @" public class Test { public delegate void NoParam(); static int Main() { dynamic x = new object(); if (((System.Func<dynamic>)(() => (x =$$= null)))()) return 0; return 1; } }"; await TestAsync(markup, MainDescription("dynamic dynamic.operator ==(dynamic left, dynamic right)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TextOnlyDocComment() { await TestAsync( @"/// <summary> ///goo /// </summary> class C$$ { }", Documentation("goo")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestTrimConcatMultiLine() { await TestAsync( @"/// <summary> /// goo /// bar /// </summary> class C$$ { }", Documentation("goo bar")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestCref() { await TestAsync( @"/// <summary> /// <see cref=""C""/> /// <seealso cref=""C""/> /// </summary> class C$$ { }", Documentation("C C")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ExcludeTextOutsideSummaryBlock() { await TestAsync( @"/// red /// <summary> /// green /// </summary> /// yellow class C$$ { }", Documentation("green")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NewlineAfterPara() { await TestAsync( @"/// <summary> /// <para>goo</para> /// </summary> class C$$ { }", Documentation("goo")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TextOnlyDocComment_Metadata() { var referenced = @" /// <summary> ///goo /// </summary> public class C { }"; var code = @" class G { void goo() { C$$ c; } }"; await TestWithMetadataReferenceHelperAsync(code, referenced, "C#", "C#", Documentation("goo")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestTrimConcatMultiLine_Metadata() { var referenced = @" /// <summary> /// goo /// bar /// </summary> public class C { }"; var code = @" class G { void goo() { C$$ c; } }"; await TestWithMetadataReferenceHelperAsync(code, referenced, "C#", "C#", Documentation("goo bar")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestCref_Metadata() { var code = @" class G { void goo() { C$$ c; } }"; var referenced = @"/// <summary> /// <see cref=""C""/> /// <seealso cref=""C""/> /// </summary> public class C { }"; await TestWithMetadataReferenceHelperAsync(code, referenced, "C#", "C#", Documentation("C C")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ExcludeTextOutsideSummaryBlock_Metadata() { var code = @" class G { void goo() { C$$ c; } }"; var referenced = @" /// red /// <summary> /// green /// </summary> /// yellow public class C { }"; await TestWithMetadataReferenceHelperAsync(code, referenced, "C#", "C#", Documentation("green")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Param() { await TestAsync( @"/// <summary></summary> public class C { /// <typeparam name=""T"">A type parameter of <see cref=""goo{ T} (string[], T)""/></typeparam> /// <param name=""args"">First parameter of <see cref=""Goo{T} (string[], T)""/></param> /// <param name=""otherParam"">Another parameter of <see cref=""Goo{T}(string[], T)""/></param> public void Goo<T>(string[] arg$$s, T otherParam) { } }", Documentation("First parameter of C.Goo<T>(string[], T)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Param_Metadata() { var code = @" class G { void goo() { C c; c.Goo<int>(arg$$s: new string[] { }, 1); } }"; var referenced = @" /// <summary></summary> public class C { /// <typeparam name=""T"">A type parameter of <see cref=""goo{ T} (string[], T)""/></typeparam> /// <param name=""args"">First parameter of <see cref=""Goo{T} (string[], T)""/></param> /// <param name=""otherParam"">Another parameter of <see cref=""Goo{T}(string[], T)""/></param> public void Goo<T>(string[] args, T otherParam) { } }"; await TestWithMetadataReferenceHelperAsync(code, referenced, "C#", "C#", Documentation("First parameter of C.Goo<T>(string[], T)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Param2() { await TestAsync( @"/// <summary></summary> public class C { /// <typeparam name=""T"">A type parameter of <see cref=""goo{ T} (string[], T)""/></typeparam> /// <param name=""args"">First parameter of <see cref=""Goo{T} (string[], T)""/></param> /// <param name=""otherParam"">Another parameter of <see cref=""Goo{T}(string[], T)""/></param> public void Goo<T>(string[] args, T oth$$erParam) { } }", Documentation("Another parameter of C.Goo<T>(string[], T)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task Param2_Metadata() { var code = @" class G { void goo() { C c; c.Goo<int>(args: new string[] { }, other$$Param: 1); } }"; var referenced = @" /// <summary></summary> public class C { /// <typeparam name=""T"">A type parameter of <see cref=""goo{ T} (string[], T)""/></typeparam> /// <param name=""args"">First parameter of <see cref=""Goo{T} (string[], T)""/></param> /// <param name=""otherParam"">Another parameter of <see cref=""Goo{T}(string[], T)""/></param> public void Goo<T>(string[] args, T otherParam) { } }"; await TestWithMetadataReferenceHelperAsync(code, referenced, "C#", "C#", Documentation("Another parameter of C.Goo<T>(string[], T)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TypeParam() { await TestAsync( @"/// <summary></summary> public class C { /// <typeparam name=""T"">A type parameter of <see cref=""Goo{T} (string[], T)""/></typeparam> /// <param name=""args"">First parameter of <see cref=""Goo{T} (string[], T)""/></param> /// <param name=""otherParam"">Another parameter of <see cref=""Goo{T}(string[], T)""/></param> public void Goo<T$$>(string[] args, T otherParam) { } }", Documentation("A type parameter of C.Goo<T>(string[], T)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task UnboundCref() { await TestAsync( @"/// <summary></summary> public class C { /// <typeparam name=""T"">A type parameter of <see cref=""goo{T}(string[], T)""/></typeparam> /// <param name=""args"">First parameter of <see cref=""Goo{T} (string[], T)""/></param> /// <param name=""otherParam"">Another parameter of <see cref=""Goo{T}(string[], T)""/></param> public void Goo<T$$>(string[] args, T otherParam) { } }", Documentation("A type parameter of goo<T>(string[], T)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task CrefInConstructor() { await TestAsync( @"public class TestClass { /// <summary> /// This sample shows how to specify the <see cref=""TestClass""/> constructor as a cref attribute. /// </summary> public TestClass$$() { } }", Documentation("This sample shows how to specify the TestClass constructor as a cref attribute.")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task CrefInConstructorOverloaded() { await TestAsync( @"public class TestClass { /// <summary> /// This sample shows how to specify the <see cref=""TestClass""/> constructor as a cref attribute. /// </summary> public TestClass() { } /// <summary> /// This sample shows how to specify the <see cref=""TestClass(int)""/> constructor as a cref attribute. /// </summary> public TestC$$lass(int value) { } }", Documentation("This sample shows how to specify the TestClass(int) constructor as a cref attribute.")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task CrefInGenericMethod1() { await TestAsync( @"public class TestClass { /// <summary> /// The GetGenericValue method. /// <para>This sample shows how to specify the <see cref=""GetGenericValue""/> method as a cref attribute.</para> /// </summary> public static T GetGenericVa$$lue<T>(T para) { return para; } }", Documentation("The GetGenericValue method.\r\n\r\nThis sample shows how to specify the TestClass.GetGenericValue<T>(T) method as a cref attribute.")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task CrefInGenericMethod2() { await TestAsync( @"public class TestClass { /// <summary> /// The GetGenericValue method. /// <para>This sample shows how to specify the <see cref=""GetGenericValue{T}(T)""/> method as a cref attribute.</para> /// </summary> public static T GetGenericVa$$lue<T>(T para) { return para; } }", Documentation("The GetGenericValue method.\r\n\r\nThis sample shows how to specify the TestClass.GetGenericValue<T>(T) method as a cref attribute.")); } [WorkItem(813350, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/813350")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task CrefInMethodOverloading1() { await TestAsync( @"public class TestClass { public static int GetZero() { GetGenericValu$$e(); GetGenericValue(5); } /// <summary> /// This sample shows how to call the <see cref=""GetGenericValue{T}(T)""/> method /// </summary> public static T GetGenericValue<T>(T para) { return para; } /// <summary> /// This sample shows how to specify the <see cref=""GetGenericValue""/> method as a cref attribute. /// </summary> public static void GetGenericValue() { } }", Documentation("This sample shows how to specify the TestClass.GetGenericValue() method as a cref attribute.")); } [WorkItem(813350, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/813350")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task CrefInMethodOverloading2() { await TestAsync( @"public class TestClass { public static int GetZero() { GetGenericValue(); GetGenericVal$$ue(5); } /// <summary> /// This sample shows how to call the <see cref=""GetGenericValue{T}(T)""/> method /// </summary> public static T GetGenericValue<T>(T para) { return para; } /// <summary> /// This sample shows how to specify the <see cref=""GetGenericValue""/> method as a cref attribute. /// </summary> public static void GetGenericValue() { } }", Documentation("This sample shows how to call the TestClass.GetGenericValue<T>(T) method")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task CrefInGenericType() { await TestAsync( @"/// <summary> /// <remarks>This example shows how to specify the <see cref=""GenericClass{T}""/> cref.</remarks> /// </summary> class Generic$$Class<T> { }", Documentation("This example shows how to specify the GenericClass<T> cref.", ExpectedClassifications( Text("This example shows how to specify the"), WhiteSpace(" "), Class("GenericClass"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, WhiteSpace(" "), Text("cref.")))); } [WorkItem(812720, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/812720")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ClassificationOfCrefsFromMetadata() { var code = @" class G { void goo() { C c; c.Go$$o(); } }"; var referenced = @" /// <summary></summary> public class C { /// <summary> /// See <see cref=""Goo""/> method /// </summary> public void Goo() { } }"; await TestWithMetadataReferenceHelperAsync(code, referenced, "C#", "C#", Documentation("See C.Goo() method", ExpectedClassifications( Text("See"), WhiteSpace(" "), Class("C"), Punctuation.Text("."), Identifier("Goo"), Punctuation.OpenParen, Punctuation.CloseParen, WhiteSpace(" "), Text("method")))); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task FieldAvailableInBothLinkedFiles() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1""> <Document FilePath=""SourceDocument""><![CDATA[ class C { int x; void goo() { x$$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; await VerifyWithReferenceWorkerAsync(markup, new[] { MainDescription($"({FeaturesResources.field}) int C.x"), Usage("") }); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task FieldUnavailableInOneLinkedFile() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""GOO""> <Document FilePath=""SourceDocument""><![CDATA[ class C { #if GOO int x; #endif void goo() { x$$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; var expectedDescription = Usage($"\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}", expectsWarningGlyph: true); await VerifyWithReferenceWorkerAsync(markup, new[] { expectedDescription }); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(37097, "https://github.com/dotnet/roslyn/issues/37097")] public async Task BindSymbolInOtherFile() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1""> <Document FilePath=""SourceDocument""><![CDATA[ class C { #if GOO int x; #endif void goo() { x$$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""GOO""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; var expectedDescription = Usage($"\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Not_Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}", expectsWarningGlyph: true); await VerifyWithReferenceWorkerAsync(markup, new[] { expectedDescription }); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task FieldUnavailableInTwoLinkedFiles() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""GOO""> <Document FilePath=""SourceDocument""><![CDATA[ class C { #if GOO int x; #endif void goo() { x$$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj3""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; var expectedDescription = Usage( $"\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Not_Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj3", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}", expectsWarningGlyph: true); await VerifyWithReferenceWorkerAsync(markup, new[] { expectedDescription }); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ExcludeFilesWithInactiveRegions() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""GOO,BAR""> <Document FilePath=""SourceDocument""><![CDATA[ class C { #if GOO int x; #endif #if BAR void goo() { x$$ } #endif } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument"" /> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj3"" PreprocessorSymbols=""BAR""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; var expectedDescription = Usage($"\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj3", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}", expectsWarningGlyph: true); await VerifyWithReferenceWorkerAsync(markup, new[] { expectedDescription }); } [WorkItem(962353, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/962353")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NoValidSymbolsInLinkedDocuments() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1""> <Document FilePath=""SourceDocument""><![CDATA[ class C { void goo() { B$$ar(); } #if B void Bar() { } #endif } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; await VerifyWithReferenceWorkerAsync(markup); } [WorkItem(1020944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1020944")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task LocalsValidInLinkedDocuments() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1""> <Document FilePath=""SourceDocument""><![CDATA[ class C { void M() { int x$$; } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; await VerifyWithReferenceWorkerAsync(markup, new[] { MainDescription($"({FeaturesResources.local_variable}) int x"), Usage("") }); } [WorkItem(1020944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1020944")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task LocalWarningInLinkedDocuments() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""PROJ1""> <Document FilePath=""SourceDocument""><![CDATA[ class C { void M() { #if PROJ1 int x; #endif int y = x$$; } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; await VerifyWithReferenceWorkerAsync(markup, new[] { MainDescription($"({FeaturesResources.local_variable}) int x"), Usage($"\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}", expectsWarningGlyph: true) }); } [WorkItem(1020944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1020944")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task LabelsValidInLinkedDocuments() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1""> <Document FilePath=""SourceDocument""><![CDATA[ class C { void M() { $$LABEL: goto LABEL; } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; await VerifyWithReferenceWorkerAsync(markup, new[] { MainDescription($"({FeaturesResources.label}) LABEL"), Usage("") }); } [WorkItem(1020944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1020944")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task RangeVariablesValidInLinkedDocuments() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1""> <Document FilePath=""SourceDocument""><![CDATA[ using System.Linq; class C { void M() { var x = from y in new[] {1, 2, 3} select $$y; } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; await VerifyWithReferenceWorkerAsync(markup, new[] { MainDescription($"({FeaturesResources.range_variable}) int y"), Usage("") }); } [WorkItem(1019766, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1019766")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task PointerAccessibility() { var markup = @"class C { unsafe static void Main() { void* p = null; void* q = null; dynamic d = true; var x = p =$$= q == d; } }"; await TestAsync(markup, MainDescription("bool void*.operator ==(void* left, void* right)")); } [WorkItem(1114300, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1114300")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task AwaitingTaskOfArrayType() { var markup = @" using System.Threading.Tasks; class Program { async Task<int[]> M() { awa$$it M(); } }"; await TestAsync(markup, MainDescription(string.Format(FeaturesResources.Awaited_task_returns_0, "int[]"))); } [WorkItem(1114300, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1114300")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task AwaitingTaskOfDynamic() { var markup = @" using System.Threading.Tasks; class Program { async Task<dynamic> M() { awa$$it M(); } }"; await TestAsync(markup, MainDescription(string.Format(FeaturesResources.Awaited_task_returns_0, "dynamic"))); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MethodOverloadDifferencesIgnored() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""ONE""> <Document FilePath=""SourceDocument""><![CDATA[ class C { #if ONE void Do(int x){} #endif #if TWO void Do(string x){} #endif void Shared() { this.Do$$ } }]]></Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""TWO""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; var expectedDescription = $"void C.Do(int x)"; await VerifyWithReferenceWorkerAsync(markup, MainDescription(expectedDescription)); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MethodOverloadDifferencesIgnored_ContainingType() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""ONE""> <Document FilePath=""SourceDocument""><![CDATA[ class C { void Shared() { var x = GetThing().Do$$(); } #if ONE private Methods1 GetThing() { return new Methods1(); } #endif #if TWO private Methods2 GetThing() { return new Methods2(); } #endif } #if ONE public class Methods1 { public void Do(string x) { } } #endif #if TWO public class Methods2 { public void Do(string x) { } } #endif ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""TWO""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; var expectedDescription = $"void Methods1.Do(string x)"; await VerifyWithReferenceWorkerAsync(markup, MainDescription(expectedDescription)); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(4868, "https://github.com/dotnet/roslyn/issues/4868")] public async Task QuickInfoExceptions() { await TestAsync( @"using System; namespace MyNs { class MyException1 : Exception { } class MyException2 : Exception { } class TestClass { /// <exception cref=""MyException1""></exception> /// <exception cref=""T:MyNs.MyException2""></exception> /// <exception cref=""System.Int32""></exception> /// <exception cref=""double""></exception> /// <exception cref=""Not_A_Class_But_Still_Displayed""></exception> void M() { M$$(); } } }", Exceptions($"\r\n{WorkspacesResources.Exceptions_colon}\r\n MyException1\r\n MyException2\r\n int\r\n double\r\n Not_A_Class_But_Still_Displayed")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23307, "https://github.com/dotnet/roslyn/issues/23307")] public async Task QuickInfoCapturesOnLocalFunction() { await TestAsync(@" class C { void M() { int i; local$$(); void local() { i++; this.M(); } } }", Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this, i")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23307, "https://github.com/dotnet/roslyn/issues/23307")] public async Task QuickInfoCapturesOnLocalFunction2() { await TestAsync(@" class C { void M() { int i; local$$(i); void local(int j) { j++; M(); } } }", Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23307, "https://github.com/dotnet/roslyn/issues/23307")] public async Task QuickInfoCapturesOnLocalFunction3() { await TestAsync(@" class C { public void M(int @this) { int i = 0; local$$(); void local() { M(1); i++; @this++; } } }", Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this, @this, i")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(26101, "https://github.com/dotnet/roslyn/issues/26101")] public async Task QuickInfoCapturesOnLocalFunction4() { await TestAsync(@" class C { int field; void M() { void OuterLocalFunction$$() { int local = 0; int InnerLocalFunction() { field++; return local; } } } }", Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(26101, "https://github.com/dotnet/roslyn/issues/26101")] public async Task QuickInfoCapturesOnLocalFunction5() { await TestAsync(@" class C { int field; void M() { void OuterLocalFunction() { int local = 0; int InnerLocalFunction$$() { field++; return local; } } } }", Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this, local")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(26101, "https://github.com/dotnet/roslyn/issues/26101")] public async Task QuickInfoCapturesOnLocalFunction6() { await TestAsync(@" class C { int field; void M() { int local1 = 0; int local2 = 0; void OuterLocalFunction$$() { _ = local1; void InnerLocalFunction() { _ = local2; } } } }", Captures($"\r\n{WorkspacesResources.Variables_captured_colon} local1, local2")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(26101, "https://github.com/dotnet/roslyn/issues/26101")] public async Task QuickInfoCapturesOnLocalFunction7() { await TestAsync(@" class C { int field; void M() { int local1 = 0; int local2 = 0; void OuterLocalFunction() { _ = local1; void InnerLocalFunction$$() { _ = local2; } } } }", Captures($"\r\n{WorkspacesResources.Variables_captured_colon} local2")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23307, "https://github.com/dotnet/roslyn/issues/23307")] public async Task QuickInfoCapturesOnLambda() { await TestAsync(@" class C { void M() { int i; System.Action a = () =$$> { i++; M(); }; } }", Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this, i")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23307, "https://github.com/dotnet/roslyn/issues/23307")] public async Task QuickInfoCapturesOnLambda2() { await TestAsync(@" class C { void M() { int i; System.Action<int> a = j =$$> { i++; j++; M(); }; } }", Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this, i")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23307, "https://github.com/dotnet/roslyn/issues/23307")] public async Task QuickInfoCapturesOnLambda2_DifferentOrder() { await TestAsync(@" class C { void M(int j) { int i; System.Action a = () =$$> { M(); i++; j++; }; } }", Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this, j, i")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23307, "https://github.com/dotnet/roslyn/issues/23307")] public async Task QuickInfoCapturesOnLambda3() { await TestAsync(@" class C { void M() { int i; int @this; N(() =$$> { M(); @this++; }, () => { i++; }); } void N(System.Action x, System.Action y) { } }", Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this, @this")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23307, "https://github.com/dotnet/roslyn/issues/23307")] public async Task QuickInfoCapturesOnLambda4() { await TestAsync(@" class C { void M() { int i; N(() => { M(); }, () =$$> { i++; }); } void N(System.Action x, System.Action y) { } }", Captures($"\r\n{WorkspacesResources.Variables_captured_colon} i")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(26101, "https://github.com/dotnet/roslyn/issues/26101")] public async Task QuickInfoCapturesOnLambda5() { await TestAsync(@" class C { int field; void M() { System.Action a = () =$$> { int local = 0; System.Func<int> b = () => { field++; return local; }; }; } }", Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(26101, "https://github.com/dotnet/roslyn/issues/26101")] public async Task QuickInfoCapturesOnLambda6() { await TestAsync(@" class C { int field; void M() { System.Action a = () => { int local = 0; System.Func<int> b = () =$$> { field++; return local; }; }; } }", Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this, local")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(26101, "https://github.com/dotnet/roslyn/issues/26101")] public async Task QuickInfoCapturesOnLambda7() { await TestAsync(@" class C { int field; void M() { int local1 = 0; int local2 = 0; System.Action a = () =$$> { _ = local1; System.Action b = () => { _ = local2; }; }; } }", Captures($"\r\n{WorkspacesResources.Variables_captured_colon} local1, local2")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(26101, "https://github.com/dotnet/roslyn/issues/26101")] public async Task QuickInfoCapturesOnLambda8() { await TestAsync(@" class C { int field; void M() { int local1 = 0; int local2 = 0; System.Action a = () => { _ = local1; System.Action b = () =$$> { _ = local2; }; }; } }", Captures($"\r\n{WorkspacesResources.Variables_captured_colon} local2")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(23307, "https://github.com/dotnet/roslyn/issues/23307")] public async Task QuickInfoCapturesOnDelegate() { await TestAsync(@" class C { void M() { int i; System.Func<bool, int> f = dele$$gate(bool b) { i++; return 1; }; } }", Captures($"\r\n{WorkspacesResources.Variables_captured_colon} i")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(1516, "https://github.com/dotnet/roslyn/issues/1516")] public async Task QuickInfoWithNonStandardSeeAttributesAppear() { await TestAsync( @"class C { /// <summary> /// <see cref=""System.String"" /> /// <see href=""http://microsoft.com"" /> /// <see langword=""null"" /> /// <see unsupported-attribute=""cat"" /> /// </summary> void M() { M$$(); } }", Documentation(@"string http://microsoft.com null cat")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(6657, "https://github.com/dotnet/roslyn/issues/6657")] public async Task OptionalParameterFromPreviousSubmission() { const string workspaceDefinition = @" <Workspace> <Submission Language=""C#"" CommonReferences=""true""> void M(int x = 1) { } </Submission> <Submission Language=""C#"" CommonReferences=""true""> M(x$$: 2) </Submission> </Workspace> "; using var workspace = TestWorkspace.Create(XElement.Parse(workspaceDefinition), workspaceKind: WorkspaceKind.Interactive); await TestWithOptionsAsync(workspace, MainDescription($"({ FeaturesResources.parameter }) int x = 1")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TupleProperty() { await TestInMethodAsync( @"interface I { (int, int) Name { get; set; } } class C : I { (int, int) I.Name$$ { get { throw new System.Exception(); } set { } } }", MainDescription("(int, int) C.Name { get; set; }")); } [WorkItem(18311, "https://github.com/dotnet/roslyn/issues/18311")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ValueTupleWithArity0VariableName() { await TestAsync( @" using System; public class C { void M() { var y$$ = ValueTuple.Create(); } } ", MainDescription($"({ FeaturesResources.local_variable }) ValueTuple y")); } [WorkItem(18311, "https://github.com/dotnet/roslyn/issues/18311")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ValueTupleWithArity0ImplicitVar() { await TestAsync( @" using System; public class C { void M() { var$$ y = ValueTuple.Create(); } } ", MainDescription("struct System.ValueTuple")); } [WorkItem(18311, "https://github.com/dotnet/roslyn/issues/18311")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ValueTupleWithArity1VariableName() { await TestAsync( @" using System; public class C { void M() { var y$$ = ValueTuple.Create(1); } } ", MainDescription($"({ FeaturesResources.local_variable }) ValueTuple<int> y")); } [WorkItem(18311, "https://github.com/dotnet/roslyn/issues/18311")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ValueTupleWithArity1ImplicitVar() { await TestAsync( @" using System; public class C { void M() { var$$ y = ValueTuple.Create(1); } } ", MainDescription("struct System.ValueTuple<System.Int32>")); } [WorkItem(18311, "https://github.com/dotnet/roslyn/issues/18311")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ValueTupleWithArity2VariableName() { await TestAsync( @" using System; public class C { void M() { var y$$ = ValueTuple.Create(1, 1); } } ", MainDescription($"({ FeaturesResources.local_variable }) (int, int) y")); } [WorkItem(18311, "https://github.com/dotnet/roslyn/issues/18311")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ValueTupleWithArity2ImplicitVar() { await TestAsync( @" using System; public class C { void M() { var$$ y = ValueTuple.Create(1, 1); } } ", MainDescription("(System.Int32, System.Int32)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestRefMethod() { await TestInMethodAsync( @"using System; class Program { static void Main(string[] args) { ref int i = ref $$goo(); } private static ref int goo() { throw new NotImplementedException(); } }", MainDescription("ref int Program.goo()")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestRefLocal() { await TestInMethodAsync( @"using System; class Program { static void Main(string[] args) { ref int $$i = ref goo(); } private static ref int goo() { throw new NotImplementedException(); } }", MainDescription($"({FeaturesResources.local_variable}) ref int i")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(410932, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?id=410932")] public async Task TestGenericMethodInDocComment() { await TestAsync( @" class Test { T F<T>() { F<T>(); } /// <summary> /// <see cref=""F$${T}()""/> /// </summary> void S() { } } ", MainDescription("T Test.F<T>()")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(403665, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=403665&_a=edit")] public async Task TestExceptionWithCrefToConstructorDoesNotCrash() { await TestAsync( @" class Test { /// <summary> /// </summary> /// <exception cref=""Test.Test""/> public Test$$() {} } ", MainDescription("Test.Test()")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestRefStruct() { var markup = "ref struct X$$ {}"; await TestAsync(markup, MainDescription("ref struct X")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestRefStruct_Nested() { var markup = @" namespace Nested { ref struct X$$ {} }"; await TestAsync(markup, MainDescription("ref struct Nested.X")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestReadOnlyStruct() { var markup = "readonly struct X$$ {}"; await TestAsync(markup, MainDescription("readonly struct X")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestReadOnlyStruct_Nested() { var markup = @" namespace Nested { readonly struct X$$ {} }"; await TestAsync(markup, MainDescription("readonly struct Nested.X")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestReadOnlyRefStruct() { var markup = "readonly ref struct X$$ {}"; await TestAsync(markup, MainDescription("readonly ref struct X")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestReadOnlyRefStruct_Nested() { var markup = @" namespace Nested { readonly ref struct X$$ {} }"; await TestAsync(markup, MainDescription("readonly ref struct Nested.X")); } [WorkItem(22450, "https://github.com/dotnet/roslyn/issues/22450")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestRefLikeTypesNoDeprecated() { var xmlString = @" <Workspace> <Project Language=""C#"" LanguageVersion=""7.2"" CommonReferences=""true""> <MetadataReferenceFromSource Language=""C#"" LanguageVersion=""7.2"" CommonReferences=""true""> <Document FilePath=""ReferencedDocument""> public ref struct TestRef { } </Document> </MetadataReferenceFromSource> <Document FilePath=""SourceDocument""> ref struct Test { private $$TestRef _field; } </Document> </Project> </Workspace>"; // There should be no [deprecated] attribute displayed. await VerifyWithReferenceWorkerAsync(xmlString, MainDescription($"ref struct TestRef")); } [WorkItem(2644, "https://github.com/dotnet/roslyn/issues/2644")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task PropertyWithSameNameAsOtherType() { await TestAsync( @"namespace ConsoleApplication1 { class Program { static A B { get; set; } static B A { get; set; } static void Main(string[] args) { B = ConsoleApplication1.B$$.F(); } } class A { } class B { public static A F() => null; } }", MainDescription($"ConsoleApplication1.A ConsoleApplication1.B.F()")); } [WorkItem(2644, "https://github.com/dotnet/roslyn/issues/2644")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task PropertyWithSameNameAsOtherType2() { await TestAsync( @"using System.Collections.Generic; namespace ConsoleApplication1 { class Program { public static List<Bar> Bar { get; set; } static void Main(string[] args) { Tes$$t<Bar>(); } static void Test<T>() { } } class Bar { } }", MainDescription($"void Program.Test<Bar>()")); } [WorkItem(23883, "https://github.com/dotnet/roslyn/issues/23883")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task InMalformedEmbeddedStatement_01() { await TestAsync( @" class Program { void method1() { if (method2()) .Any(b => b.Content$$Type, out var chars) { } } } "); } [WorkItem(23883, "https://github.com/dotnet/roslyn/issues/23883")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task InMalformedEmbeddedStatement_02() { await TestAsync( @" class Program { void method1() { if (method2()) .Any(b => b$$.ContentType, out var chars) { } } } ", MainDescription($"({ FeaturesResources.parameter }) ? b")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task EnumConstraint() { await TestInMethodAsync( @" class X<T> where T : System.Enum { private $$T x; }", MainDescription($"T {FeaturesResources.in_} X<T> where T : Enum")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task DelegateConstraint() { await TestInMethodAsync( @" class X<T> where T : System.Delegate { private $$T x; }", MainDescription($"T {FeaturesResources.in_} X<T> where T : Delegate")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task MulticastDelegateConstraint() { await TestInMethodAsync( @" class X<T> where T : System.MulticastDelegate { private $$T x; }", MainDescription($"T {FeaturesResources.in_} X<T> where T : MulticastDelegate")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task UnmanagedConstraint_Type() { await TestAsync( @" class $$X<T> where T : unmanaged { }", MainDescription("class X<T> where T : unmanaged")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task UnmanagedConstraint_Method() { await TestAsync( @" class X { void $$M<T>() where T : unmanaged { } }", MainDescription("void X.M<T>() where T : unmanaged")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task UnmanagedConstraint_Delegate() { await TestAsync( "delegate void $$D<T>() where T : unmanaged;", MainDescription("delegate void D<T>() where T : unmanaged")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task UnmanagedConstraint_LocalFunction() { await TestAsync( @" class X { void N() { void $$M<T>() where T : unmanaged { } } }", MainDescription("void M<T>() where T : unmanaged")); } [WorkItem(29703, "https://github.com/dotnet/roslyn/issues/29703")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestGetAccessorDocumentation() { await TestAsync( @" class X { /// <summary>Summary for property Goo</summary> int Goo { g$$et; set; } }", Documentation("Summary for property Goo")); } [WorkItem(29703, "https://github.com/dotnet/roslyn/issues/29703")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestSetAccessorDocumentation() { await TestAsync( @" class X { /// <summary>Summary for property Goo</summary> int Goo { get; s$$et; } }", Documentation("Summary for property Goo")); } [WorkItem(29703, "https://github.com/dotnet/roslyn/issues/29703")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestEventAddDocumentation1() { await TestAsync( @" using System; class X { /// <summary>Summary for event Goo</summary> event EventHandler<EventArgs> Goo { a$$dd => throw null; remove => throw null; } }", Documentation("Summary for event Goo")); } [WorkItem(29703, "https://github.com/dotnet/roslyn/issues/29703")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestEventAddDocumentation2() { await TestAsync( @" using System; class X { /// <summary>Summary for event Goo</summary> event EventHandler<EventArgs> Goo; void M() => Goo +$$= null; }", Documentation("Summary for event Goo")); } [WorkItem(29703, "https://github.com/dotnet/roslyn/issues/29703")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestEventRemoveDocumentation1() { await TestAsync( @" using System; class X { /// <summary>Summary for event Goo</summary> event EventHandler<EventArgs> Goo { add => throw null; r$$emove => throw null; } }", Documentation("Summary for event Goo")); } [WorkItem(29703, "https://github.com/dotnet/roslyn/issues/29703")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestEventRemoveDocumentation2() { await TestAsync( @" using System; class X { /// <summary>Summary for event Goo</summary> event EventHandler<EventArgs> Goo; void M() => Goo -$$= null; }", Documentation("Summary for event Goo")); } [WorkItem(30642, "https://github.com/dotnet/roslyn/issues/30642")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task BuiltInOperatorWithUserDefinedEquivalent() { await TestAsync( @" class X { void N(string a, string b) { var v = a $$== b; } }", MainDescription("bool string.operator ==(string a, string b)"), SymbolGlyph(Glyph.Operator)); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NotNullConstraint_Type() { await TestAsync( @" class $$X<T> where T : notnull { }", MainDescription("class X<T> where T : notnull")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NotNullConstraint_Method() { await TestAsync( @" class X { void $$M<T>() where T : notnull { } }", MainDescription("void X.M<T>() where T : notnull")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NotNullConstraint_Delegate() { await TestAsync( "delegate void $$D<T>() where T : notnull;", MainDescription("delegate void D<T>() where T : notnull")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NotNullConstraint_LocalFunction() { await TestAsync( @" class X { void N() { void $$M<T>() where T : notnull { } } }", MainDescription("void M<T>() where T : notnull")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NullableParameterThatIsMaybeNull() { await TestWithOptionsAsync(TestOptions.Regular8, @"#nullable enable class X { void N(string? s) { string s2 = $$s; } }", MainDescription($"({FeaturesResources.parameter}) string? s"), NullabilityAnalysis(string.Format(FeaturesResources._0_may_be_null_here, "s"))); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NullableParameterThatIsNotNull() { await TestWithOptionsAsync(TestOptions.Regular8, @"#nullable enable class X { void N(string? s) { s = """"; string s2 = $$s; } }", MainDescription($"({FeaturesResources.parameter}) string? s"), NullabilityAnalysis(string.Format(FeaturesResources._0_is_not_null_here, "s"))); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NullableFieldThatIsMaybeNull() { await TestWithOptionsAsync(TestOptions.Regular8, @"#nullable enable class X { string? s = null; void N() { string s2 = $$s; } }", MainDescription($"({FeaturesResources.field}) string? X.s"), NullabilityAnalysis(string.Format(FeaturesResources._0_may_be_null_here, "s"))); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NullableFieldThatIsNotNull() { await TestWithOptionsAsync(TestOptions.Regular8, @"#nullable enable class X { string? s = null; void N() { s = """"; string s2 = $$s; } }", MainDescription($"({FeaturesResources.field}) string? X.s"), NullabilityAnalysis(string.Format(FeaturesResources._0_is_not_null_here, "s"))); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NullablePropertyThatIsMaybeNull() { await TestWithOptionsAsync(TestOptions.Regular8, @"#nullable enable class X { string? S { get; set; } void N() { string s2 = $$S; } }", MainDescription("string? X.S { get; set; }"), NullabilityAnalysis(string.Format(FeaturesResources._0_may_be_null_here, "S"))); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NullablePropertyThatIsNotNull() { await TestWithOptionsAsync(TestOptions.Regular8, @"#nullable enable class X { string? S { get; set; } void N() { S = """"; string s2 = $$S; } }", MainDescription("string? X.S { get; set; }"), NullabilityAnalysis(string.Format(FeaturesResources._0_is_not_null_here, "S"))); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NullableRangeVariableThatIsMaybeNull() { await TestWithOptionsAsync(TestOptions.Regular8, @"#nullable enable using System.Collections.Generic; class X { void N() { IEnumerable<string?> enumerable; foreach (var s in enumerable) { string s2 = $$s; } } }", MainDescription($"({FeaturesResources.local_variable}) string? s"), NullabilityAnalysis(string.Format(FeaturesResources._0_may_be_null_here, "s"))); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NullableRangeVariableThatIsNotNull() { await TestWithOptionsAsync(TestOptions.Regular8, @"#nullable enable using System.Collections.Generic; class X { void N() { IEnumerable<string> enumerable; foreach (var s in enumerable) { string s2 = $$s; } } }", MainDescription($"({FeaturesResources.local_variable}) string? s"), NullabilityAnalysis(string.Format(FeaturesResources._0_is_not_null_here, "s"))); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NullableLocalThatIsMaybeNull() { await TestWithOptionsAsync(TestOptions.Regular8, @"#nullable enable using System.Collections.Generic; class X { void N() { string? s = null; string s2 = $$s; } }", MainDescription($"({FeaturesResources.local_variable}) string? s"), NullabilityAnalysis(string.Format(FeaturesResources._0_may_be_null_here, "s"))); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NullableLocalThatIsNotNull() { await TestWithOptionsAsync(TestOptions.Regular8, @"#nullable enable using System.Collections.Generic; class X { void N() { string? s = """"; string s2 = $$s; } }", MainDescription($"({FeaturesResources.local_variable}) string? s"), NullabilityAnalysis(string.Format(FeaturesResources._0_is_not_null_here, "s"))); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NullableNotShownPriorToLanguageVersion8() { await TestWithOptionsAsync(TestOptions.Regular7_3, @"#nullable enable using System.Collections.Generic; class X { void N() { string s = """"; string s2 = $$s; } }", MainDescription($"({FeaturesResources.local_variable}) string s"), NullabilityAnalysis("")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NullableNotShownInNullableDisable() { await TestWithOptionsAsync(TestOptions.Regular8, @"#nullable disable using System.Collections.Generic; class X { void N() { string s = """"; string s2 = $$s; } }", MainDescription($"({FeaturesResources.local_variable}) string s"), NullabilityAnalysis("")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NullableShownWhenEnabledGlobally() { await TestWithOptionsAsync(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, nullableContextOptions: NullableContextOptions.Enable), @"using System.Collections.Generic; class X { void N() { string s = """"; string s2 = $$s; } }", MainDescription($"({FeaturesResources.local_variable}) string s"), NullabilityAnalysis(string.Format(FeaturesResources._0_is_not_null_here, "s"))); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NullableNotShownForValueType() { await TestWithOptionsAsync(TestOptions.Regular8, @"#nullable enable using System.Collections.Generic; class X { void N() { int a = 0; int b = $$a; } }", MainDescription($"({FeaturesResources.local_variable}) int a"), NullabilityAnalysis("")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task NullableNotShownForConst() { await TestWithOptionsAsync(TestOptions.Regular8, @"#nullable enable using System.Collections.Generic; class X { void N() { const string? s = null; string? s2 = $$s; } }", MainDescription($"({FeaturesResources.local_constant}) string? s = null"), NullabilityAnalysis("")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestInheritdocInlineSummary() { var markup = @" /// <summary>Summary documentation</summary> /// <remarks>Remarks documentation</remarks> void M(int x) { } /// <summary><inheritdoc cref=""M(int)""/></summary> void $$M(int x, int y) { }"; await TestInClassAsync(markup, MainDescription("void C.M(int x, int y)"), Documentation("Summary documentation")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestInheritdocTwoLevels1() { var markup = @" /// <summary>Summary documentation</summary> /// <remarks>Remarks documentation</remarks> void M() { } /// <inheritdoc cref=""M()""/> void M(int x) { } /// <inheritdoc cref=""M(int)""/> void $$M(int x, int y) { }"; await TestInClassAsync(markup, MainDescription("void C.M(int x, int y)"), Documentation("Summary documentation")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestInheritdocTwoLevels2() { var markup = @" /// <summary>Summary documentation</summary> /// <remarks>Remarks documentation</remarks> void M() { } /// <summary><inheritdoc cref=""M()""/></summary> void M(int x) { } /// <summary><inheritdoc cref=""M(int)""/></summary> void $$M(int x, int y) { }"; await TestInClassAsync(markup, MainDescription("void C.M(int x, int y)"), Documentation("Summary documentation")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestInheritdocWithTypeParamRef() { var markup = @" public class Program { public static void Main() => _ = new Test<int>().$$Clone(); } public class Test<T> : ICloneable<Test<T>> { /// <inheritdoc/> public Test<T> Clone() => new(); } /// <summary>A type that has clonable instances.</summary> /// <typeparam name=""T"">The type of instances that can be cloned.</typeparam> public interface ICloneable<T> { /// <summary>Clones a <typeparamref name=""T""/>.</summary> /// <returns>A clone of the <typeparamref name=""T""/>.</returns> public T Clone(); }"; await TestInClassAsync(markup, MainDescription("Test<int> Test<int>.Clone()"), Documentation("Clones a Test<T>.")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestInheritdocCycle1() { var markup = @" /// <inheritdoc cref=""M(int, int)""/> void M(int x) { } /// <inheritdoc cref=""M(int)""/> void $$M(int x, int y) { }"; await TestInClassAsync(markup, MainDescription("void C.M(int x, int y)"), Documentation("")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestInheritdocCycle2() { var markup = @" /// <inheritdoc cref=""M(int)""/> void $$M(int x) { }"; await TestInClassAsync(markup, MainDescription("void C.M(int x)"), Documentation("")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestInheritdocCycle3() { var markup = @" /// <inheritdoc cref=""M""/> void $$M(int x) { }"; await TestInClassAsync(markup, MainDescription("void C.M(int x)"), Documentation("")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(38794, "https://github.com/dotnet/roslyn/issues/38794")] public async Task TestLinqGroupVariableDeclaration() { var code = @" void M(string[] a) { var v = from x in a group x by x.Length into $$g select g; }"; await TestInClassAsync(code, MainDescription($"({FeaturesResources.range_variable}) IGrouping<int, string> g")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(38283, "https://github.com/dotnet/roslyn/issues/38283")] public async Task QuickInfoOnIndexerCloseBracket() { await TestAsync(@" class C { public int this[int x] { get { return 1; } } void M() { var x = new C()[5$$]; } }", MainDescription("int C.this[int x] { get; }")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(38283, "https://github.com/dotnet/roslyn/issues/38283")] public async Task QuickInfoOnIndexerOpenBracket() { await TestAsync(@" class C { public int this[int x] { get { return 1; } } void M() { var x = new C()$$[5]; } }", MainDescription("int C.this[int x] { get; }")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(38283, "https://github.com/dotnet/roslyn/issues/38283")] public async Task QuickInfoOnIndexer_NotOnArrayAccess() { await TestAsync(@" class Program { void M() { int[] x = new int[4]; int y = x[3$$]; } }", MainDescription("struct System.Int32")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(31618, "https://github.com/dotnet/roslyn/issues/31618")] public async Task QuickInfoWithRemarksOnMethod() { await TestAsync(@" class Program { /// <summary> /// Summary text /// </summary> /// <remarks> /// Remarks text /// </remarks> int M() { return $$M(); } }", MainDescription("int Program.M()"), Documentation("Summary text"), Remarks("\r\nRemarks text")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(31618, "https://github.com/dotnet/roslyn/issues/31618")] public async Task QuickInfoWithRemarksOnPropertyAccessor() { await TestAsync(@" class Program { /// <summary> /// Summary text /// </summary> /// <remarks> /// Remarks text /// </remarks> int M { $$get; } }", MainDescription("int Program.M.get"), Documentation("Summary text"), Remarks("\r\nRemarks text")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(31618, "https://github.com/dotnet/roslyn/issues/31618")] public async Task QuickInfoWithReturnsOnMethod() { await TestAsync(@" class Program { /// <summary> /// Summary text /// </summary> /// <returns> /// Returns text /// </returns> int M() { return $$M(); } }", MainDescription("int Program.M()"), Documentation("Summary text"), Returns($"\r\n{FeaturesResources.Returns_colon}\r\n Returns text")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(31618, "https://github.com/dotnet/roslyn/issues/31618")] public async Task QuickInfoWithReturnsOnPropertyAccessor() { await TestAsync(@" class Program { /// <summary> /// Summary text /// </summary> /// <returns> /// Returns text /// </returns> int M { $$get; } }", MainDescription("int Program.M.get"), Documentation("Summary text"), Returns($"\r\n{FeaturesResources.Returns_colon}\r\n Returns text")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(31618, "https://github.com/dotnet/roslyn/issues/31618")] public async Task QuickInfoWithValueOnMethod() { await TestAsync(@" class Program { /// <summary> /// Summary text /// </summary> /// <value> /// Value text /// </value> int M() { return $$M(); } }", MainDescription("int Program.M()"), Documentation("Summary text"), Value($"\r\n{FeaturesResources.Value_colon}\r\n Value text")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(31618, "https://github.com/dotnet/roslyn/issues/31618")] public async Task QuickInfoWithValueOnPropertyAccessor() { await TestAsync(@" class Program { /// <summary> /// Summary text /// </summary> /// <value> /// Value text /// </value> int M { $$get; } }", MainDescription("int Program.M.get"), Documentation("Summary text"), Value($"\r\n{FeaturesResources.Value_colon}\r\n Value text")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")] public async Task QuickInfoNotPattern1() { await TestAsync(@" class Person { void Goo(object o) { if (o is not $$Person p) { } } }", MainDescription("class Person")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")] public async Task QuickInfoNotPattern2() { await TestAsync(@" class Person { void Goo(object o) { if (o is $$not Person p) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")] public async Task QuickInfoOrPattern1() { await TestAsync(@" class Person { void Goo(object o) { if (o is $$Person or int) { } } }", MainDescription("class Person")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")] public async Task QuickInfoOrPattern2() { await TestAsync(@" class Person { void Goo(object o) { if (o is Person or $$int) { } } }", MainDescription("struct System.Int32")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")] public async Task QuickInfoOrPattern3() { await TestAsync(@" class Person { void Goo(object o) { if (o is Person $$or int) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task QuickInfoRecord() { await TestWithOptionsAsync( Options.Regular.WithLanguageVersion(LanguageVersion.CSharp9), @"record Person(string First, string Last) { void M($$Person p) { } }", MainDescription("record Person")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task QuickInfoDerivedRecord() { await TestWithOptionsAsync( Options.Regular.WithLanguageVersion(LanguageVersion.CSharp9), @"record Person(string First, string Last) { } record Student(string Id) { void M($$Student p) { } } ", MainDescription("record Student")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(44904, "https://github.com/dotnet/roslyn/issues/44904")] public async Task QuickInfoRecord_BaseTypeList() { await TestAsync(@" record Person(string First, string Last); record Student(int Id) : $$Person(null, null); ", MainDescription("Person.Person(string First, string Last)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task QuickInfo_BaseConstructorInitializer() { await TestAsync(@" public class Person { public Person(int id) { } } public class Student : Person { public Student() : $$base(0) { } } ", MainDescription("Person.Person(int id)")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task QuickInfoRecordClass() { await TestWithOptionsAsync( Options.Regular.WithLanguageVersion(LanguageVersion.CSharp9), @"record class Person(string First, string Last) { void M($$Person p) { } }", MainDescription("record Person")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task QuickInfoRecordStruct() { await TestWithOptionsAsync( Options.Regular.WithLanguageVersion(LanguageVersion.CSharp9), @"record struct Person(string First, string Last) { void M($$Person p) { } }", MainDescription("record struct Person")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task QuickInfoReadOnlyRecordStruct() { await TestWithOptionsAsync( Options.Regular.WithLanguageVersion(LanguageVersion.CSharp9), @"readonly record struct Person(string First, string Last) { void M($$Person p) { } }", MainDescription("readonly record struct Person")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] [WorkItem(51615, "https://github.com/dotnet/roslyn/issues/51615")] public async Task TestVarPatternOnVarKeyword() { await TestAsync( @"class C { string M() { } void M2() { if (M() is va$$r x && x.Length > 0) { } } }", MainDescription("class System.String")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestVarPatternOnVariableItself() { await TestAsync( @"class C { string M() { } void M2() { if (M() is var x$$ && x.Length > 0) { } } }", MainDescription($"({FeaturesResources.local_variable}) string? x")); } [WorkItem(53135, "https://github.com/dotnet/roslyn/issues/53135")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestDocumentationCData() { var markup = @"using I$$ = IGoo; /// <summary> /// summary for interface IGoo /// <code><![CDATA[ /// List<string> y = null; /// ]]></code> /// </summary> interface IGoo { }"; await TestAsync(markup, MainDescription("interface IGoo"), Documentation(@"summary for interface IGoo List<string> y = null;")); } [WorkItem(37503, "https://github.com/dotnet/roslyn/issues/37503")] [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task DoNotNormalizeWhitespaceForCode() { var markup = @"using I$$ = IGoo; /// <summary> /// Normalize this, and <c>Also this</c> /// <code> /// line 1 /// line 2 /// </code> /// </summary> interface IGoo { }"; await TestAsync(markup, MainDescription("interface IGoo"), Documentation(@"Normalize this, and Also this line 1 line 2")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestStaticAbstract_ImplicitImplementation() { var code = @" interface I1 { /// <summary>Summary text</summary> static abstract void M1(); } class C1_1 : I1 { public static void $$M1() { } } "; await TestAsync( code, MainDescription("void C1_1.M1()"), Documentation("Summary text")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestStaticAbstract_ImplicitImplementation_FromReference() { var code = @" interface I1 { /// <summary>Summary text</summary> static abstract void M1(); } class C1_1 : I1 { public static void M1() { } } class R { public static void M() { C1_1.$$M1(); } } "; await TestAsync( code, MainDescription("void C1_1.M1()"), Documentation("Summary text")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestStaticAbstract_FromTypeParameterReference() { var code = @" interface I1 { /// <summary>Summary text</summary> static abstract void M1(); } class R { public static void M<T>() where T : I1 { T.$$M1(); } } "; await TestAsync( code, MainDescription("void I1.M1()"), Documentation("Summary text")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestStaticAbstract_ExplicitInheritdoc_ImplicitImplementation() { var code = @" interface I1 { /// <summary>Summary text</summary> static abstract void M1(); } class C1_1 : I1 { /// <inheritdoc/> public static void $$M1() { } } "; await TestAsync( code, MainDescription("void C1_1.M1()"), Documentation("Summary text")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestStaticAbstract_ExplicitImplementation() { var code = @" interface I1 { /// <summary>Summary text</summary> static abstract void M1(); } class C1_1 : I1 { static void I1.$$M1() { } } "; await TestAsync( code, MainDescription("void C1_1.M1()"), Documentation("Summary text")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestStaticAbstract_ExplicitInheritdoc_ExplicitImplementation() { var code = @" interface I1 { /// <summary>Summary text</summary> static abstract void M1(); } class C1_1 : I1 { /// <inheritdoc/> static void I1.$$M1() { } } "; await TestAsync( code, MainDescription("void C1_1.M1()"), Documentation("Summary text")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task QuickInfoLambdaReturnType_01() { await TestWithOptionsAsync( Options.Regular.WithLanguageVersion(LanguageVersion.CSharp9), @"class Program { System.Delegate D = bo$$ol () => true; }", MainDescription("struct System.Boolean")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task QuickInfoLambdaReturnType_02() { await TestWithOptionsAsync( Options.Regular.WithLanguageVersion(LanguageVersion.CSharp9), @"class A { struct B { } System.Delegate D = A.B$$ () => null; }", MainDescription("struct A.B")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task QuickInfoLambdaReturnType_03() { await TestWithOptionsAsync( Options.Regular.WithLanguageVersion(LanguageVersion.CSharp9), @"class A<T> { } struct B { System.Delegate D = A<B$$> () => null; }", MainDescription("struct B")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestNormalFuncSynthesizedLambdaType() { await TestAsync( @"class C { void M() { $$var v = (int i) => i.ToString(); } }", MainDescription("delegate TResult System.Func<in T, out TResult>(T arg)"), TypeParameterMap($@" T {FeaturesResources.is_} int TResult {FeaturesResources.is_} string")); } [Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task TestAnonymousSynthesizedLambdaType() { await TestAsync( @"class C { void M() { $$var v = (ref int i) => i.ToString(); } }", MainDescription("delegate string <anonymous delegate>(ref int)")); } } }
1
dotnet/roslyn
56,419
Fix partial method doc comments
Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
RikkiGibson
"2021-09-15T20:47:39Z"
"2021-09-21T23:49:10Z"
0f60b3e9446f5d0fc14a570998c81a5d6c40cc23
8cda7462843d43d9b72039eede2f4cb43126cac2
Fix partial method doc comments. Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
./src/Features/LanguageServer/ProtocolUnitTests/Definitions/GoToTypeDefinitionTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using System.Threading; using System.Threading.Tasks; using Roslyn.Test.Utilities; using Xunit; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.Definitions { public class GoToTypeDefinitionTests : AbstractLanguageServerProtocolTests { [Fact] public async Task TestGotoTypeDefinitionAsync() { var markup = @"class {|definition:A|} { } class B { {|caret:|}A classA; }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var results = await RunGotoTypeDefinitionAsync(testLspServer, locations["caret"].Single()); AssertLocationsEqual(locations["definition"], results); } [Fact] public async Task TestGotoTypeDefinitionAsync_DifferentDocument() { var markups = new string[] { @"namespace One { class {|definition:A|} { } }", @"namespace One { class B { {|caret:|}A classA; } }" }; using var testLspServer = CreateTestLspServer(markups, out var locations); var results = await RunGotoTypeDefinitionAsync(testLspServer, locations["caret"].Single()); AssertLocationsEqual(locations["definition"], results); } [Fact] public async Task TestGotoTypeDefinitionAsync_InvalidLocation() { var markup = @"class {|definition:A|} { } class B { A classA; {|caret:|} }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var results = await RunGotoTypeDefinitionAsync(testLspServer, locations["caret"].Single()); Assert.Empty(results); } private static async Task<LSP.Location[]> RunGotoTypeDefinitionAsync(TestLspServer testLspServer, LSP.Location caret) { return await testLspServer.ExecuteRequestAsync<LSP.TextDocumentPositionParams, LSP.Location[]>(LSP.Methods.TextDocumentTypeDefinitionName, CreateTextDocumentPositionParams(caret), new LSP.ClientCapabilities(), null, CancellationToken.None); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using System.Threading; using System.Threading.Tasks; using Roslyn.Test.Utilities; using Xunit; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.Definitions { public class GoToTypeDefinitionTests : AbstractLanguageServerProtocolTests { [Fact] public async Task TestGotoTypeDefinitionAsync() { var markup = @"class {|definition:A|} { } class B { {|caret:|}A classA; }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var results = await RunGotoTypeDefinitionAsync(testLspServer, locations["caret"].Single()); AssertLocationsEqual(locations["definition"], results); } [Fact] public async Task TestGotoTypeDefinitionAsync_DifferentDocument() { var markups = new string[] { @"namespace One { class {|definition:A|} { } }", @"namespace One { class B { {|caret:|}A classA; } }" }; using var testLspServer = CreateTestLspServer(markups, out var locations); var results = await RunGotoTypeDefinitionAsync(testLspServer, locations["caret"].Single()); AssertLocationsEqual(locations["definition"], results); } [Fact] public async Task TestGotoTypeDefinitionAsync_InvalidLocation() { var markup = @"class {|definition:A|} { } class B { A classA; {|caret:|} }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var results = await RunGotoTypeDefinitionAsync(testLspServer, locations["caret"].Single()); Assert.Empty(results); } private static async Task<LSP.Location[]> RunGotoTypeDefinitionAsync(TestLspServer testLspServer, LSP.Location caret) { return await testLspServer.ExecuteRequestAsync<LSP.TextDocumentPositionParams, LSP.Location[]>(LSP.Methods.TextDocumentTypeDefinitionName, CreateTextDocumentPositionParams(caret), new LSP.ClientCapabilities(), null, CancellationToken.None); } } }
-1
dotnet/roslyn
56,419
Fix partial method doc comments
Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
RikkiGibson
"2021-09-15T20:47:39Z"
"2021-09-21T23:49:10Z"
0f60b3e9446f5d0fc14a570998c81a5d6c40cc23
8cda7462843d43d9b72039eede2f4cb43126cac2
Fix partial method doc comments. Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
./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,419
Fix partial method doc comments
Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
RikkiGibson
"2021-09-15T20:47:39Z"
"2021-09-21T23:49:10Z"
0f60b3e9446f5d0fc14a570998c81a5d6c40cc23
8cda7462843d43d9b72039eede2f4cb43126cac2
Fix partial method doc comments. Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
./src/EditorFeatures/CSharp/BraceMatching/CSharpDirectiveTriviaBraceMatcher.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.ComponentModel.Composition; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Editor.CSharp.BraceMatching { [ExportBraceMatcher(LanguageNames.CSharp)] internal class CSharpDirectiveTriviaBraceMatcher : AbstractDirectiveTriviaBraceMatcher<DirectiveTriviaSyntax, IfDirectiveTriviaSyntax, ElifDirectiveTriviaSyntax, ElseDirectiveTriviaSyntax, EndIfDirectiveTriviaSyntax, RegionDirectiveTriviaSyntax, EndRegionDirectiveTriviaSyntax> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpDirectiveTriviaBraceMatcher() { } internal override List<DirectiveTriviaSyntax> GetMatchingConditionalDirectives(DirectiveTriviaSyntax directive, CancellationToken cancellationToken) => directive.GetMatchingConditionalDirectives(cancellationToken)?.ToList(); internal override DirectiveTriviaSyntax GetMatchingDirective(DirectiveTriviaSyntax directive, CancellationToken cancellationToken) => directive.GetMatchingDirective(cancellationToken); internal override TextSpan GetSpanForTagging(DirectiveTriviaSyntax directive) => TextSpan.FromBounds(directive.HashToken.SpanStart, directive.DirectiveNameToken.Span.End); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Editor.CSharp.BraceMatching { [ExportBraceMatcher(LanguageNames.CSharp)] internal class CSharpDirectiveTriviaBraceMatcher : AbstractDirectiveTriviaBraceMatcher<DirectiveTriviaSyntax, IfDirectiveTriviaSyntax, ElifDirectiveTriviaSyntax, ElseDirectiveTriviaSyntax, EndIfDirectiveTriviaSyntax, RegionDirectiveTriviaSyntax, EndRegionDirectiveTriviaSyntax> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpDirectiveTriviaBraceMatcher() { } internal override List<DirectiveTriviaSyntax> GetMatchingConditionalDirectives(DirectiveTriviaSyntax directive, CancellationToken cancellationToken) => directive.GetMatchingConditionalDirectives(cancellationToken)?.ToList(); internal override DirectiveTriviaSyntax GetMatchingDirective(DirectiveTriviaSyntax directive, CancellationToken cancellationToken) => directive.GetMatchingDirective(cancellationToken); internal override TextSpan GetSpanForTagging(DirectiveTriviaSyntax directive) => TextSpan.FromBounds(directive.HashToken.SpanStart, directive.DirectiveNameToken.Span.End); } }
-1
dotnet/roslyn
56,419
Fix partial method doc comments
Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
RikkiGibson
"2021-09-15T20:47:39Z"
"2021-09-21T23:49:10Z"
0f60b3e9446f5d0fc14a570998c81a5d6c40cc23
8cda7462843d43d9b72039eede2f4cb43126cac2
Fix partial method doc comments. Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
./src/EditorFeatures/CSharp/DecompiledSource/CSharpDecompiledSourceFormattingRule.cs
// Licensed to the .NET Foundation under one or more agreements. // 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; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Formatting.Rules; namespace Microsoft.CodeAnalysis.Editor.CSharp.DecompiledSource { internal class CSharpDecompiledSourceFormattingRule : AbstractFormattingRule { public static readonly AbstractFormattingRule Instance = new CSharpDecompiledSourceFormattingRule(); private CSharpDecompiledSourceFormattingRule() { } public override AdjustNewLinesOperation? GetAdjustNewLinesOperation( in SyntaxToken previousToken, in SyntaxToken currentToken, in NextGetAdjustNewLinesOperation nextOperation) { var operation = GetAdjustNewLinesOperation(previousToken, currentToken); return operation ?? nextOperation.Invoke(in previousToken, in currentToken); } private static AdjustNewLinesOperation? GetAdjustNewLinesOperation(SyntaxToken previousToken, SyntaxToken currentToken) { // To help code not look too tightly packed, we place a blank line after every statement that ends with a // `}` (unless it's also followed by another `}`). if (previousToken.Kind() != SyntaxKind.CloseBraceToken) return null; if (currentToken.Kind() == SyntaxKind.CloseBraceToken) return null; if (previousToken.Parent == null || currentToken.Parent == null) return null; var previousStatement = previousToken.Parent.FirstAncestorOrSelf<StatementSyntax>(); var nextStatement = currentToken.Parent.FirstAncestorOrSelf<StatementSyntax>(); if (previousStatement == null || nextStatement == null || previousStatement == nextStatement) return null; // Ensure that we're only updating the whitespace between statements. if (previousStatement.GetLastToken() != previousToken || nextStatement.GetFirstToken() != currentToken) return null; // Ensure a blank line between these two. return FormattingOperations.CreateAdjustNewLinesOperation(2, AdjustNewLinesOption.ForceLines); } } }
// Licensed to the .NET Foundation under one or more agreements. // 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; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Formatting.Rules; namespace Microsoft.CodeAnalysis.Editor.CSharp.DecompiledSource { internal class CSharpDecompiledSourceFormattingRule : AbstractFormattingRule { public static readonly AbstractFormattingRule Instance = new CSharpDecompiledSourceFormattingRule(); private CSharpDecompiledSourceFormattingRule() { } public override AdjustNewLinesOperation? GetAdjustNewLinesOperation( in SyntaxToken previousToken, in SyntaxToken currentToken, in NextGetAdjustNewLinesOperation nextOperation) { var operation = GetAdjustNewLinesOperation(previousToken, currentToken); return operation ?? nextOperation.Invoke(in previousToken, in currentToken); } private static AdjustNewLinesOperation? GetAdjustNewLinesOperation(SyntaxToken previousToken, SyntaxToken currentToken) { // To help code not look too tightly packed, we place a blank line after every statement that ends with a // `}` (unless it's also followed by another `}`). if (previousToken.Kind() != SyntaxKind.CloseBraceToken) return null; if (currentToken.Kind() == SyntaxKind.CloseBraceToken) return null; if (previousToken.Parent == null || currentToken.Parent == null) return null; var previousStatement = previousToken.Parent.FirstAncestorOrSelf<StatementSyntax>(); var nextStatement = currentToken.Parent.FirstAncestorOrSelf<StatementSyntax>(); if (previousStatement == null || nextStatement == null || previousStatement == nextStatement) return null; // Ensure that we're only updating the whitespace between statements. if (previousStatement.GetLastToken() != previousToken || nextStatement.GetFirstToken() != currentToken) return null; // Ensure a blank line between these two. return FormattingOperations.CreateAdjustNewLinesOperation(2, AdjustNewLinesOption.ForceLines); } } }
-1
dotnet/roslyn
56,419
Fix partial method doc comments
Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
RikkiGibson
"2021-09-15T20:47:39Z"
"2021-09-21T23:49:10Z"
0f60b3e9446f5d0fc14a570998c81a5d6c40cc23
8cda7462843d43d9b72039eede2f4cb43126cac2
Fix partial method doc comments. Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/NamingStyles/NamingStyle.WordSpanEnumerable.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.NamingStyles { internal partial struct NamingStyle { private struct WordSpanEnumerable { private readonly string _name; private readonly TextSpan _nameSpan; private readonly string _wordSeparator; public WordSpanEnumerable(string name, TextSpan nameSpan, string wordSeparator) { _name = name; _nameSpan = nameSpan; _wordSeparator = wordSeparator; } public WordSpanEnumerator GetEnumerator() => new(_name, _nameSpan, _wordSeparator); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.NamingStyles { internal partial struct NamingStyle { private struct WordSpanEnumerable { private readonly string _name; private readonly TextSpan _nameSpan; private readonly string _wordSeparator; public WordSpanEnumerable(string name, TextSpan nameSpan, string wordSeparator) { _name = name; _nameSpan = nameSpan; _wordSeparator = wordSeparator; } public WordSpanEnumerator GetEnumerator() => new(_name, _nameSpan, _wordSeparator); } } }
-1
dotnet/roslyn
56,419
Fix partial method doc comments
Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
RikkiGibson
"2021-09-15T20:47:39Z"
"2021-09-21T23:49:10Z"
0f60b3e9446f5d0fc14a570998c81a5d6c40cc23
8cda7462843d43d9b72039eede2f4cb43126cac2
Fix partial method doc comments. Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
./src/VisualStudio/Core/Def/Implementation/ProjectSystem/IEntryPointFinderService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Host; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem { internal interface IEntryPointFinderService : ILanguageService { /// <summary> /// Finds the types that contain entry points like the Main method in a give namespace. /// </summary> /// <param name="symbol">The namespace to search.</param> /// <param name="findFormsOnly">Restrict the search to only Windows Forms classes. Note that this is only implemented for VisualBasic</param> IEnumerable<INamedTypeSymbol> FindEntryPoints(INamespaceSymbol symbol, bool findFormsOnly); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Host; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem { internal interface IEntryPointFinderService : ILanguageService { /// <summary> /// Finds the types that contain entry points like the Main method in a give namespace. /// </summary> /// <param name="symbol">The namespace to search.</param> /// <param name="findFormsOnly">Restrict the search to only Windows Forms classes. Note that this is only implemented for VisualBasic</param> IEnumerable<INamedTypeSymbol> FindEntryPoints(INamespaceSymbol symbol, bool findFormsOnly); } }
-1
dotnet/roslyn
56,419
Fix partial method doc comments
Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
RikkiGibson
"2021-09-15T20:47:39Z"
"2021-09-21T23:49:10Z"
0f60b3e9446f5d0fc14a570998c81a5d6c40cc23
8cda7462843d43d9b72039eede2f4cb43126cac2
Fix partial method doc comments. Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
./src/VisualStudio/Core/Impl/CodeModel/InternalElements/CodeFunction.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Linq; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements { [ComVisible(true)] [ComDefaultInterface(typeof(EnvDTE80.CodeFunction2))] public partial class CodeFunction : AbstractCodeMember, ICodeElementContainer<CodeParameter>, ICodeElementContainer<CodeAttribute>, EnvDTE.CodeFunction, EnvDTE80.CodeFunction2, IMethodXML, IMethodXML2 { internal static EnvDTE.CodeFunction Create( CodeModelState state, FileCodeModel fileCodeModel, SyntaxNodeKey nodeKey, int? nodeKind) { var element = new CodeFunction(state, fileCodeModel, nodeKey, nodeKind); var result = (EnvDTE.CodeFunction)ComAggregate.CreateAggregatedObject(element); fileCodeModel.OnCodeElementCreated(nodeKey, (EnvDTE.CodeElement)result); return result; } internal static EnvDTE.CodeFunction CreateUnknown( CodeModelState state, FileCodeModel fileCodeModel, int nodeKind, string name) { var element = new CodeFunction(state, fileCodeModel, nodeKind, name); return (EnvDTE.CodeFunction)ComAggregate.CreateAggregatedObject(element); } internal CodeFunction( CodeModelState state, FileCodeModel fileCodeModel, SyntaxNodeKey nodeKey, int? nodeKind) : base(state, fileCodeModel, nodeKey, nodeKind) { } internal CodeFunction( CodeModelState state, FileCodeModel fileCodeModel, int nodeKind, string name) : base(state, fileCodeModel, nodeKind, name) { } EnvDTE.CodeElements ICodeElementContainer<CodeParameter>.GetCollection() => this.Parameters; EnvDTE.CodeElements ICodeElementContainer<CodeAttribute>.GetCollection() => this.Attributes; private IMethodSymbol MethodSymbol { get { return (IMethodSymbol)LookupSymbol(); } } internal override ImmutableArray<SyntaxNode> GetParameters() => ImmutableArray.CreateRange(CodeModelService.GetParameterNodes(LookupNode())); protected override object GetExtenderNames() => CodeModelService.GetFunctionExtenderNames(); protected override object GetExtender(string name) => CodeModelService.GetFunctionExtender(name, LookupNode(), LookupSymbol()); public override EnvDTE.vsCMElement Kind { get { return EnvDTE.vsCMElement.vsCMElementFunction; } } public bool CanOverride { get { return CodeModelService.GetCanOverride(LookupNode()); } set { UpdateNode(FileCodeModel.UpdateCanOverride, value); } } public EnvDTE.vsCMFunction FunctionKind { get { if (LookupSymbol() is not IMethodSymbol symbol) { throw Exceptions.ThrowEUnexpected(); } return CodeModelService.GetFunctionKind(symbol); } } public bool IsOverloaded { get { var symbol = (IMethodSymbol)LookupSymbol(); // Only methods and constructors can be overloaded if (symbol.MethodKind is not MethodKind.Ordinary and not MethodKind.Constructor) { return false; } var methodsOfName = symbol.ContainingType.GetMembers(symbol.Name) .Where(m => m.Kind == SymbolKind.Method); return methodsOfName.Count() > 1; } } public EnvDTE.CodeElements Overloads { get { return OverloadsCollection.Create(this.FileCodeModel.State, this); } } public override EnvDTE.CodeElements Children { get { return UnionCollection.Create(this.State, this, (ICodeElements)this.Attributes, (ICodeElements)this.Parameters); } } public EnvDTE.CodeTypeRef Type { get { return CodeTypeRef.Create(this.State, this, GetProjectId(), MethodSymbol.ReturnType); } set { // The type is sometimes part of the node key, so we should be sure to reacquire // it after updating it. Note that we pass trackKinds: false because it's possible // that UpdateType might change the kind of a node (e.g. change a VB Sub to a Function). UpdateNodeAndReacquireNodeKey(FileCodeModel.UpdateType, value, trackKinds: false); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Linq; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements { [ComVisible(true)] [ComDefaultInterface(typeof(EnvDTE80.CodeFunction2))] public partial class CodeFunction : AbstractCodeMember, ICodeElementContainer<CodeParameter>, ICodeElementContainer<CodeAttribute>, EnvDTE.CodeFunction, EnvDTE80.CodeFunction2, IMethodXML, IMethodXML2 { internal static EnvDTE.CodeFunction Create( CodeModelState state, FileCodeModel fileCodeModel, SyntaxNodeKey nodeKey, int? nodeKind) { var element = new CodeFunction(state, fileCodeModel, nodeKey, nodeKind); var result = (EnvDTE.CodeFunction)ComAggregate.CreateAggregatedObject(element); fileCodeModel.OnCodeElementCreated(nodeKey, (EnvDTE.CodeElement)result); return result; } internal static EnvDTE.CodeFunction CreateUnknown( CodeModelState state, FileCodeModel fileCodeModel, int nodeKind, string name) { var element = new CodeFunction(state, fileCodeModel, nodeKind, name); return (EnvDTE.CodeFunction)ComAggregate.CreateAggregatedObject(element); } internal CodeFunction( CodeModelState state, FileCodeModel fileCodeModel, SyntaxNodeKey nodeKey, int? nodeKind) : base(state, fileCodeModel, nodeKey, nodeKind) { } internal CodeFunction( CodeModelState state, FileCodeModel fileCodeModel, int nodeKind, string name) : base(state, fileCodeModel, nodeKind, name) { } EnvDTE.CodeElements ICodeElementContainer<CodeParameter>.GetCollection() => this.Parameters; EnvDTE.CodeElements ICodeElementContainer<CodeAttribute>.GetCollection() => this.Attributes; private IMethodSymbol MethodSymbol { get { return (IMethodSymbol)LookupSymbol(); } } internal override ImmutableArray<SyntaxNode> GetParameters() => ImmutableArray.CreateRange(CodeModelService.GetParameterNodes(LookupNode())); protected override object GetExtenderNames() => CodeModelService.GetFunctionExtenderNames(); protected override object GetExtender(string name) => CodeModelService.GetFunctionExtender(name, LookupNode(), LookupSymbol()); public override EnvDTE.vsCMElement Kind { get { return EnvDTE.vsCMElement.vsCMElementFunction; } } public bool CanOverride { get { return CodeModelService.GetCanOverride(LookupNode()); } set { UpdateNode(FileCodeModel.UpdateCanOverride, value); } } public EnvDTE.vsCMFunction FunctionKind { get { if (LookupSymbol() is not IMethodSymbol symbol) { throw Exceptions.ThrowEUnexpected(); } return CodeModelService.GetFunctionKind(symbol); } } public bool IsOverloaded { get { var symbol = (IMethodSymbol)LookupSymbol(); // Only methods and constructors can be overloaded if (symbol.MethodKind is not MethodKind.Ordinary and not MethodKind.Constructor) { return false; } var methodsOfName = symbol.ContainingType.GetMembers(symbol.Name) .Where(m => m.Kind == SymbolKind.Method); return methodsOfName.Count() > 1; } } public EnvDTE.CodeElements Overloads { get { return OverloadsCollection.Create(this.FileCodeModel.State, this); } } public override EnvDTE.CodeElements Children { get { return UnionCollection.Create(this.State, this, (ICodeElements)this.Attributes, (ICodeElements)this.Parameters); } } public EnvDTE.CodeTypeRef Type { get { return CodeTypeRef.Create(this.State, this, GetProjectId(), MethodSymbol.ReturnType); } set { // The type is sometimes part of the node key, so we should be sure to reacquire // it after updating it. Note that we pass trackKinds: false because it's possible // that UpdateType might change the kind of a node (e.g. change a VB Sub to a Function). UpdateNodeAndReacquireNodeKey(FileCodeModel.UpdateType, value, trackKinds: false); } } } }
-1
dotnet/roslyn
56,419
Fix partial method doc comments
Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
RikkiGibson
"2021-09-15T20:47:39Z"
"2021-09-21T23:49:10Z"
0f60b3e9446f5d0fc14a570998c81a5d6c40cc23
8cda7462843d43d9b72039eede2f4cb43126cac2
Fix partial method doc comments. Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
./src/EditorFeatures/CSharpTest/Diagnostics/Configuration/ConfigureSeverity/CategoryBasedSeverityConfigurationTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CodeFixes.Configuration.ConfigureSeverity; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.Configuration.ConfigureSeverity { public abstract partial class CategoryBasedSeverityConfigurationTests : AbstractSuppressionDiagnosticTest { private sealed class CustomDiagnosticAnalyzer : DiagnosticAnalyzer { private static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor( id: "XYZ0001", title: "Title", messageFormat: "Message", category: "CustomCategory", defaultSeverity: DiagnosticSeverity.Info, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule); public override void Initialize(AnalysisContext context) { context.RegisterSyntaxNodeAction( c => c.ReportDiagnostic(Diagnostic.Create(Rule, c.Node.GetLocation())), SyntaxKind.ClassDeclaration); } } protected internal override string GetLanguage() => LanguageNames.CSharp; protected override ParseOptions GetScriptOptions() => Options.Script; internal override Tuple<DiagnosticAnalyzer, IConfigurationFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace) { return new Tuple<DiagnosticAnalyzer, IConfigurationFixProvider>( new CustomDiagnosticAnalyzer(), new ConfigureSeverityLevelCodeFixProvider()); } public sealed class SilentConfigurationTests : CategoryBasedSeverityConfigurationTests { /// <summary> /// Code action ranges: /// 1. (0 - 4) => Code actions for diagnostic "ID" configuration with severity None, Silent, Suggestion, Warning and Error /// 2. (5 - 9) => Code actions for diagnostic "Category" configuration with severity None, Silent, Suggestion, Warning and Error /// 3. (10 - 14) => Code actions for all analyzer diagnostics configuration with severity None, Silent, Suggestion, Warning and Error /// </summary> protected override int CodeActionIndex => 6; [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_Empty() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"" FilePath=""z:\\Assembly1.csproj""> <Document FilePath=""z:\\file.cs""> [|class Program1 { }|] </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig""></AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"" FilePath=""z:\\Assembly1.csproj""> <Document FilePath=""z:\\file.cs""> class Program1 { } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] # Default severity for analyzer diagnostics with category 'CustomCategory' dotnet_analyzer_diagnostic.category-CustomCategory.severity = silent </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_RuleExists() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"" FilePath=""z:\\Assembly1.csproj""> <Document FilePath=""z:\\file.cs""> [|class Program1 { }|] </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] dotnet_analyzer_diagnostic.category-CustomCategory.severity = suggestion # Comment </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"" FilePath=""z:\\Assembly1.csproj""> <Document FilePath=""z:\\file.cs""> class Program1 { } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] dotnet_analyzer_diagnostic.category-CustomCategory.severity = silent # Comment </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_RuleIdEntryExists() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"" FilePath=""z:\\Assembly1.csproj""> <Document FilePath=""z:\\file.cs""> [|class Program1 { }|] </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] dotnet_diagnostic.XYZ0001.severity = suggestion # Comment </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"" FilePath=""z:\\Assembly1.csproj""> <Document FilePath=""z:\\file.cs""> class Program1 { } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] dotnet_diagnostic.XYZ0001.severity = suggestion # Comment # Default severity for analyzer diagnostics with category 'CustomCategory' dotnet_analyzer_diagnostic.category-CustomCategory.severity = silent </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_InvalidHeader() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"" FilePath=""z:\\Assembly1.csproj""> <Document FilePath=""z:\\file.cs""> [|class Program1 { }|] </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.vb] dotnet_analyzer_diagnostic.category-CustomCategory.severity = suggestion </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"" FilePath=""z:\\Assembly1.csproj""> <Document FilePath=""z:\\file.cs""> class Program1 { } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.vb] dotnet_analyzer_diagnostic.category-CustomCategory.severity = suggestion [*.cs] # Default severity for analyzer diagnostics with category 'CustomCategory' dotnet_analyzer_diagnostic.category-CustomCategory.severity = silent </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_MaintainExistingEntry() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"" FilePath=""z:\\Assembly1.csproj""> <Document FilePath=""z:\\file.cs""> [|class Program1 { }|] </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{vb,cs}] dotnet_analyzer_diagnostic.category-CustomCategory.severity = silent </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, input, CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_DiagnosticsSuppressed() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"" FilePath=""z:\\Assembly1.csproj""> <Document FilePath=""z:\\file.cs""> [|class Program1 { }|] </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{vb,cs}] dotnet_analyzer_diagnostic.category-CustomCategory.severity = none </AnalyzerConfigDocument> </Project> </Workspace>"; await TestMissingInRegularAndScriptAsync(input); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_InvalidRule() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"" FilePath=""z:\\Assembly1.csproj""> <Document FilePath=""z:\\file.cs""> [|class Program1 { }|] </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{vb,cs}] dotnet_analyzer_diagnostic.category-XYZ1111Category.severity = suggestion </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"" FilePath=""z:\\Assembly1.csproj""> <Document FilePath=""z:\\file.cs""> [|class Program1 { }|] </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{vb,cs}] dotnet_analyzer_diagnostic.category-XYZ1111Category.severity = suggestion # Default severity for analyzer diagnostics with category 'CustomCategory' dotnet_analyzer_diagnostic.category-CustomCategory.severity = silent </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_RegexHeaderMatch() { // NOTE: Even though we have a regex match, bulk configuration code fix is always applied to all files // within the editorconfig cone, so it generates a new entry. var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"" FilePath=""z:\\Assembly1.csproj""> <Document FilePath=""z:\\Program/file.cs""> [|class Program1 { }|] </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*am/fi*e.cs] # Default severity for analyzer diagnostics with category 'CustomCategory' dotnet_analyzer_diagnostic.category-CustomCategory.severity = warning </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"" FilePath=""z:\\Assembly1.csproj""> <Document FilePath=""z:\\Program/file.cs""> class Program1 { } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*am/fi*e.cs] # Default severity for analyzer diagnostics with category 'CustomCategory' dotnet_analyzer_diagnostic.category-CustomCategory.severity = warning [*.cs] # Default severity for analyzer diagnostics with category 'CustomCategory' dotnet_analyzer_diagnostic.category-CustomCategory.severity = silent </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_RegexHeaderNonMatch() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"" FilePath=""z:\\Assembly1.csproj""> <Document FilePath=""z:\\Program/file.cs""> [|class Program1 { }|] </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*am/fii*e.cs] # Default severity for analyzer diagnostics with category 'CustomCategory' dotnet_analyzer_diagnostic.category-CustomCategory.severity = warning </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"" FilePath=""z:\\Assembly1.csproj""> <Document FilePath=""z:\\Program/file.cs""> class Program1 { } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*am/fii*e.cs] # Default severity for analyzer diagnostics with category 'CustomCategory' dotnet_analyzer_diagnostic.category-CustomCategory.severity = warning [*.cs] # Default severity for analyzer diagnostics with category 'CustomCategory' dotnet_analyzer_diagnostic.category-CustomCategory.severity = silent </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CodeFixes.Configuration.ConfigureSeverity; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.Configuration.ConfigureSeverity { public abstract partial class CategoryBasedSeverityConfigurationTests : AbstractSuppressionDiagnosticTest { private sealed class CustomDiagnosticAnalyzer : DiagnosticAnalyzer { private static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor( id: "XYZ0001", title: "Title", messageFormat: "Message", category: "CustomCategory", defaultSeverity: DiagnosticSeverity.Info, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule); public override void Initialize(AnalysisContext context) { context.RegisterSyntaxNodeAction( c => c.ReportDiagnostic(Diagnostic.Create(Rule, c.Node.GetLocation())), SyntaxKind.ClassDeclaration); } } protected internal override string GetLanguage() => LanguageNames.CSharp; protected override ParseOptions GetScriptOptions() => Options.Script; internal override Tuple<DiagnosticAnalyzer, IConfigurationFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace) { return new Tuple<DiagnosticAnalyzer, IConfigurationFixProvider>( new CustomDiagnosticAnalyzer(), new ConfigureSeverityLevelCodeFixProvider()); } public sealed class SilentConfigurationTests : CategoryBasedSeverityConfigurationTests { /// <summary> /// Code action ranges: /// 1. (0 - 4) => Code actions for diagnostic "ID" configuration with severity None, Silent, Suggestion, Warning and Error /// 2. (5 - 9) => Code actions for diagnostic "Category" configuration with severity None, Silent, Suggestion, Warning and Error /// 3. (10 - 14) => Code actions for all analyzer diagnostics configuration with severity None, Silent, Suggestion, Warning and Error /// </summary> protected override int CodeActionIndex => 6; [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_Empty() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"" FilePath=""z:\\Assembly1.csproj""> <Document FilePath=""z:\\file.cs""> [|class Program1 { }|] </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig""></AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"" FilePath=""z:\\Assembly1.csproj""> <Document FilePath=""z:\\file.cs""> class Program1 { } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] # Default severity for analyzer diagnostics with category 'CustomCategory' dotnet_analyzer_diagnostic.category-CustomCategory.severity = silent </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_RuleExists() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"" FilePath=""z:\\Assembly1.csproj""> <Document FilePath=""z:\\file.cs""> [|class Program1 { }|] </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] dotnet_analyzer_diagnostic.category-CustomCategory.severity = suggestion # Comment </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"" FilePath=""z:\\Assembly1.csproj""> <Document FilePath=""z:\\file.cs""> class Program1 { } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] dotnet_analyzer_diagnostic.category-CustomCategory.severity = silent # Comment </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_RuleIdEntryExists() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"" FilePath=""z:\\Assembly1.csproj""> <Document FilePath=""z:\\file.cs""> [|class Program1 { }|] </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] dotnet_diagnostic.XYZ0001.severity = suggestion # Comment </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"" FilePath=""z:\\Assembly1.csproj""> <Document FilePath=""z:\\file.cs""> class Program1 { } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] dotnet_diagnostic.XYZ0001.severity = suggestion # Comment # Default severity for analyzer diagnostics with category 'CustomCategory' dotnet_analyzer_diagnostic.category-CustomCategory.severity = silent </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_InvalidHeader() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"" FilePath=""z:\\Assembly1.csproj""> <Document FilePath=""z:\\file.cs""> [|class Program1 { }|] </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.vb] dotnet_analyzer_diagnostic.category-CustomCategory.severity = suggestion </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"" FilePath=""z:\\Assembly1.csproj""> <Document FilePath=""z:\\file.cs""> class Program1 { } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.vb] dotnet_analyzer_diagnostic.category-CustomCategory.severity = suggestion [*.cs] # Default severity for analyzer diagnostics with category 'CustomCategory' dotnet_analyzer_diagnostic.category-CustomCategory.severity = silent </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_MaintainExistingEntry() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"" FilePath=""z:\\Assembly1.csproj""> <Document FilePath=""z:\\file.cs""> [|class Program1 { }|] </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{vb,cs}] dotnet_analyzer_diagnostic.category-CustomCategory.severity = silent </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, input, CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_DiagnosticsSuppressed() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"" FilePath=""z:\\Assembly1.csproj""> <Document FilePath=""z:\\file.cs""> [|class Program1 { }|] </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{vb,cs}] dotnet_analyzer_diagnostic.category-CustomCategory.severity = none </AnalyzerConfigDocument> </Project> </Workspace>"; await TestMissingInRegularAndScriptAsync(input); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_InvalidRule() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"" FilePath=""z:\\Assembly1.csproj""> <Document FilePath=""z:\\file.cs""> [|class Program1 { }|] </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{vb,cs}] dotnet_analyzer_diagnostic.category-XYZ1111Category.severity = suggestion </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"" FilePath=""z:\\Assembly1.csproj""> <Document FilePath=""z:\\file.cs""> [|class Program1 { }|] </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{vb,cs}] dotnet_analyzer_diagnostic.category-XYZ1111Category.severity = suggestion # Default severity for analyzer diagnostics with category 'CustomCategory' dotnet_analyzer_diagnostic.category-CustomCategory.severity = silent </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_RegexHeaderMatch() { // NOTE: Even though we have a regex match, bulk configuration code fix is always applied to all files // within the editorconfig cone, so it generates a new entry. var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"" FilePath=""z:\\Assembly1.csproj""> <Document FilePath=""z:\\Program/file.cs""> [|class Program1 { }|] </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*am/fi*e.cs] # Default severity for analyzer diagnostics with category 'CustomCategory' dotnet_analyzer_diagnostic.category-CustomCategory.severity = warning </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"" FilePath=""z:\\Assembly1.csproj""> <Document FilePath=""z:\\Program/file.cs""> class Program1 { } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*am/fi*e.cs] # Default severity for analyzer diagnostics with category 'CustomCategory' dotnet_analyzer_diagnostic.category-CustomCategory.severity = warning [*.cs] # Default severity for analyzer diagnostics with category 'CustomCategory' dotnet_analyzer_diagnostic.category-CustomCategory.severity = silent </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_RegexHeaderNonMatch() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"" FilePath=""z:\\Assembly1.csproj""> <Document FilePath=""z:\\Program/file.cs""> [|class Program1 { }|] </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*am/fii*e.cs] # Default severity for analyzer diagnostics with category 'CustomCategory' dotnet_analyzer_diagnostic.category-CustomCategory.severity = warning </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"" FilePath=""z:\\Assembly1.csproj""> <Document FilePath=""z:\\Program/file.cs""> class Program1 { } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*am/fii*e.cs] # Default severity for analyzer diagnostics with category 'CustomCategory' dotnet_analyzer_diagnostic.category-CustomCategory.severity = warning [*.cs] # Default severity for analyzer diagnostics with category 'CustomCategory' dotnet_analyzer_diagnostic.category-CustomCategory.severity = silent </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } } } }
-1
dotnet/roslyn
56,419
Fix partial method doc comments
Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
RikkiGibson
"2021-09-15T20:47:39Z"
"2021-09-21T23:49:10Z"
0f60b3e9446f5d0fc14a570998c81a5d6c40cc23
8cda7462843d43d9b72039eede2f4cb43126cac2
Fix partial method doc comments. Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
./src/Compilers/Server/VBCSCompilerTests/Extensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.CompilerServer.UnitTests { internal static class Extensions { public static Task ToTask(this WaitHandle handle, int? timeoutMilliseconds) { RegisteredWaitHandle registeredHandle = null; var tcs = new TaskCompletionSource<object>(); registeredHandle = ThreadPool.RegisterWaitForSingleObject( handle, (_, timeout) => { tcs.TrySetResult(null); if (registeredHandle is object) { registeredHandle.Unregister(waitObject: null); } }, null, timeoutMilliseconds ?? -1, executeOnlyOnce: true); return tcs.Task; } public static async Task WaitOneAsync(this WaitHandle handle, int? timeoutMilliseconds = null) => await handle.ToTask(timeoutMilliseconds); public static async ValueTask<T> TakeAsync<T>(this BlockingCollection<T> collection, TimeSpan? pollTimeSpan = null, CancellationToken cancellationToken = default) { var delay = pollTimeSpan ?? TimeSpan.FromSeconds(.25); do { if (collection.TryTake(out T value)) { return value; } await Task.Delay(delay, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); } while (true); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.CompilerServer.UnitTests { internal static class Extensions { public static Task ToTask(this WaitHandle handle, int? timeoutMilliseconds) { RegisteredWaitHandle registeredHandle = null; var tcs = new TaskCompletionSource<object>(); registeredHandle = ThreadPool.RegisterWaitForSingleObject( handle, (_, timeout) => { tcs.TrySetResult(null); if (registeredHandle is object) { registeredHandle.Unregister(waitObject: null); } }, null, timeoutMilliseconds ?? -1, executeOnlyOnce: true); return tcs.Task; } public static async Task WaitOneAsync(this WaitHandle handle, int? timeoutMilliseconds = null) => await handle.ToTask(timeoutMilliseconds); public static async ValueTask<T> TakeAsync<T>(this BlockingCollection<T> collection, TimeSpan? pollTimeSpan = null, CancellationToken cancellationToken = default) { var delay = pollTimeSpan ?? TimeSpan.FromSeconds(.25); do { if (collection.TryTake(out T value)) { return value; } await Task.Delay(delay, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); } while (true); } } }
-1
dotnet/roslyn
56,419
Fix partial method doc comments
Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
RikkiGibson
"2021-09-15T20:47:39Z"
"2021-09-21T23:49:10Z"
0f60b3e9446f5d0fc14a570998c81a5d6c40cc23
8cda7462843d43d9b72039eede2f4cb43126cac2
Fix partial method doc comments. Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
./src/EditorFeatures/Core/GoToDefinition/AbstractGoToDefinitionService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.FindUsages; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.FindUsages; using Microsoft.CodeAnalysis.GoToDefinition; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Navigation; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.GoToDefinition { // GoToDefinition internal abstract class AbstractGoToDefinitionService : AbstractFindDefinitionService, IGoToDefinitionService { private readonly IThreadingContext _threadingContext; /// <summary> /// Used to present go to definition results in <see cref="TryGoToDefinition(Document, int, CancellationToken)"/> /// </summary> private readonly IStreamingFindUsagesPresenter _streamingPresenter; protected AbstractGoToDefinitionService( IThreadingContext threadingContext, IStreamingFindUsagesPresenter streamingPresenter) { _threadingContext = threadingContext; _streamingPresenter = streamingPresenter; } async Task<IEnumerable<INavigableItem>?> IGoToDefinitionService.FindDefinitionsAsync(Document document, int position, CancellationToken cancellationToken) => await FindDefinitionsAsync(document, position, cancellationToken).ConfigureAwait(false); private static bool TryNavigateToSpan(Document document, int position, CancellationToken cancellationToken) { var solution = document.Project.Solution; var workspace = solution.Workspace; var service = workspace.Services.GetRequiredService<IDocumentNavigationService>(); var options = solution.Options.WithChangedOption(NavigationOptions.PreferProvisionalTab, true); options = options.WithChangedOption(NavigationOptions.ActivateTab, true); return service.TryNavigateToPosition(workspace, document.Id, position, virtualSpace: 0, options, cancellationToken); } public bool TryGoToDefinition(Document document, int position, CancellationToken cancellationToken) { var symbolService = document.GetRequiredLanguageService<IGoToDefinitionSymbolService>(); var targetPositionOfControlFlow = symbolService.GetTargetIfControlFlowAsync(document, position, cancellationToken).WaitAndGetResult(cancellationToken); if (targetPositionOfControlFlow is not null) { return TryNavigateToSpan(document, targetPositionOfControlFlow.Value, cancellationToken); } // Try to compute the referenced symbol and attempt to go to definition for the symbol. var (symbol, _) = symbolService.GetSymbolAndBoundSpanAsync(document, position, includeType: true, cancellationToken).WaitAndGetResult(cancellationToken); if (symbol is null) return false; // if the symbol only has a single source location, and we're already on it, // try to see if there's a better symbol we could navigate to. var remapped = TryGoToAlternativeLocationIfAlreadyOnDefinition(document, position, symbol, cancellationToken); if (remapped) return true; var isThirdPartyNavigationAllowed = IsThirdPartyNavigationAllowed(symbol, position, document, cancellationToken); return GoToDefinitionHelpers.TryGoToDefinition( symbol, document.Project.Solution, _threadingContext, _streamingPresenter, thirdPartyNavigationAllowed: isThirdPartyNavigationAllowed, cancellationToken: cancellationToken); } private bool TryGoToAlternativeLocationIfAlreadyOnDefinition( Document document, int position, ISymbol symbol, CancellationToken cancellationToken) { var project = document.Project; var solution = project.Solution; var sourceLocations = symbol.Locations.WhereAsArray(loc => loc.IsInSource); if (sourceLocations.Length != 1) return false; var definitionLocation = sourceLocations[0]; if (!definitionLocation.SourceSpan.IntersectsWith(position)) return false; var definitionTree = definitionLocation.SourceTree; var definitionDocument = solution.GetDocument(definitionTree); if (definitionDocument != document) return false; // Ok, we were already on the definition. Look for better symbols we could show results // for instead. For now, just see if we're on an interface member impl. If so, we can // instead navigate to the actual interface member. // // In the future we can expand this with other mappings if appropriate. var interfaceImpls = symbol.ExplicitOrImplicitInterfaceImplementations(); if (interfaceImpls.Length == 0) return false; var title = string.Format(EditorFeaturesResources._0_implemented_members, FindUsagesHelpers.GetDisplayName(symbol)); return _threadingContext.JoinableTaskFactory.Run(async () => { using var _ = ArrayBuilder<DefinitionItem>.GetInstance(out var definitions); foreach (var impl in interfaceImpls) { // Use ConfigureAwait(true) here. Not for a correctness requirements, but because we're // already blocking the UI thread by being in a JTF.Run call. So we might as well try to // continue to use the blocking UI thread to do as much work as possible instead of making // it wait for threadpool threads to be available to process the work. definitions.AddRange(await GoToDefinitionHelpers.GetDefinitionsAsync( impl, solution, thirdPartyNavigationAllowed: false, cancellationToken).ConfigureAwait(true)); } return await _streamingPresenter.TryNavigateToOrPresentItemsAsync( _threadingContext, solution.Workspace, title, definitions.ToImmutable(), cancellationToken).ConfigureAwait(true); }); } private static bool IsThirdPartyNavigationAllowed(ISymbol symbolToNavigateTo, int caretPosition, Document document, CancellationToken cancellationToken) { var syntaxRoot = document.GetSyntaxRootSynchronously(cancellationToken); var syntaxFactsService = document.GetRequiredLanguageService<ISyntaxFactsService>(); var containingTypeDeclaration = syntaxFactsService.GetContainingTypeDeclaration(syntaxRoot, caretPosition); if (containingTypeDeclaration != null) { var semanticModel = document.GetSemanticModelAsync(cancellationToken).WaitAndGetResult(cancellationToken); Debug.Assert(semanticModel != null); // Allow third parties to navigate to all symbols except types/constructors // if we are navigating from the corresponding type. if (semanticModel.GetDeclaredSymbol(containingTypeDeclaration, cancellationToken) is ITypeSymbol containingTypeSymbol && (symbolToNavigateTo is ITypeSymbol || symbolToNavigateTo.IsConstructor())) { var candidateTypeSymbol = symbolToNavigateTo is ITypeSymbol ? symbolToNavigateTo : symbolToNavigateTo.ContainingType; if (Equals(containingTypeSymbol, candidateTypeSymbol)) { // We are navigating from the same type, so don't allow third parties to perform the navigation. // This ensures that if we navigate to a class from within that class, we'll stay in the same file // rather than navigate to, say, XAML. return false; } } } return true; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.FindUsages; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.FindUsages; using Microsoft.CodeAnalysis.GoToDefinition; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Navigation; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.GoToDefinition { // GoToDefinition internal abstract class AbstractGoToDefinitionService : AbstractFindDefinitionService, IGoToDefinitionService { private readonly IThreadingContext _threadingContext; /// <summary> /// Used to present go to definition results in <see cref="TryGoToDefinition(Document, int, CancellationToken)"/> /// </summary> private readonly IStreamingFindUsagesPresenter _streamingPresenter; protected AbstractGoToDefinitionService( IThreadingContext threadingContext, IStreamingFindUsagesPresenter streamingPresenter) { _threadingContext = threadingContext; _streamingPresenter = streamingPresenter; } async Task<IEnumerable<INavigableItem>?> IGoToDefinitionService.FindDefinitionsAsync(Document document, int position, CancellationToken cancellationToken) => await FindDefinitionsAsync(document, position, cancellationToken).ConfigureAwait(false); private static bool TryNavigateToSpan(Document document, int position, CancellationToken cancellationToken) { var solution = document.Project.Solution; var workspace = solution.Workspace; var service = workspace.Services.GetRequiredService<IDocumentNavigationService>(); var options = solution.Options.WithChangedOption(NavigationOptions.PreferProvisionalTab, true); options = options.WithChangedOption(NavigationOptions.ActivateTab, true); return service.TryNavigateToPosition(workspace, document.Id, position, virtualSpace: 0, options, cancellationToken); } public bool TryGoToDefinition(Document document, int position, CancellationToken cancellationToken) { var symbolService = document.GetRequiredLanguageService<IGoToDefinitionSymbolService>(); var targetPositionOfControlFlow = symbolService.GetTargetIfControlFlowAsync(document, position, cancellationToken).WaitAndGetResult(cancellationToken); if (targetPositionOfControlFlow is not null) { return TryNavigateToSpan(document, targetPositionOfControlFlow.Value, cancellationToken); } // Try to compute the referenced symbol and attempt to go to definition for the symbol. var (symbol, _) = symbolService.GetSymbolAndBoundSpanAsync(document, position, includeType: true, cancellationToken).WaitAndGetResult(cancellationToken); if (symbol is null) return false; // if the symbol only has a single source location, and we're already on it, // try to see if there's a better symbol we could navigate to. var remapped = TryGoToAlternativeLocationIfAlreadyOnDefinition(document, position, symbol, cancellationToken); if (remapped) return true; var isThirdPartyNavigationAllowed = IsThirdPartyNavigationAllowed(symbol, position, document, cancellationToken); return GoToDefinitionHelpers.TryGoToDefinition( symbol, document.Project.Solution, _threadingContext, _streamingPresenter, thirdPartyNavigationAllowed: isThirdPartyNavigationAllowed, cancellationToken: cancellationToken); } private bool TryGoToAlternativeLocationIfAlreadyOnDefinition( Document document, int position, ISymbol symbol, CancellationToken cancellationToken) { var project = document.Project; var solution = project.Solution; var sourceLocations = symbol.Locations.WhereAsArray(loc => loc.IsInSource); if (sourceLocations.Length != 1) return false; var definitionLocation = sourceLocations[0]; if (!definitionLocation.SourceSpan.IntersectsWith(position)) return false; var definitionTree = definitionLocation.SourceTree; var definitionDocument = solution.GetDocument(definitionTree); if (definitionDocument != document) return false; // Ok, we were already on the definition. Look for better symbols we could show results // for instead. For now, just see if we're on an interface member impl. If so, we can // instead navigate to the actual interface member. // // In the future we can expand this with other mappings if appropriate. var interfaceImpls = symbol.ExplicitOrImplicitInterfaceImplementations(); if (interfaceImpls.Length == 0) return false; var title = string.Format(EditorFeaturesResources._0_implemented_members, FindUsagesHelpers.GetDisplayName(symbol)); return _threadingContext.JoinableTaskFactory.Run(async () => { using var _ = ArrayBuilder<DefinitionItem>.GetInstance(out var definitions); foreach (var impl in interfaceImpls) { // Use ConfigureAwait(true) here. Not for a correctness requirements, but because we're // already blocking the UI thread by being in a JTF.Run call. So we might as well try to // continue to use the blocking UI thread to do as much work as possible instead of making // it wait for threadpool threads to be available to process the work. definitions.AddRange(await GoToDefinitionHelpers.GetDefinitionsAsync( impl, solution, thirdPartyNavigationAllowed: false, cancellationToken).ConfigureAwait(true)); } return await _streamingPresenter.TryNavigateToOrPresentItemsAsync( _threadingContext, solution.Workspace, title, definitions.ToImmutable(), cancellationToken).ConfigureAwait(true); }); } private static bool IsThirdPartyNavigationAllowed(ISymbol symbolToNavigateTo, int caretPosition, Document document, CancellationToken cancellationToken) { var syntaxRoot = document.GetSyntaxRootSynchronously(cancellationToken); var syntaxFactsService = document.GetRequiredLanguageService<ISyntaxFactsService>(); var containingTypeDeclaration = syntaxFactsService.GetContainingTypeDeclaration(syntaxRoot, caretPosition); if (containingTypeDeclaration != null) { var semanticModel = document.GetSemanticModelAsync(cancellationToken).WaitAndGetResult(cancellationToken); Debug.Assert(semanticModel != null); // Allow third parties to navigate to all symbols except types/constructors // if we are navigating from the corresponding type. if (semanticModel.GetDeclaredSymbol(containingTypeDeclaration, cancellationToken) is ITypeSymbol containingTypeSymbol && (symbolToNavigateTo is ITypeSymbol || symbolToNavigateTo.IsConstructor())) { var candidateTypeSymbol = symbolToNavigateTo is ITypeSymbol ? symbolToNavigateTo : symbolToNavigateTo.ContainingType; if (Equals(containingTypeSymbol, candidateTypeSymbol)) { // We are navigating from the same type, so don't allow third parties to perform the navigation. // This ensures that if we navigate to a class from within that class, we'll stay in the same file // rather than navigate to, say, XAML. return false; } } } return true; } } }
-1
dotnet/roslyn
56,419
Fix partial method doc comments
Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
RikkiGibson
"2021-09-15T20:47:39Z"
"2021-09-21T23:49:10Z"
0f60b3e9446f5d0fc14a570998c81a5d6c40cc23
8cda7462843d43d9b72039eede2f4cb43126cac2
Fix partial method doc comments. Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
./src/Compilers/CSharp/Test/Emit/BreakingChanges.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class BreakingChanges : CSharpTestBase { [Fact, WorkItem(527050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527050")] [Trait("Feature", "Directives")] public void TestCS1024DefineWithUnicodeInMiddle() { var test = @"#de\u0066in\U00000065 ABC"; // This is now a negative test, this should not be allowed. SyntaxFactory.ParseSyntaxTree(test).GetDiagnostics().Verify(Diagnostic(ErrorCode.ERR_PPDirectiveExpected, @"de\u0066in\U00000065")); } [Fact, WorkItem(527951, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527951")] public void CS0133ERR_NotConstantExpression05() { var text = @" class A { public void Do() { const object o1 = null; const string o2 = (string)o1; // Dev10 reports CS0133 } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (7,22): warning CS0219: The variable 'o2' is assigned but its value is never used // const string o2 = (string)o1; // Dev10 reports CS0133 Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "o2").WithArguments("o2") ); } [WorkItem(527943, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527943")] [Fact] public void CS0146ERR_CircularBase05() { var text = @" interface IFace<T> { } class B : IFace<B.C.D> { public class C { public class D { } } } "; var comp = CreateCompilation(text); // In Dev10, there was an error - ErrorCode.ERR_CircularBase at (4,7) Assert.Equal(0, comp.GetDiagnostics().Count()); } [WorkItem(540371, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540371"), WorkItem(530792, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530792")] [Fact] private void CS0507ERR_CantChangeAccessOnOverride_TestSynthesizedSealedAccessorsInDifferentAssembly() { var source1 = @" using System.Collections.Generic; public class Base<T> { public virtual List<T> Property1 { get { return null; } protected internal set { } } public virtual List<T> Property2 { protected internal get { return null; } set { } } }"; var compilation1 = CreateCompilation(source1); var source2 = @" using System.Collections.Generic; public class Derived : Base<int> { public sealed override List<int> Property1 { get { return null; } } public sealed override List<int> Property2 { set { } } }"; var comp = CreateCompilation(source2, new[] { new CSharpCompilationReference(compilation1) }); comp.VerifyDiagnostics(); // This is not a breaking change - but it is a change in behavior from Dev10 // Dev10 used to report following errors - // Error CS0507: 'Derived.Property1.set': cannot change access modifiers when overriding 'protected' inherited member 'Base<int>.Property1.set' // Error CS0507: 'Derived.Property2.get': cannot change access modifiers when overriding 'protected' inherited member 'Base<int>.Property2.get' // Roslyn makes this case work by synthesizing 'protected' accessors for the missing ones var baseClass = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("Base"); var baseProperty1 = baseClass.GetMember<PropertySymbol>("Property1"); var baseProperty2 = baseClass.GetMember<PropertySymbol>("Property2"); Assert.Equal(Accessibility.Public, baseProperty1.DeclaredAccessibility); Assert.Equal(Accessibility.Public, baseProperty1.GetMethod.DeclaredAccessibility); Assert.Equal(Accessibility.ProtectedOrInternal, baseProperty1.SetMethod.DeclaredAccessibility); Assert.Equal(Accessibility.Public, baseProperty2.DeclaredAccessibility); Assert.Equal(Accessibility.ProtectedOrInternal, baseProperty2.GetMethod.DeclaredAccessibility); Assert.Equal(Accessibility.Public, baseProperty2.SetMethod.DeclaredAccessibility); var derivedClass = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("Derived"); var derivedProperty1 = derivedClass.GetMember<SourcePropertySymbol>("Property1"); var derivedProperty2 = derivedClass.GetMember<SourcePropertySymbol>("Property2"); Assert.Equal(Accessibility.Public, derivedProperty1.DeclaredAccessibility); Assert.Equal(Accessibility.Public, derivedProperty1.GetMethod.DeclaredAccessibility); Assert.Null(derivedProperty1.SetMethod); Assert.Equal(Accessibility.Public, derivedProperty2.DeclaredAccessibility); Assert.Null(derivedProperty2.GetMethod); Assert.Equal(Accessibility.Public, derivedProperty2.SetMethod.DeclaredAccessibility); var derivedProperty1Synthesized = derivedProperty1.SynthesizedSealedAccessorOpt; var derivedProperty2Synthesized = derivedProperty2.SynthesizedSealedAccessorOpt; Assert.Equal(MethodKind.PropertySet, derivedProperty1Synthesized.MethodKind); Assert.Equal(Accessibility.Protected, derivedProperty1Synthesized.DeclaredAccessibility); Assert.Equal(MethodKind.PropertyGet, derivedProperty2Synthesized.MethodKind); Assert.Equal(Accessibility.Protected, derivedProperty2Synthesized.DeclaredAccessibility); } // Confirm that this error no longer exists [Fact] public void CS0609ERR_NameAttributeOnOverride() { var text = @" using System.Runtime.CompilerServices; public class idx { public virtual int this[int iPropIndex] { get { return 0; } set { } } } public class MonthDays : idx { [IndexerName(""MonthInfoIndexer"")] public override int this[int iPropIndex] { get { return 1; } set { } } } "; var compilation = CreateCompilation(text); compilation.VerifyDiagnostics(); var indexer = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("MonthDays").Indexers.Single(); Assert.Equal(Microsoft.CodeAnalysis.WellKnownMemberNames.Indexer, indexer.Name); Assert.Equal("MonthInfoIndexer", indexer.MetadataName); } [WorkItem(527116, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527116")] [Fact] public void RegressWarningInSingleMultiLineMixedXml() { var text = @" /// <summary> /** This is the summary */ /// </summary> class Test { /** <summary> */ /// This is the summary1 /** </summary> */ public int Field = 0; /** <summary> */ /// This is the summary2 /// </summary> string Prop { get; set; } /// <summary> /** This is the summary3 * </summary> */ static int Main() { return new Test().Field; } } "; var tree = Parse(text, options: TestOptions.RegularWithDocumentationComments); Assert.NotNull(tree); Assert.Equal(text, tree.GetCompilationUnitRoot().ToFullString()); // Dev10 allows (no warning) // Roslyn gives Warning CS1570 - "XML Comment has badly formed XML..." Assert.Equal(8, tree.GetDiagnostics().Count()); } [Fact, WorkItem(527093, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527093")] public void NoCS1570ForUndefinedXmlNamespace() { var text = @" /// <xml> xmlns:s=""uuid: BDC6E3F0-6DA3-11d1-A2A3 - 00AA00C14882""> /// <s:inventory> /// </s:inventory> /// </xml> class A { } "; var tree = Parse(text, options: TestOptions.RegularWithDocumentationComments); Assert.NotNull(tree); Assert.Equal(text, tree.GetCompilationUnitRoot().ToFullString()); // Native Warning CS1570 - "XML Comment has badly formed XML..." // Roslyn no Assert.Empty(tree.GetDiagnostics()); } [Fact, WorkItem(541345, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541345")] public void CS0019_TestNullCoalesceWithNullOperandsErrors() { var source = @" class Program { static void Main() { // This is acceptable by the native compiler and treated as a non-constant null literal. // That violates the specification; we now correctly treat this as an error. object a = null ?? null; // The null coalescing operator never produces a compile-time constant even when // the arguments are constants. const object b = null ?? ""ABC""; const string c = ""DEF"" ?? null; const int d = (int?)null ?? 123; // It is legal, though pointless, to use null literals and constants in coalescing // expressions, provided you don't try to make the result a constant. These should // produce no errors: object z = null ?? ""GHI""; string y = ""JKL"" ?? null; int x = (int?)null ?? 456; } } "; CreateCompilation(source).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_BadBinaryOps, "null ?? null").WithArguments("??", "<null>", "<null>"), Diagnostic(ErrorCode.ERR_NotConstantExpression, @"null ?? ""ABC""").WithArguments("b"), Diagnostic(ErrorCode.ERR_NotConstantExpression, @"""DEF"" ?? null").WithArguments("c"), Diagnostic(ErrorCode.ERR_NotConstantExpression, "(int?)null ?? 123").WithArguments("d")); } [Fact, WorkItem(528676, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528676"), WorkItem(528676, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528676")] private // CS0657WRN_AttributeLocationOnBadDeclaration_AfterAttrDeclOrDelegate void CS1730ERR_CantUseAttributeOnInvaildLocation() { var test = @"using System; [AttributeUsage(AttributeTargets.All)] public class Goo : Attribute { public int Name; public Goo(int sName) { Name = sName; } } public delegate void EventHandler(object sender, EventArgs e); [assembly: Goo(5)] public class Test { } "; // In Dev10, this is a warning CS0657 // Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "type") SyntaxFactory.ParseSyntaxTree(test).GetDiagnostics().Verify(Diagnostic(ErrorCode.ERR_GlobalAttributesNotFirst, "assembly")); } [WorkItem(528711, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528711")] [Fact] public void CS9259_StructLayoutCycle() { var text = @"struct S1<T> { S1<S1<T>>.S2 x; struct S2 { static T x; } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (3,18): warning CS0169: The field 'S1<T>.x' is never used // S1<S1<T>>.S2 x; Diagnostic(ErrorCode.WRN_UnreferencedField, "x").WithArguments("S1<T>.x").WithLocation(3, 18), // (6,18): warning CS0169: The field 'S1<T>.S2.x' is never used // static T x; Diagnostic(ErrorCode.WRN_UnreferencedField, "x").WithArguments("S1<T>.S2.x").WithLocation(6, 18) ); } [WorkItem(528094, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528094")] [Fact] public void FormattingUnicodeNotPartOfId() { string source = @" // <Area> Lexical - Unicode Characters</Area> // <Title> // Compiler considers identifiers, which differ only in formatting-character, as different ones; // This is not actually correct behavior but for the time being this is what we expect //</Title> //<RelatedBugs>DDB:133151</RelatedBugs> // <Expects Status=Success></Expects> #define A using System; class Program { static int Main() { int x = 0; #if A == A\uFFFB x=1; #endif Console.Write(x); return x; } } "; // Dev10 print '0' CompileAndVerify(source, expectedOutput: "1"); } [WorkItem(529000, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529000")] [Fact] public void NoCS0121ForSwitchedParamNames_Dev10814222() { string source = @" using System; // Bug Dev10: 814222 resolved as Won't Fix class Test { static void Main() { Console.Write(Bar(x: 1, y: ""T0"")); // Dev10:CS0121 Test01.Main01(); } public static int Bar(int x, string y, params int[] z) { return 1; } public static int Bar(string y, int x) { return 0; } // Roslyn pick this one } class Test01 { public static int Bar<T>(int x, T y, params int[] z) { return 1; } public static int Bar<T>(string y, int x) { return 0; } // Roslyn pick this one public static int Goo<T>(int x, T y) { return 1; } public static int Goo<T>(string y, int x) { return 0; } // Roslyn pick this one public static int AbcDef<T>(int x, T y) { return 0; } // Roslyn pick this one public static int AbcDef<T>(string y, int x, params int[] z) { return 1; } public static void Main01() { Console.Write(Bar<string>(x: 1, y: ""T1"")); // Dev10:CS0121 Console.Write(Goo<string>(x: 1, y: ""T2"")); // Dev10:CS0121 Console.Write(AbcDef<string>(x: 1, y: ""T3"")); // Dev10:CS0121 } } "; CompileAndVerify(source, expectedOutput: "0000"); } [WorkItem(529001, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529001")] [WorkItem(529002, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529002")] [WorkItem(1067, "https://github.com/dotnet/roslyn/issues/1067")] [Fact] public void CS0185ERR_LockNeedsReference_RequireRefType() { var source = @" class C { void M<T, TClass, TStruct>() where TClass : class where TStruct : struct { lock (default(object)) ; lock (default(int)) ; // CS0185 lock (default(T)) {} // new CS0185 - no constraints (Bug#10755) lock (default(TClass)) {} lock (default(TStruct)) {} // new CS0185 - constraints to value type (Bug#10756) lock (null) {} // new CS0185 - null is not an object type } } "; var standardCompilation = CreateCompilation(source); var strictCompilation = CreateCompilation(source, parseOptions: TestOptions.Regular.WithStrictFeature()); standardCompilation.VerifyDiagnostics( // (8,32): warning CS0642: Possible mistaken empty statement // lock (default(object)) ; Diagnostic(ErrorCode.WRN_PossibleMistakenNullStatement, ";").WithLocation(8, 32), // (9,29): warning CS0642: Possible mistaken empty statement // lock (default(int)) ; // CS0185 Diagnostic(ErrorCode.WRN_PossibleMistakenNullStatement, ";").WithLocation(9, 29), // (9,15): error CS0185: 'int' is not a reference type as required by the lock statement // lock (default(int)) ; // CS0185 Diagnostic(ErrorCode.ERR_LockNeedsReference, "default(int)").WithArguments("int").WithLocation(9, 15), // (12,15): error CS0185: 'TStruct' is not a reference type as required by the lock statement // lock (default(TStruct)) {} // new CS0185 - constraints to value type (Bug#10756) Diagnostic(ErrorCode.ERR_LockNeedsReference, "default(TStruct)").WithArguments("TStruct").WithLocation(12, 15) ); strictCompilation.VerifyDiagnostics( // (8,32): warning CS0642: Possible mistaken empty statement // lock (default(object)) ; Diagnostic(ErrorCode.WRN_PossibleMistakenNullStatement, ";").WithLocation(8, 32), // (9,29): warning CS0642: Possible mistaken empty statement // lock (default(int)) ; // CS0185 Diagnostic(ErrorCode.WRN_PossibleMistakenNullStatement, ";").WithLocation(9, 29), // (9,15): error CS0185: 'int' is not a reference type as required by the lock statement // lock (default(int)) ; // CS0185 Diagnostic(ErrorCode.ERR_LockNeedsReference, "default(int)").WithArguments("int").WithLocation(9, 15), // (10,15): error CS0185: 'T' is not a reference type as required by the lock statement // lock (default(T)) {} // new CS0185 - no constraints (Bug#10755) Diagnostic(ErrorCode.ERR_LockNeedsReference, "default(T)").WithArguments("T").WithLocation(10, 15), // (12,15): error CS0185: 'TStruct' is not a reference type as required by the lock statement // lock (default(TStruct)) {} // new CS0185 - constraints to value type (Bug#10756) Diagnostic(ErrorCode.ERR_LockNeedsReference, "default(TStruct)").WithArguments("TStruct").WithLocation(12, 15), // (13,15): error CS0185: '<null>' is not a reference type as required by the lock statement // lock (null) {} // new CS0185 - null is not an object type Diagnostic(ErrorCode.ERR_LockNeedsReference, "null").WithArguments("<null>").WithLocation(13, 15) ); } [WorkItem(528972, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528972")] [Fact] public void CS0121ERR_AmbigCall_Lambda1() { var text = @" using System; class A { static void Main() { Goo( delegate () { throw new Exception(); }); // both Dev10 & Roslyn no error Goo(x: () => { throw new Exception(); }); // Dev10: CS0121, Roslyn: no error } public static void Goo(Action x) { Console.WriteLine(1); } public static void Goo(Func<int> x) { Console.WriteLine(2); // Roslyn call this one } } "; // Dev11 FIXED this, no error anymore (So Not breaking Dev11) // Dev10 reports CS0121 because ExpressionBinder::WhichConversionIsBetter fails to unwrap // the NamedArgumentSpecification to find the UNBOUNDLAMBDA and, thus, never calls // WhichLambdaConversionIsBetter. CreateCompilation(text).VerifyDiagnostics(); } [Fact, WorkItem(529202, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529202")] public void NoCS0029_ErrorOnZeroToEnumToTypeConversion() { string source = @" class Program { static void Main() { S s = 0; } } enum E { Zero, One, Two } struct S { public static implicit operator S(E s) { return E.Zero; } }"; // Dev10/11: (11,9): error CS0029: Cannot implicitly convert type 'int' to 'S' CreateCompilation(source).VerifyDiagnostics( // (6,15): error CS0029: Cannot implicitly convert type 'int' to 'S' // S s = 0; Diagnostic(ErrorCode.ERR_NoImplicitConv, "0").WithArguments("int", "S") ); } [Fact, WorkItem(529242, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529242")] public void ThrowOverflowExceptionForUncheckedCheckedLambda() { string source = @" using System; class Program { static void Main() { Func<int, int> d = checked(delegate(int i) { int max = int.MaxValue; try { int n = max + 1; } catch (OverflowException) { Console.Write(""OV ""); // Roslyn throw } return i; }); var r = unchecked(d(9)); Console.Write(r); } } "; CompileAndVerify(source, expectedOutput: "OV 9"); } [WorkItem(529262, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529262")] [Fact] public void PartialMethod_ParameterAndTypeParameterNames() { var source = @"using System; using System.Reflection; partial class C { static partial void M<T, U>(T x, U y); static partial void M<T1, T2>(T1 y, T2 x) { Console.Write(""{0}, {1} | "", x, y); var m = typeof(C).GetMethod(""M"", BindingFlags.Static | BindingFlags.NonPublic); var tp = m.GetGenericArguments(); Console.Write(""{0}, {1} | "", tp[0].Name, tp[1].Name); var p = m.GetParameters(); Console.Write(""{0}, {1}"", p[0].Name, p[1].Name); } static void Main() { M(x: 1, y: 2); } }"; // Dev12 would emit "2, 1 | T1, T2 | x, y". CompileAndVerify(source, expectedOutput: "2, 1 | T, U | x, y"); } [Fact, WorkItem(529279, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529279")] public void NewCS0029_ImplicitlyUnwrapGenericNullable() { string source = @" public class GenC<T, U> where T : struct, U { public void Test(T t) { /*<bind>*/T? nt = t;/*</bind>*/ U valueUn = nt; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,21): error CS0029: Cannot implicitly convert type 'T?' to 'U' // U valueUn = nt; Diagnostic(ErrorCode.ERR_NoImplicitConv, "nt").WithArguments("T?", "U")); VerifyOperationTreeForTest<LocalDeclarationStatementSyntax>(comp, @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'T? nt = t;') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'T? nt = t') Declarators: IVariableDeclaratorOperation (Symbol: T? nt) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'nt = t') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= t') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: T?, IsImplicit) (Syntax: 't') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IParameterReferenceOperation: t (OperationKind.ParameterReference, Type: T) (Syntax: 't') Initializer: null "); } [Fact, WorkItem(529280, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529280"), WorkItem(546864, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546864")] public void ExplicitUDCWithGenericConstraints() { // This compiles successfully in Dev10 dues to a bug; a user-defined conversion // that converts from or to an interface should never be chosen. If you are // converting from Alpha to Beta via standard conversion, then Beta to Gamma // via user-defined conversion, then Gamma to Delta via standard conversion, then // none of Alpha, Beta, Gamma or Delta should be allowed to be interfaces. The // Dev10 compiler only checks Alpha and Delta, not Beta and Gamma. // // Unfortunately, real-world code both in devdiv and in the wild depends on this // behavior, so we are replicating the bug in Roslyn. string source = @"using System; public interface IGoo { void Method(); } public class CT : IGoo { public void Method() { } } public class GenC<T> where T : IGoo { public T valueT; public static explicit operator T(GenC<T> val) { Console.Write(""ExpConv""); return val.valueT; } } public class Test { public static void Main() { var _class = new GenC<IGoo>(); var ret = (CT)_class; } } "; // CompileAndVerify(source, expectedOutput: "ExpConv"); CreateCompilation(source).VerifyDiagnostics(); } [Fact, WorkItem(529362, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529362")] public void TestNullCoalescingOverImplicitExplicitUDC() { string source = @"using System; struct GenS<T> where T : struct { public static int Flag; public static explicit operator T?(GenS<T> s) { Flag = 3; return default(T); } public static implicit operator T(GenS<T> s) { Flag = 2; return default(T); } } class Program { public static void Main() { int? int_a1 = 1; GenS<int>? s28 = new GenS<int>(); // Due to related bug dev10: 742047 is won't fix // so expects the code will call explicit conversion operator int? result28 = s28 ?? int_a1; Console.WriteLine(GenS<int>.Flag); } } "; // Native compiler picks explicit conversion - print 3 CompileAndVerify(source, expectedOutput: "2"); } [Fact, WorkItem(529362, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529362")] public void TestNullCoalescingOverImplicitExplicitUDC_2() { string source = @"using System; struct S { public static explicit operator int?(S? s) { Console.WriteLine(""Explicit""); return 3; } public static implicit operator int(S? s) { Console.WriteLine(""Implicit""); return 2; } } class Program { public static void Main() { int? nn = -1; S? s = new S(); int? ret = s ?? nn; } } "; // Native compiler picks explicit conversion CompileAndVerify(source, expectedOutput: "Implicit"); } [Fact, WorkItem(529363, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529363")] public void AssignmentNullCoalescingOperator() { string source = @"using System; class NullCoalescingTest { public static void Main() { int? a; int c; var x = (a = null) ?? (c = 123); Console.WriteLine(c); } } "; // Native compiler no error (print -123) CreateCompilation(source).VerifyDiagnostics( // (10,27): error CS0165: Use of unassigned local variable 'c' // Console.WriteLine(c); Diagnostic(ErrorCode.ERR_UseDefViolation, "c").WithArguments("c"), // (7,14): warning CS0219: The variable 'a' is assigned but its value is never used // int? a; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "a").WithArguments("a")); } [Fact, WorkItem(529464, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529464")] public void MultiDimensionArrayWithDiffTypeIndexDevDiv31328() { var text = @" class A { public static void Main() { byte[,] arr = new byte[1, 1]; ulong i1 = 0; int i2 = 1; arr[i1, i2] = 127; // Dev10 CS0266 } } "; // Dev10 Won't fix bug#31328 for md array with different types' index and involving ulong // CS0266: Cannot implicitly convert type 'ulong' to 'int'. ... CreateCompilation(text).VerifyDiagnostics(); } [Fact] public void PointerArithmetic_SubtractNullLiteral() { var text = @" unsafe class C { long M(int* p) { return p - null; //Dev10 reports CS0019 } } "; // Dev10: the null literal is treated as though it is converted to void*, making the subtraction illegal (ExpressionBinder::GetPtrBinOpSigs). // Roslyn: the null literal is converted to int*, making the subtraction legal. CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void CS0181ERR_BadAttributeParamType_Nullable() { var text = @" [Boom] class Boom : System.Attribute { public Boom(int? x = 0) { } static void Main() { typeof(Boom).GetCustomAttributes(true); } } "; // Roslyn: error CS0181: Attribute constructor parameter 'x' has type 'int?', which is not a valid attribute parameter type // Dev10/11: no error, but throw at runtime - System.Reflection.CustomAttributeFormatException CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_BadAttributeParamType, "Boom").WithArguments("x", "int?")); } /// <summary> /// When determining whether the LHS of a null-coalescing operator (??) is non-null, the native compiler strips off casts. /// /// We have decided not to reproduce this behavior. /// </summary> [Fact] public void CastOnLhsOfConditionalOperator() { var text = @" class C { static void Main(string[] args) { int i; int? j = (int?)1 ?? i; //dev10 accepts, since it treats the RHS as unreachable. int k; int? l = ((int?)1 ?? j) ?? k; // If the LHS of the LHS is non-null, then the LHS should be non-null, but dev10 only handles casts. int m; int? n = ((int?)1).HasValue ? ((int?)1).Value : m; //dev10 does not strip casts in a comparable conditional operator } } "; // Roslyn: error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('object') // Dev10/11: no error CreateCompilation(text).VerifyDiagnostics( // This is new in Roslyn. // (7,29): error CS0165: Use of unassigned local variable 'i' // int? j = (int?)1 ?? i; //dev10 accepts, since it treats the RHS as unreachable. Diagnostic(ErrorCode.ERR_UseDefViolation, "i").WithArguments("i"), // These match Dev10. // (10,36): error CS0165: Use of unassigned local variable 'k' // int? l = ((int?)1 ?? j) ?? k; // If the LHS of the LHS is non-null, then the LHS should be non-null, but dev10 only handles casts. Diagnostic(ErrorCode.ERR_UseDefViolation, "k").WithArguments("k"), // (13,57): error CS0165: Use of unassigned local variable 'm' // int? n = ((int?)1).HasValue ? ((int?)1).Value : m; //dev10 does not strip casts in a comparable conditional operator Diagnostic(ErrorCode.ERR_UseDefViolation, "m").WithArguments("m")); } [WorkItem(529974, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529974")] [Fact] public void TestCollisionForLoopControlVariable() { var source = @" namespace Microsoft.Test.XmlGen.Protocols.Saml2 { using System; using System.Collections.Generic; public class ProxyRestriction { XmlGenIntegerAttribute count; private List<XmlGenAttribute> Attributes { get; set; } public ProxyRestriction() { for (int count = 0; count < 10; count++) { } for (int i = 0; i < this.Attributes.Count; i++) { XmlGenAttribute attribute = this.Attributes[i]; if (attribute.LocalName == null) { if (count is XmlGenIntegerAttribute) { count = (XmlGenIntegerAttribute)attribute; } else { count = new XmlGenIntegerAttribute(attribute); this.Attributes[i] = count; } break; } } if (count == null) { this.Attributes.Add(new XmlGenIntegerAttribute(String.Empty, null, String.Empty, -1, false)); } } } internal class XmlGenAttribute { public object LocalName { get; internal set; } } internal class XmlGenIntegerAttribute : XmlGenAttribute { public XmlGenIntegerAttribute(string empty1, object count, string empty2, int v, bool isPresent) { } public XmlGenIntegerAttribute(XmlGenAttribute attribute) { } } } public class Program { public static void Main() { } }"; // Dev11 reported no errors for the above repro and allowed the name 'count' to bind to different // variables within the same declaration space. According to the old spec the error should be reported. // In Roslyn the single definition rule is relaxed and we do not give an error, but for a different reason. CreateCompilation(source).VerifyDiagnostics(); } [Fact, WorkItem(530301, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530301")] public void NoMore_CS0458WRN_AlwaysNull02() { CreateCompilation( @" public class Test { const bool ct = true; public static int Main() { var a = (true & null) ?? null; // CS0458 if (((null & true) == null)) // CS0458 return 0; var b = !(null | false); // CS0458 if ((false | null) != null) // CS0458 return 1; const bool cf = false; var d = ct & null ^ null; // CS0458 - Roslyn Warn this ONLY d ^= !(null | cf); // CS0458 return -1; } } ") // We decided to not report WRN_AlwaysNull in some cases. .VerifyDiagnostics( // Diagnostic(ErrorCode.WRN_AlwaysNull, "true & null").WithArguments("bool?"), // Diagnostic(ErrorCode.WRN_AlwaysNull, "null & true").WithArguments("bool?"), // Diagnostic(ErrorCode.WRN_AlwaysNull, "null | false").WithArguments("bool?"), // Diagnostic(ErrorCode.WRN_AlwaysNull, "false | null").WithArguments("bool?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "ct & null ^ null").WithArguments("bool?") //, // Diagnostic(ErrorCode.WRN_AlwaysNull, "null | cf").WithArguments("bool?") ); } [WorkItem(530403, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530403")] [Fact] public void CS0135_local_param_cannot_be_declared() { // Dev11 missed this error. The issue is that an a is a field of c, and then it is a local in parts of d. // by then referring to the field without the this keyword, it should be flagged as declaring a competing variable (as it is confusing). var text = @" using System; public class c { int a = 0; void d(bool b) { if(b) { int a = 1; Console.WriteLine(a); } else { a = 2; } a = 3; Console.WriteLine(a); } } "; var comp = CreateCompilation(text); // In Roslyn the single definition rule is relaxed and we do not give an error. comp.VerifyDiagnostics(); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30160")] [WorkItem(530518, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530518")] public void ExpressionTreeExplicitOpVsConvert() { var text = @" using System; using System.Linq; using System.Linq.Expressions; class Test { public static explicit operator int(Test x) { return 1; } static void Main() { Expression<Func<Test, long?>> testExpr1 = x => (long?)x; Console.WriteLine(testExpr1); Expression<Func<Test, decimal?>> testExpr2 = x => (decimal?)x; Console.WriteLine(testExpr2); } } "; // Native Compiler: x => Convert(Convert(op_Explicit(x))) CompileAndVerify(text, expectedOutput: @"x => Convert(Convert(Convert(x))) x => Convert(Convert(Convert(x))) "); } [WorkItem(530531, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530531")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30160")] private void ExpressionTreeNoCovertForIdentityConversion() { var source = @" using System; using System.Linq; using System.Linq.Expressions; class Test { static void Main() { Expression<Func<Guid, bool>> e = (x) => x != null; Console.WriteLine(e); Console.WriteLine(e.Compile()(default(Guid))); } } "; // Native compiler: x => (Convert(x) != Convert(null)) CompileAndVerify(source, expectedOutput: @"x => (Convert(x) != null) True "); } [Fact, WorkItem(530548, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530548")] public void CS0219WRN_UnreferencedVarAssg_RHSMidRefType() { string source = @" public interface Base { } public struct Derived : Base { } public class Test { public static void Main() { var b1 = new Derived(); // Both Warning CS0219 var b2 = (Base)new Derived(); // Both NO Warn (reference type) var b3 = (Derived)((Base)new Derived()); // Roslyn Warning CS0219 } } "; // Native compiler no error (print -123) CreateCompilation(source).VerifyDiagnostics( // (8,13): warning CS0219: The variable 'b1' is assigned but its value is never used // var b1 = new Derived(); // Both Warning CS0219 Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "b1").WithArguments("b1"), // (10,13): warning CS0219: The variable 'b3' is assigned but its value is never used // var b3 = (Derived)((Base)new Derived()); // Roslyn Warning CS0219 Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "b3").WithArguments("b3")); } [Fact, WorkItem(530556, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530556")] public void NoCS0591ERR_InvalidAttributeArgument() { string source = @" using System; [AttributeUsage(AttributeTargets.All + 0xFFFFFF)] class MyAtt : Attribute { } [AttributeUsage((AttributeTargets)0xffff)] class MyAtt1 : Attribute { } public class Test {} "; // Native compiler error CS0591: Invalid value for argument to 'AttributeUsage' attribute CreateCompilation(source).VerifyDiagnostics(); } [Fact, WorkItem(530586, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530586")] public void ThrowOnceInIteratorFinallyBlock() { string source = @" //<Title> Finally block runs twice in iterator</Title> //<RelatedBug>Dev10:473561-->8444?</RelatedBug> using System; using System.Collections; class Program { public static void Main() { var demo = new test(); try { foreach (var x in demo.Goo()) { } } catch (Exception) { Console.Write(""EX ""); } Console.WriteLine(demo.count); } class test { public int count = 0; public IEnumerable Goo() { try { yield return null; try { yield break; } catch { } } finally { Console.Write(""++ ""); ++count; throw new Exception(); } } } } "; // Native print "++ ++ EX 2" var verifier = CompileAndVerify(source, expectedOutput: " ++ EX 1"); // must not load "<>4__this" verifier.VerifyIL("Program.test.<Goo>d__1.System.Collections.IEnumerator.MoveNext()", @" { // Code size 101 (0x65) .maxstack 2 .locals init (bool V_0, int V_1) .try { IL_0000: ldarg.0 IL_0001: ldfld ""int Program.test.<Goo>d__1.<>1__state"" IL_0006: stloc.1 IL_0007: ldloc.1 IL_0008: brfalse.s IL_0012 IL_000a: ldloc.1 IL_000b: ldc.i4.1 IL_000c: beq.s IL_0033 IL_000e: ldc.i4.0 IL_000f: stloc.0 IL_0010: leave.s IL_0063 IL_0012: ldarg.0 IL_0013: ldc.i4.m1 IL_0014: stfld ""int Program.test.<Goo>d__1.<>1__state"" IL_0019: ldarg.0 IL_001a: ldc.i4.s -3 IL_001c: stfld ""int Program.test.<Goo>d__1.<>1__state"" IL_0021: ldarg.0 IL_0022: ldnull IL_0023: stfld ""object Program.test.<Goo>d__1.<>2__current"" IL_0028: ldarg.0 IL_0029: ldc.i4.1 IL_002a: stfld ""int Program.test.<Goo>d__1.<>1__state"" IL_002f: ldc.i4.1 IL_0030: stloc.0 IL_0031: leave.s IL_0063 IL_0033: ldarg.0 IL_0034: ldc.i4.s -3 IL_0036: stfld ""int Program.test.<Goo>d__1.<>1__state"" .try { IL_003b: ldc.i4.0 IL_003c: stloc.0 IL_003d: leave.s IL_004a } catch object { IL_003f: pop IL_0040: leave.s IL_0042 } IL_0042: ldarg.0 IL_0043: call ""void Program.test.<Goo>d__1.<>m__Finally1()"" IL_0048: br.s IL_0052 IL_004a: ldarg.0 IL_004b: call ""void Program.test.<Goo>d__1.<>m__Finally1()"" IL_0050: leave.s IL_0063 IL_0052: leave.s IL_005b } fault { IL_0054: ldarg.0 IL_0055: call ""void Program.test.<Goo>d__1.Dispose()"" IL_005a: endfinally } IL_005b: ldarg.0 IL_005c: call ""void Program.test.<Goo>d__1.Dispose()"" IL_0061: ldc.i4.1 IL_0062: stloc.0 IL_0063: ldloc.0 IL_0064: ret } "); // must load "<>4__this" verifier.VerifyIL("Program.test.<Goo>d__1.<>m__Finally1()", @" { // Code size 42 (0x2a) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldc.i4.m1 IL_0002: stfld ""int Program.test.<Goo>d__1.<>1__state"" IL_0007: ldarg.0 IL_0008: ldfld ""Program.test Program.test.<Goo>d__1.<>4__this"" IL_000d: ldstr ""++ "" IL_0012: call ""void System.Console.Write(string)"" IL_0017: dup IL_0018: ldfld ""int Program.test.count"" IL_001d: ldc.i4.1 IL_001e: add IL_001f: stfld ""int Program.test.count"" IL_0024: newobj ""System.Exception..ctor()"" IL_0029: throw } "); } [Fact, WorkItem(530587, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530587")] public void NoFormatCharInIDEqual() { string source = @" #define A using System; class Program { static int Main() { int x = 0; #if A == A\uFFFB x=1; #endif Console.Write(x); return x; } } "; CompileAndVerify(source, expectedOutput: "1"); // Native print 0 } [Fact, WorkItem(530614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530614")] public void CS1718WRN_ComparisonToSelf_Roslyn() { string source = @" enum esbyte : sbyte { e0, e1 }; public class z_1495j12 { public static void Main() { if (esbyte.e0 == esbyte.e0) { System.Console.WriteLine(""T""); } }} "; // Native compiler no warn CreateCompilation(source).VerifyDiagnostics( // (7,5): warning CS1718: Comparison made to same variable; did you mean to compare something else? Diagnostic(ErrorCode.WRN_ComparisonToSelf, "esbyte.e0 == esbyte.e0")); } [Fact, WorkItem(530629, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530629")] public void CS0414WRN_UnreferencedFieldAssg_Roslyn() { string source = @" namespace VS7_336319 { public sealed class PredefinedTypes { public class Kind { public static int Decimal; } } public class ExpressionBinder { private static PredefinedTypes PredefinedTypes = null; private void Goo() { if (0 == (int)PredefinedTypes.Kind.Decimal) { } } } } "; // Native compiler no warn CreateCompilation(source).VerifyDiagnostics( // (10,40): warning CS0414: The field 'VS7_336319.ExpressionBinder.PredefinedTypes' is assigned but its value is never used // private static PredefinedTypes PredefinedTypes = null; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "PredefinedTypes").WithArguments("VS7_336319.ExpressionBinder.PredefinedTypes")); } [WorkItem(530666, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530666")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30160")] public void ExpressionTreeWithNullableUDCandOperator() { string source = @" using System; using System.Linq.Expressions; struct B { public static implicit operator int?(B x) { return 1; } public static int operator +(B x, int y) { return 2 + y; } static int Main() { Expression<Func<B, int?>> f = x => x + x; var ret = f.Compile()(new B()); Console.WriteLine(ret); return ret.Value - 3; } } "; // Native compiler throw CompileAndVerify(source, expectedOutput: "3"); } [Fact, WorkItem(530696, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530696")] public void CS0121Err_AmbiguousMethodCall() { string source = @" class G<T> { } class C { static void M(params double[] x) { System.Console.WriteLine(1); } static void M(params G<int>[] x) { System.Console.WriteLine(2); } static void Main() { M(); } } "; CreateCompilation(source).VerifyDiagnostics( // (15,13): error CS0121: The call is ambiguous between the following methods or properties: 'C.M(params double[])' and 'C.M(params G<int>[])' // M(); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C.M(params double[])", "C.M(params G<int>[])")); } [Fact, WorkItem(530653, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530653")] public void RepeatedObsoleteWarnings() { // <quote source="Srivatsn's comments from bug 16642"> // Inside a method body if you access a static field twice thus: // // var x = ObsoleteType.field1; // var y = ObsoleteType.field1; // // then the native compiler reports ObsoleteType as obsolete only once. This is because the native compiler caches // the lookup of type names for certain cases and doesn't report errors on the second lookup as that just comes // from the cache. Note how I said caches sometimes. If you simply say - // // var x= new ObsoleteType(); // var y = new ObsoleteType(); // // Then the native compiler reports the error twice. I don't think we should replicate this in Roslyn. Note however // that this is a breaking change because if the first line had been #pragma disabled, then the code would compile // without warnings in Dev11 but we will report warnings. I think it's a corner enough scenario and the native // behavior is quirky enough to warrant a break. // </quote> CompileAndVerify(@" using System; [Obsolete] public class ObsoleteType { public static readonly int field = 0; } public class Program { public static void Main() { #pragma warning disable 0612 var x = ObsoleteType.field; #pragma warning restore 0612 var y = ObsoleteType.field; // In Dev11, this line doesn't produce a warning. } }").VerifyDiagnostics( // (15,17): warning CS0612: 'ObsoleteType' is obsolete // var y = ObsoleteType.field; Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "ObsoleteType").WithArguments("ObsoleteType")); } [Fact, WorkItem(530303, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530303")] public void TestReferenceResolution() { var cs1Compilation = CreateCSharpCompilation("CS1", @"public class CS1 {}", compilationOptions: TestOptions.ReleaseDll); var cs1Verifier = CompileAndVerify(cs1Compilation); cs1Verifier.VerifyDiagnostics(); var cs2Compilation = CreateCSharpCompilation("CS2", @"public class CS2<T> {}", compilationOptions: TestOptions.ReleaseDll, referencedCompilations: new Compilation[] { cs1Compilation }); var cs2Verifier = CompileAndVerify(cs2Compilation); cs2Verifier.VerifyDiagnostics(); var cs3Compilation = CreateCSharpCompilation("CS3", @"public class CS3 : CS2<CS1> {}", compilationOptions: TestOptions.ReleaseDll, referencedCompilations: new Compilation[] { cs1Compilation, cs2Compilation }); var cs3Verifier = CompileAndVerify(cs3Compilation); cs3Verifier.VerifyDiagnostics(); var cs4Compilation = CreateCSharpCompilation("CS4", @"public class Program { static void Main() { System.Console.WriteLine(typeof(CS3)); } }", compilationOptions: TestOptions.ReleaseExe, referencedCompilations: new Compilation[] { cs2Compilation, cs3Compilation }); cs4Compilation.VerifyDiagnostics(); } [Fact, WorkItem(531014, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531014")] public void TestVariableAndTypeNameClashes() { CompileAndVerify(@" using System; public class Class1 { internal class A4 { internal class B { } internal static string F() { return ""A4""; } } internal class A5 { internal class B { } internal static string F() { return ""A5""; } } internal class A6 { internal class B { } internal static string F() { return ""A6""; } } internal delegate void D(); // Check the weird E.M cases. internal class Outer2 { internal static void F(A4 A4) { A5 A5; const A6 A6 = null; Console.WriteLine(typeof(A4.B)); Console.WriteLine(typeof(A5.B)); Console.WriteLine(typeof(A6.B)); Console.WriteLine(A4.F()); Console.WriteLine(A5.F()); Console.WriteLine(A6.F()); Console.WriteLine(default(A4) == null); Console.WriteLine(default(A5) == null); Console.WriteLine(default(A6) == null); } } }").VerifyDiagnostics( // Breaking Change: See bug 17395. Dev11 had a bug because of which it didn't report the below warnings. // (13,16): warning CS0168: The variable 'A5' is declared but never used // A5 A5; const A6 A6 = null; Diagnostic(ErrorCode.WRN_UnreferencedVar, "A5").WithArguments("A5"), // (13,29): warning CS0219: The variable 'A6' is assigned but its value is never used // A5 A5; const A6 A6 = null; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "A6").WithArguments("A6")); } [WorkItem(530584, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530584")] [Fact] public void NotRuntimeAmbiguousBecauseOfReturnTypes() { var source = @" using System; class Base<T, S> { public virtual int Goo(ref S x) { return 0; } public virtual string Goo(out T x) { x = default(T); return ""Base.Out""; } } class Derived : Base<int, int> { public override string Goo(out int x) { x = 0; return ""Derived.Out""; } static void Main() { int x; Console.WriteLine(new Derived().Goo(out x)); } } "; // BREAK: Dev11 reports WRN_MultipleRuntimeOverrideMatches, but there // is no runtime ambiguity because the return types differ. CompileAndVerify(source, expectedOutput: "Derived.Out"); } [WorkItem(695311, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/695311")] [Fact] public void NestedCollectionInitializerOnGenericProperty() { var libSource = @" using System.Collections; public interface IAdd { void Add(object o); } public struct S : IEnumerable, IAdd { private ArrayList list; public void Add(object o) { list = list ?? new ArrayList(); list.Add(o); } public IEnumerator GetEnumerator() { return (list ?? new ArrayList()).GetEnumerator(); } } public class C : IEnumerable, IAdd { private readonly ArrayList list = new ArrayList(); public void Add(object o) { list.Add(o); } public IEnumerator GetEnumerator() { return list.GetEnumerator(); } } public class Wrapper<T> : IEnumerable where T : IEnumerable, new() { public Wrapper() { this.Item = new T(); } public T Item { get; private set; } public IEnumerator GetEnumerator() { return Item.GetEnumerator(); } } public static class Util { public static int Count(IEnumerable i) { int count = 0; foreach (var v in i) count++; return count; } } "; var libRef = CreateCompilation(libSource, assemblyName: "lib").EmitToImageReference(); { var source = @" using System; using System.Collections; class Test { static void Main() { Console.Write(Util.Count(Goo<S>())); Console.Write(Util.Count(Goo<C>())); } static Wrapper<T> Goo<T>() where T : IEnumerable, IAdd, new() { return new Wrapper<T> { Item = { 1, 2, 3} }; } } "; // As in dev11. var comp = CreateCompilation(source, new[] { libRef }, TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "03"); } { var source = @" using System; using System.Collections; class Test { static void Main() { Console.Write(Util.Count(Goo<C>())); } static Wrapper<T> Goo<T>() where T : class, IEnumerable, IAdd, new() { return new Wrapper<T> { Item = { 1, 2, 3} }; } } "; // As in dev11. // NOTE: The spec will likely be updated to make this illegal. var comp = CreateCompilation(source, new[] { libRef }, TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "3"); } { var source = @" using System; using System.Collections; class Test { static void Main() { Console.Write(Util.Count(Goo<S>())); } static Wrapper<T> Goo<T>() where T : struct, IEnumerable, IAdd { return new Wrapper<T> { Item = { 1, 2, 3} }; } } "; // BREAK: dev11 compiles and prints "0" var comp = CreateCompilation(source, new[] { libRef }, TestOptions.ReleaseExe); comp.VerifyDiagnostics( // (15,33): error CS1918: Members of property 'Wrapper<T>.Item' of type 'T' cannot be assigned with an object initializer because it is of a value type // return new Wrapper<T> { Item = { 1, 2, 3} }; Diagnostic(ErrorCode.ERR_ValueTypePropertyInObjectInitializer, "Item").WithArguments("Wrapper<T>.Item", "T")); } } [Fact, WorkItem(770424, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/770424"), WorkItem(1079034, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1079034")] public void UserDefinedShortCircuitingOperators() { var source = @" public class Base { public static bool operator true(Base x) { System.Console.Write(""Base.op_True""); return x != null; } public static bool operator false(Base x) { System.Console.Write(""Base.op_False""); return x == null; } } public class Derived : Base { public static Derived operator&(Derived x, Derived y) { return x; } public static Derived operator|(Derived x, Derived y) { return y; } static void Main() { Derived d = new Derived(); var b = (d && d) || d; } } "; CompileAndVerify(source, expectedOutput: "Base.op_FalseBase.op_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.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class BreakingChanges : CSharpTestBase { [Fact, WorkItem(527050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527050")] [Trait("Feature", "Directives")] public void TestCS1024DefineWithUnicodeInMiddle() { var test = @"#de\u0066in\U00000065 ABC"; // This is now a negative test, this should not be allowed. SyntaxFactory.ParseSyntaxTree(test).GetDiagnostics().Verify(Diagnostic(ErrorCode.ERR_PPDirectiveExpected, @"de\u0066in\U00000065")); } [Fact, WorkItem(527951, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527951")] public void CS0133ERR_NotConstantExpression05() { var text = @" class A { public void Do() { const object o1 = null; const string o2 = (string)o1; // Dev10 reports CS0133 } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (7,22): warning CS0219: The variable 'o2' is assigned but its value is never used // const string o2 = (string)o1; // Dev10 reports CS0133 Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "o2").WithArguments("o2") ); } [WorkItem(527943, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527943")] [Fact] public void CS0146ERR_CircularBase05() { var text = @" interface IFace<T> { } class B : IFace<B.C.D> { public class C { public class D { } } } "; var comp = CreateCompilation(text); // In Dev10, there was an error - ErrorCode.ERR_CircularBase at (4,7) Assert.Equal(0, comp.GetDiagnostics().Count()); } [WorkItem(540371, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540371"), WorkItem(530792, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530792")] [Fact] private void CS0507ERR_CantChangeAccessOnOverride_TestSynthesizedSealedAccessorsInDifferentAssembly() { var source1 = @" using System.Collections.Generic; public class Base<T> { public virtual List<T> Property1 { get { return null; } protected internal set { } } public virtual List<T> Property2 { protected internal get { return null; } set { } } }"; var compilation1 = CreateCompilation(source1); var source2 = @" using System.Collections.Generic; public class Derived : Base<int> { public sealed override List<int> Property1 { get { return null; } } public sealed override List<int> Property2 { set { } } }"; var comp = CreateCompilation(source2, new[] { new CSharpCompilationReference(compilation1) }); comp.VerifyDiagnostics(); // This is not a breaking change - but it is a change in behavior from Dev10 // Dev10 used to report following errors - // Error CS0507: 'Derived.Property1.set': cannot change access modifiers when overriding 'protected' inherited member 'Base<int>.Property1.set' // Error CS0507: 'Derived.Property2.get': cannot change access modifiers when overriding 'protected' inherited member 'Base<int>.Property2.get' // Roslyn makes this case work by synthesizing 'protected' accessors for the missing ones var baseClass = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("Base"); var baseProperty1 = baseClass.GetMember<PropertySymbol>("Property1"); var baseProperty2 = baseClass.GetMember<PropertySymbol>("Property2"); Assert.Equal(Accessibility.Public, baseProperty1.DeclaredAccessibility); Assert.Equal(Accessibility.Public, baseProperty1.GetMethod.DeclaredAccessibility); Assert.Equal(Accessibility.ProtectedOrInternal, baseProperty1.SetMethod.DeclaredAccessibility); Assert.Equal(Accessibility.Public, baseProperty2.DeclaredAccessibility); Assert.Equal(Accessibility.ProtectedOrInternal, baseProperty2.GetMethod.DeclaredAccessibility); Assert.Equal(Accessibility.Public, baseProperty2.SetMethod.DeclaredAccessibility); var derivedClass = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("Derived"); var derivedProperty1 = derivedClass.GetMember<SourcePropertySymbol>("Property1"); var derivedProperty2 = derivedClass.GetMember<SourcePropertySymbol>("Property2"); Assert.Equal(Accessibility.Public, derivedProperty1.DeclaredAccessibility); Assert.Equal(Accessibility.Public, derivedProperty1.GetMethod.DeclaredAccessibility); Assert.Null(derivedProperty1.SetMethod); Assert.Equal(Accessibility.Public, derivedProperty2.DeclaredAccessibility); Assert.Null(derivedProperty2.GetMethod); Assert.Equal(Accessibility.Public, derivedProperty2.SetMethod.DeclaredAccessibility); var derivedProperty1Synthesized = derivedProperty1.SynthesizedSealedAccessorOpt; var derivedProperty2Synthesized = derivedProperty2.SynthesizedSealedAccessorOpt; Assert.Equal(MethodKind.PropertySet, derivedProperty1Synthesized.MethodKind); Assert.Equal(Accessibility.Protected, derivedProperty1Synthesized.DeclaredAccessibility); Assert.Equal(MethodKind.PropertyGet, derivedProperty2Synthesized.MethodKind); Assert.Equal(Accessibility.Protected, derivedProperty2Synthesized.DeclaredAccessibility); } // Confirm that this error no longer exists [Fact] public void CS0609ERR_NameAttributeOnOverride() { var text = @" using System.Runtime.CompilerServices; public class idx { public virtual int this[int iPropIndex] { get { return 0; } set { } } } public class MonthDays : idx { [IndexerName(""MonthInfoIndexer"")] public override int this[int iPropIndex] { get { return 1; } set { } } } "; var compilation = CreateCompilation(text); compilation.VerifyDiagnostics(); var indexer = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("MonthDays").Indexers.Single(); Assert.Equal(Microsoft.CodeAnalysis.WellKnownMemberNames.Indexer, indexer.Name); Assert.Equal("MonthInfoIndexer", indexer.MetadataName); } [WorkItem(527116, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527116")] [Fact] public void RegressWarningInSingleMultiLineMixedXml() { var text = @" /// <summary> /** This is the summary */ /// </summary> class Test { /** <summary> */ /// This is the summary1 /** </summary> */ public int Field = 0; /** <summary> */ /// This is the summary2 /// </summary> string Prop { get; set; } /// <summary> /** This is the summary3 * </summary> */ static int Main() { return new Test().Field; } } "; var tree = Parse(text, options: TestOptions.RegularWithDocumentationComments); Assert.NotNull(tree); Assert.Equal(text, tree.GetCompilationUnitRoot().ToFullString()); // Dev10 allows (no warning) // Roslyn gives Warning CS1570 - "XML Comment has badly formed XML..." Assert.Equal(8, tree.GetDiagnostics().Count()); } [Fact, WorkItem(527093, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527093")] public void NoCS1570ForUndefinedXmlNamespace() { var text = @" /// <xml> xmlns:s=""uuid: BDC6E3F0-6DA3-11d1-A2A3 - 00AA00C14882""> /// <s:inventory> /// </s:inventory> /// </xml> class A { } "; var tree = Parse(text, options: TestOptions.RegularWithDocumentationComments); Assert.NotNull(tree); Assert.Equal(text, tree.GetCompilationUnitRoot().ToFullString()); // Native Warning CS1570 - "XML Comment has badly formed XML..." // Roslyn no Assert.Empty(tree.GetDiagnostics()); } [Fact, WorkItem(541345, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541345")] public void CS0019_TestNullCoalesceWithNullOperandsErrors() { var source = @" class Program { static void Main() { // This is acceptable by the native compiler and treated as a non-constant null literal. // That violates the specification; we now correctly treat this as an error. object a = null ?? null; // The null coalescing operator never produces a compile-time constant even when // the arguments are constants. const object b = null ?? ""ABC""; const string c = ""DEF"" ?? null; const int d = (int?)null ?? 123; // It is legal, though pointless, to use null literals and constants in coalescing // expressions, provided you don't try to make the result a constant. These should // produce no errors: object z = null ?? ""GHI""; string y = ""JKL"" ?? null; int x = (int?)null ?? 456; } } "; CreateCompilation(source).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_BadBinaryOps, "null ?? null").WithArguments("??", "<null>", "<null>"), Diagnostic(ErrorCode.ERR_NotConstantExpression, @"null ?? ""ABC""").WithArguments("b"), Diagnostic(ErrorCode.ERR_NotConstantExpression, @"""DEF"" ?? null").WithArguments("c"), Diagnostic(ErrorCode.ERR_NotConstantExpression, "(int?)null ?? 123").WithArguments("d")); } [Fact, WorkItem(528676, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528676"), WorkItem(528676, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528676")] private // CS0657WRN_AttributeLocationOnBadDeclaration_AfterAttrDeclOrDelegate void CS1730ERR_CantUseAttributeOnInvaildLocation() { var test = @"using System; [AttributeUsage(AttributeTargets.All)] public class Goo : Attribute { public int Name; public Goo(int sName) { Name = sName; } } public delegate void EventHandler(object sender, EventArgs e); [assembly: Goo(5)] public class Test { } "; // In Dev10, this is a warning CS0657 // Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "type") SyntaxFactory.ParseSyntaxTree(test).GetDiagnostics().Verify(Diagnostic(ErrorCode.ERR_GlobalAttributesNotFirst, "assembly")); } [WorkItem(528711, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528711")] [Fact] public void CS9259_StructLayoutCycle() { var text = @"struct S1<T> { S1<S1<T>>.S2 x; struct S2 { static T x; } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (3,18): warning CS0169: The field 'S1<T>.x' is never used // S1<S1<T>>.S2 x; Diagnostic(ErrorCode.WRN_UnreferencedField, "x").WithArguments("S1<T>.x").WithLocation(3, 18), // (6,18): warning CS0169: The field 'S1<T>.S2.x' is never used // static T x; Diagnostic(ErrorCode.WRN_UnreferencedField, "x").WithArguments("S1<T>.S2.x").WithLocation(6, 18) ); } [WorkItem(528094, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528094")] [Fact] public void FormattingUnicodeNotPartOfId() { string source = @" // <Area> Lexical - Unicode Characters</Area> // <Title> // Compiler considers identifiers, which differ only in formatting-character, as different ones; // This is not actually correct behavior but for the time being this is what we expect //</Title> //<RelatedBugs>DDB:133151</RelatedBugs> // <Expects Status=Success></Expects> #define A using System; class Program { static int Main() { int x = 0; #if A == A\uFFFB x=1; #endif Console.Write(x); return x; } } "; // Dev10 print '0' CompileAndVerify(source, expectedOutput: "1"); } [WorkItem(529000, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529000")] [Fact] public void NoCS0121ForSwitchedParamNames_Dev10814222() { string source = @" using System; // Bug Dev10: 814222 resolved as Won't Fix class Test { static void Main() { Console.Write(Bar(x: 1, y: ""T0"")); // Dev10:CS0121 Test01.Main01(); } public static int Bar(int x, string y, params int[] z) { return 1; } public static int Bar(string y, int x) { return 0; } // Roslyn pick this one } class Test01 { public static int Bar<T>(int x, T y, params int[] z) { return 1; } public static int Bar<T>(string y, int x) { return 0; } // Roslyn pick this one public static int Goo<T>(int x, T y) { return 1; } public static int Goo<T>(string y, int x) { return 0; } // Roslyn pick this one public static int AbcDef<T>(int x, T y) { return 0; } // Roslyn pick this one public static int AbcDef<T>(string y, int x, params int[] z) { return 1; } public static void Main01() { Console.Write(Bar<string>(x: 1, y: ""T1"")); // Dev10:CS0121 Console.Write(Goo<string>(x: 1, y: ""T2"")); // Dev10:CS0121 Console.Write(AbcDef<string>(x: 1, y: ""T3"")); // Dev10:CS0121 } } "; CompileAndVerify(source, expectedOutput: "0000"); } [WorkItem(529001, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529001")] [WorkItem(529002, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529002")] [WorkItem(1067, "https://github.com/dotnet/roslyn/issues/1067")] [Fact] public void CS0185ERR_LockNeedsReference_RequireRefType() { var source = @" class C { void M<T, TClass, TStruct>() where TClass : class where TStruct : struct { lock (default(object)) ; lock (default(int)) ; // CS0185 lock (default(T)) {} // new CS0185 - no constraints (Bug#10755) lock (default(TClass)) {} lock (default(TStruct)) {} // new CS0185 - constraints to value type (Bug#10756) lock (null) {} // new CS0185 - null is not an object type } } "; var standardCompilation = CreateCompilation(source); var strictCompilation = CreateCompilation(source, parseOptions: TestOptions.Regular.WithStrictFeature()); standardCompilation.VerifyDiagnostics( // (8,32): warning CS0642: Possible mistaken empty statement // lock (default(object)) ; Diagnostic(ErrorCode.WRN_PossibleMistakenNullStatement, ";").WithLocation(8, 32), // (9,29): warning CS0642: Possible mistaken empty statement // lock (default(int)) ; // CS0185 Diagnostic(ErrorCode.WRN_PossibleMistakenNullStatement, ";").WithLocation(9, 29), // (9,15): error CS0185: 'int' is not a reference type as required by the lock statement // lock (default(int)) ; // CS0185 Diagnostic(ErrorCode.ERR_LockNeedsReference, "default(int)").WithArguments("int").WithLocation(9, 15), // (12,15): error CS0185: 'TStruct' is not a reference type as required by the lock statement // lock (default(TStruct)) {} // new CS0185 - constraints to value type (Bug#10756) Diagnostic(ErrorCode.ERR_LockNeedsReference, "default(TStruct)").WithArguments("TStruct").WithLocation(12, 15) ); strictCompilation.VerifyDiagnostics( // (8,32): warning CS0642: Possible mistaken empty statement // lock (default(object)) ; Diagnostic(ErrorCode.WRN_PossibleMistakenNullStatement, ";").WithLocation(8, 32), // (9,29): warning CS0642: Possible mistaken empty statement // lock (default(int)) ; // CS0185 Diagnostic(ErrorCode.WRN_PossibleMistakenNullStatement, ";").WithLocation(9, 29), // (9,15): error CS0185: 'int' is not a reference type as required by the lock statement // lock (default(int)) ; // CS0185 Diagnostic(ErrorCode.ERR_LockNeedsReference, "default(int)").WithArguments("int").WithLocation(9, 15), // (10,15): error CS0185: 'T' is not a reference type as required by the lock statement // lock (default(T)) {} // new CS0185 - no constraints (Bug#10755) Diagnostic(ErrorCode.ERR_LockNeedsReference, "default(T)").WithArguments("T").WithLocation(10, 15), // (12,15): error CS0185: 'TStruct' is not a reference type as required by the lock statement // lock (default(TStruct)) {} // new CS0185 - constraints to value type (Bug#10756) Diagnostic(ErrorCode.ERR_LockNeedsReference, "default(TStruct)").WithArguments("TStruct").WithLocation(12, 15), // (13,15): error CS0185: '<null>' is not a reference type as required by the lock statement // lock (null) {} // new CS0185 - null is not an object type Diagnostic(ErrorCode.ERR_LockNeedsReference, "null").WithArguments("<null>").WithLocation(13, 15) ); } [WorkItem(528972, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528972")] [Fact] public void CS0121ERR_AmbigCall_Lambda1() { var text = @" using System; class A { static void Main() { Goo( delegate () { throw new Exception(); }); // both Dev10 & Roslyn no error Goo(x: () => { throw new Exception(); }); // Dev10: CS0121, Roslyn: no error } public static void Goo(Action x) { Console.WriteLine(1); } public static void Goo(Func<int> x) { Console.WriteLine(2); // Roslyn call this one } } "; // Dev11 FIXED this, no error anymore (So Not breaking Dev11) // Dev10 reports CS0121 because ExpressionBinder::WhichConversionIsBetter fails to unwrap // the NamedArgumentSpecification to find the UNBOUNDLAMBDA and, thus, never calls // WhichLambdaConversionIsBetter. CreateCompilation(text).VerifyDiagnostics(); } [Fact, WorkItem(529202, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529202")] public void NoCS0029_ErrorOnZeroToEnumToTypeConversion() { string source = @" class Program { static void Main() { S s = 0; } } enum E { Zero, One, Two } struct S { public static implicit operator S(E s) { return E.Zero; } }"; // Dev10/11: (11,9): error CS0029: Cannot implicitly convert type 'int' to 'S' CreateCompilation(source).VerifyDiagnostics( // (6,15): error CS0029: Cannot implicitly convert type 'int' to 'S' // S s = 0; Diagnostic(ErrorCode.ERR_NoImplicitConv, "0").WithArguments("int", "S") ); } [Fact, WorkItem(529242, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529242")] public void ThrowOverflowExceptionForUncheckedCheckedLambda() { string source = @" using System; class Program { static void Main() { Func<int, int> d = checked(delegate(int i) { int max = int.MaxValue; try { int n = max + 1; } catch (OverflowException) { Console.Write(""OV ""); // Roslyn throw } return i; }); var r = unchecked(d(9)); Console.Write(r); } } "; CompileAndVerify(source, expectedOutput: "OV 9"); } [WorkItem(529262, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529262")] [Fact] public void PartialMethod_ParameterAndTypeParameterNames() { var source = @"using System; using System.Reflection; partial class C { static partial void M<T, U>(T x, U y); static partial void M<T1, T2>(T1 y, T2 x) { Console.Write(""{0}, {1} | "", x, y); var m = typeof(C).GetMethod(""M"", BindingFlags.Static | BindingFlags.NonPublic); var tp = m.GetGenericArguments(); Console.Write(""{0}, {1} | "", tp[0].Name, tp[1].Name); var p = m.GetParameters(); Console.Write(""{0}, {1}"", p[0].Name, p[1].Name); } static void Main() { M(x: 1, y: 2); } }"; // Dev12 would emit "2, 1 | T1, T2 | x, y". CompileAndVerify(source, expectedOutput: "2, 1 | T, U | x, y"); } [Fact, WorkItem(529279, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529279")] public void NewCS0029_ImplicitlyUnwrapGenericNullable() { string source = @" public class GenC<T, U> where T : struct, U { public void Test(T t) { /*<bind>*/T? nt = t;/*</bind>*/ U valueUn = nt; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,21): error CS0029: Cannot implicitly convert type 'T?' to 'U' // U valueUn = nt; Diagnostic(ErrorCode.ERR_NoImplicitConv, "nt").WithArguments("T?", "U")); VerifyOperationTreeForTest<LocalDeclarationStatementSyntax>(comp, @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'T? nt = t;') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'T? nt = t') Declarators: IVariableDeclaratorOperation (Symbol: T? nt) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'nt = t') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= t') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: T?, IsImplicit) (Syntax: 't') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IParameterReferenceOperation: t (OperationKind.ParameterReference, Type: T) (Syntax: 't') Initializer: null "); } [Fact, WorkItem(529280, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529280"), WorkItem(546864, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546864")] public void ExplicitUDCWithGenericConstraints() { // This compiles successfully in Dev10 dues to a bug; a user-defined conversion // that converts from or to an interface should never be chosen. If you are // converting from Alpha to Beta via standard conversion, then Beta to Gamma // via user-defined conversion, then Gamma to Delta via standard conversion, then // none of Alpha, Beta, Gamma or Delta should be allowed to be interfaces. The // Dev10 compiler only checks Alpha and Delta, not Beta and Gamma. // // Unfortunately, real-world code both in devdiv and in the wild depends on this // behavior, so we are replicating the bug in Roslyn. string source = @"using System; public interface IGoo { void Method(); } public class CT : IGoo { public void Method() { } } public class GenC<T> where T : IGoo { public T valueT; public static explicit operator T(GenC<T> val) { Console.Write(""ExpConv""); return val.valueT; } } public class Test { public static void Main() { var _class = new GenC<IGoo>(); var ret = (CT)_class; } } "; // CompileAndVerify(source, expectedOutput: "ExpConv"); CreateCompilation(source).VerifyDiagnostics(); } [Fact, WorkItem(529362, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529362")] public void TestNullCoalescingOverImplicitExplicitUDC() { string source = @"using System; struct GenS<T> where T : struct { public static int Flag; public static explicit operator T?(GenS<T> s) { Flag = 3; return default(T); } public static implicit operator T(GenS<T> s) { Flag = 2; return default(T); } } class Program { public static void Main() { int? int_a1 = 1; GenS<int>? s28 = new GenS<int>(); // Due to related bug dev10: 742047 is won't fix // so expects the code will call explicit conversion operator int? result28 = s28 ?? int_a1; Console.WriteLine(GenS<int>.Flag); } } "; // Native compiler picks explicit conversion - print 3 CompileAndVerify(source, expectedOutput: "2"); } [Fact, WorkItem(529362, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529362")] public void TestNullCoalescingOverImplicitExplicitUDC_2() { string source = @"using System; struct S { public static explicit operator int?(S? s) { Console.WriteLine(""Explicit""); return 3; } public static implicit operator int(S? s) { Console.WriteLine(""Implicit""); return 2; } } class Program { public static void Main() { int? nn = -1; S? s = new S(); int? ret = s ?? nn; } } "; // Native compiler picks explicit conversion CompileAndVerify(source, expectedOutput: "Implicit"); } [Fact, WorkItem(529363, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529363")] public void AssignmentNullCoalescingOperator() { string source = @"using System; class NullCoalescingTest { public static void Main() { int? a; int c; var x = (a = null) ?? (c = 123); Console.WriteLine(c); } } "; // Native compiler no error (print -123) CreateCompilation(source).VerifyDiagnostics( // (10,27): error CS0165: Use of unassigned local variable 'c' // Console.WriteLine(c); Diagnostic(ErrorCode.ERR_UseDefViolation, "c").WithArguments("c"), // (7,14): warning CS0219: The variable 'a' is assigned but its value is never used // int? a; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "a").WithArguments("a")); } [Fact, WorkItem(529464, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529464")] public void MultiDimensionArrayWithDiffTypeIndexDevDiv31328() { var text = @" class A { public static void Main() { byte[,] arr = new byte[1, 1]; ulong i1 = 0; int i2 = 1; arr[i1, i2] = 127; // Dev10 CS0266 } } "; // Dev10 Won't fix bug#31328 for md array with different types' index and involving ulong // CS0266: Cannot implicitly convert type 'ulong' to 'int'. ... CreateCompilation(text).VerifyDiagnostics(); } [Fact] public void PointerArithmetic_SubtractNullLiteral() { var text = @" unsafe class C { long M(int* p) { return p - null; //Dev10 reports CS0019 } } "; // Dev10: the null literal is treated as though it is converted to void*, making the subtraction illegal (ExpressionBinder::GetPtrBinOpSigs). // Roslyn: the null literal is converted to int*, making the subtraction legal. CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void CS0181ERR_BadAttributeParamType_Nullable() { var text = @" [Boom] class Boom : System.Attribute { public Boom(int? x = 0) { } static void Main() { typeof(Boom).GetCustomAttributes(true); } } "; // Roslyn: error CS0181: Attribute constructor parameter 'x' has type 'int?', which is not a valid attribute parameter type // Dev10/11: no error, but throw at runtime - System.Reflection.CustomAttributeFormatException CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_BadAttributeParamType, "Boom").WithArguments("x", "int?")); } /// <summary> /// When determining whether the LHS of a null-coalescing operator (??) is non-null, the native compiler strips off casts. /// /// We have decided not to reproduce this behavior. /// </summary> [Fact] public void CastOnLhsOfConditionalOperator() { var text = @" class C { static void Main(string[] args) { int i; int? j = (int?)1 ?? i; //dev10 accepts, since it treats the RHS as unreachable. int k; int? l = ((int?)1 ?? j) ?? k; // If the LHS of the LHS is non-null, then the LHS should be non-null, but dev10 only handles casts. int m; int? n = ((int?)1).HasValue ? ((int?)1).Value : m; //dev10 does not strip casts in a comparable conditional operator } } "; // Roslyn: error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('object') // Dev10/11: no error CreateCompilation(text).VerifyDiagnostics( // This is new in Roslyn. // (7,29): error CS0165: Use of unassigned local variable 'i' // int? j = (int?)1 ?? i; //dev10 accepts, since it treats the RHS as unreachable. Diagnostic(ErrorCode.ERR_UseDefViolation, "i").WithArguments("i"), // These match Dev10. // (10,36): error CS0165: Use of unassigned local variable 'k' // int? l = ((int?)1 ?? j) ?? k; // If the LHS of the LHS is non-null, then the LHS should be non-null, but dev10 only handles casts. Diagnostic(ErrorCode.ERR_UseDefViolation, "k").WithArguments("k"), // (13,57): error CS0165: Use of unassigned local variable 'm' // int? n = ((int?)1).HasValue ? ((int?)1).Value : m; //dev10 does not strip casts in a comparable conditional operator Diagnostic(ErrorCode.ERR_UseDefViolation, "m").WithArguments("m")); } [WorkItem(529974, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529974")] [Fact] public void TestCollisionForLoopControlVariable() { var source = @" namespace Microsoft.Test.XmlGen.Protocols.Saml2 { using System; using System.Collections.Generic; public class ProxyRestriction { XmlGenIntegerAttribute count; private List<XmlGenAttribute> Attributes { get; set; } public ProxyRestriction() { for (int count = 0; count < 10; count++) { } for (int i = 0; i < this.Attributes.Count; i++) { XmlGenAttribute attribute = this.Attributes[i]; if (attribute.LocalName == null) { if (count is XmlGenIntegerAttribute) { count = (XmlGenIntegerAttribute)attribute; } else { count = new XmlGenIntegerAttribute(attribute); this.Attributes[i] = count; } break; } } if (count == null) { this.Attributes.Add(new XmlGenIntegerAttribute(String.Empty, null, String.Empty, -1, false)); } } } internal class XmlGenAttribute { public object LocalName { get; internal set; } } internal class XmlGenIntegerAttribute : XmlGenAttribute { public XmlGenIntegerAttribute(string empty1, object count, string empty2, int v, bool isPresent) { } public XmlGenIntegerAttribute(XmlGenAttribute attribute) { } } } public class Program { public static void Main() { } }"; // Dev11 reported no errors for the above repro and allowed the name 'count' to bind to different // variables within the same declaration space. According to the old spec the error should be reported. // In Roslyn the single definition rule is relaxed and we do not give an error, but for a different reason. CreateCompilation(source).VerifyDiagnostics(); } [Fact, WorkItem(530301, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530301")] public void NoMore_CS0458WRN_AlwaysNull02() { CreateCompilation( @" public class Test { const bool ct = true; public static int Main() { var a = (true & null) ?? null; // CS0458 if (((null & true) == null)) // CS0458 return 0; var b = !(null | false); // CS0458 if ((false | null) != null) // CS0458 return 1; const bool cf = false; var d = ct & null ^ null; // CS0458 - Roslyn Warn this ONLY d ^= !(null | cf); // CS0458 return -1; } } ") // We decided to not report WRN_AlwaysNull in some cases. .VerifyDiagnostics( // Diagnostic(ErrorCode.WRN_AlwaysNull, "true & null").WithArguments("bool?"), // Diagnostic(ErrorCode.WRN_AlwaysNull, "null & true").WithArguments("bool?"), // Diagnostic(ErrorCode.WRN_AlwaysNull, "null | false").WithArguments("bool?"), // Diagnostic(ErrorCode.WRN_AlwaysNull, "false | null").WithArguments("bool?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "ct & null ^ null").WithArguments("bool?") //, // Diagnostic(ErrorCode.WRN_AlwaysNull, "null | cf").WithArguments("bool?") ); } [WorkItem(530403, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530403")] [Fact] public void CS0135_local_param_cannot_be_declared() { // Dev11 missed this error. The issue is that an a is a field of c, and then it is a local in parts of d. // by then referring to the field without the this keyword, it should be flagged as declaring a competing variable (as it is confusing). var text = @" using System; public class c { int a = 0; void d(bool b) { if(b) { int a = 1; Console.WriteLine(a); } else { a = 2; } a = 3; Console.WriteLine(a); } } "; var comp = CreateCompilation(text); // In Roslyn the single definition rule is relaxed and we do not give an error. comp.VerifyDiagnostics(); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30160")] [WorkItem(530518, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530518")] public void ExpressionTreeExplicitOpVsConvert() { var text = @" using System; using System.Linq; using System.Linq.Expressions; class Test { public static explicit operator int(Test x) { return 1; } static void Main() { Expression<Func<Test, long?>> testExpr1 = x => (long?)x; Console.WriteLine(testExpr1); Expression<Func<Test, decimal?>> testExpr2 = x => (decimal?)x; Console.WriteLine(testExpr2); } } "; // Native Compiler: x => Convert(Convert(op_Explicit(x))) CompileAndVerify(text, expectedOutput: @"x => Convert(Convert(Convert(x))) x => Convert(Convert(Convert(x))) "); } [WorkItem(530531, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530531")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30160")] private void ExpressionTreeNoCovertForIdentityConversion() { var source = @" using System; using System.Linq; using System.Linq.Expressions; class Test { static void Main() { Expression<Func<Guid, bool>> e = (x) => x != null; Console.WriteLine(e); Console.WriteLine(e.Compile()(default(Guid))); } } "; // Native compiler: x => (Convert(x) != Convert(null)) CompileAndVerify(source, expectedOutput: @"x => (Convert(x) != null) True "); } [Fact, WorkItem(530548, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530548")] public void CS0219WRN_UnreferencedVarAssg_RHSMidRefType() { string source = @" public interface Base { } public struct Derived : Base { } public class Test { public static void Main() { var b1 = new Derived(); // Both Warning CS0219 var b2 = (Base)new Derived(); // Both NO Warn (reference type) var b3 = (Derived)((Base)new Derived()); // Roslyn Warning CS0219 } } "; // Native compiler no error (print -123) CreateCompilation(source).VerifyDiagnostics( // (8,13): warning CS0219: The variable 'b1' is assigned but its value is never used // var b1 = new Derived(); // Both Warning CS0219 Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "b1").WithArguments("b1"), // (10,13): warning CS0219: The variable 'b3' is assigned but its value is never used // var b3 = (Derived)((Base)new Derived()); // Roslyn Warning CS0219 Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "b3").WithArguments("b3")); } [Fact, WorkItem(530556, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530556")] public void NoCS0591ERR_InvalidAttributeArgument() { string source = @" using System; [AttributeUsage(AttributeTargets.All + 0xFFFFFF)] class MyAtt : Attribute { } [AttributeUsage((AttributeTargets)0xffff)] class MyAtt1 : Attribute { } public class Test {} "; // Native compiler error CS0591: Invalid value for argument to 'AttributeUsage' attribute CreateCompilation(source).VerifyDiagnostics(); } [Fact, WorkItem(530586, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530586")] public void ThrowOnceInIteratorFinallyBlock() { string source = @" //<Title> Finally block runs twice in iterator</Title> //<RelatedBug>Dev10:473561-->8444?</RelatedBug> using System; using System.Collections; class Program { public static void Main() { var demo = new test(); try { foreach (var x in demo.Goo()) { } } catch (Exception) { Console.Write(""EX ""); } Console.WriteLine(demo.count); } class test { public int count = 0; public IEnumerable Goo() { try { yield return null; try { yield break; } catch { } } finally { Console.Write(""++ ""); ++count; throw new Exception(); } } } } "; // Native print "++ ++ EX 2" var verifier = CompileAndVerify(source, expectedOutput: " ++ EX 1"); // must not load "<>4__this" verifier.VerifyIL("Program.test.<Goo>d__1.System.Collections.IEnumerator.MoveNext()", @" { // Code size 101 (0x65) .maxstack 2 .locals init (bool V_0, int V_1) .try { IL_0000: ldarg.0 IL_0001: ldfld ""int Program.test.<Goo>d__1.<>1__state"" IL_0006: stloc.1 IL_0007: ldloc.1 IL_0008: brfalse.s IL_0012 IL_000a: ldloc.1 IL_000b: ldc.i4.1 IL_000c: beq.s IL_0033 IL_000e: ldc.i4.0 IL_000f: stloc.0 IL_0010: leave.s IL_0063 IL_0012: ldarg.0 IL_0013: ldc.i4.m1 IL_0014: stfld ""int Program.test.<Goo>d__1.<>1__state"" IL_0019: ldarg.0 IL_001a: ldc.i4.s -3 IL_001c: stfld ""int Program.test.<Goo>d__1.<>1__state"" IL_0021: ldarg.0 IL_0022: ldnull IL_0023: stfld ""object Program.test.<Goo>d__1.<>2__current"" IL_0028: ldarg.0 IL_0029: ldc.i4.1 IL_002a: stfld ""int Program.test.<Goo>d__1.<>1__state"" IL_002f: ldc.i4.1 IL_0030: stloc.0 IL_0031: leave.s IL_0063 IL_0033: ldarg.0 IL_0034: ldc.i4.s -3 IL_0036: stfld ""int Program.test.<Goo>d__1.<>1__state"" .try { IL_003b: ldc.i4.0 IL_003c: stloc.0 IL_003d: leave.s IL_004a } catch object { IL_003f: pop IL_0040: leave.s IL_0042 } IL_0042: ldarg.0 IL_0043: call ""void Program.test.<Goo>d__1.<>m__Finally1()"" IL_0048: br.s IL_0052 IL_004a: ldarg.0 IL_004b: call ""void Program.test.<Goo>d__1.<>m__Finally1()"" IL_0050: leave.s IL_0063 IL_0052: leave.s IL_005b } fault { IL_0054: ldarg.0 IL_0055: call ""void Program.test.<Goo>d__1.Dispose()"" IL_005a: endfinally } IL_005b: ldarg.0 IL_005c: call ""void Program.test.<Goo>d__1.Dispose()"" IL_0061: ldc.i4.1 IL_0062: stloc.0 IL_0063: ldloc.0 IL_0064: ret } "); // must load "<>4__this" verifier.VerifyIL("Program.test.<Goo>d__1.<>m__Finally1()", @" { // Code size 42 (0x2a) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldc.i4.m1 IL_0002: stfld ""int Program.test.<Goo>d__1.<>1__state"" IL_0007: ldarg.0 IL_0008: ldfld ""Program.test Program.test.<Goo>d__1.<>4__this"" IL_000d: ldstr ""++ "" IL_0012: call ""void System.Console.Write(string)"" IL_0017: dup IL_0018: ldfld ""int Program.test.count"" IL_001d: ldc.i4.1 IL_001e: add IL_001f: stfld ""int Program.test.count"" IL_0024: newobj ""System.Exception..ctor()"" IL_0029: throw } "); } [Fact, WorkItem(530587, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530587")] public void NoFormatCharInIDEqual() { string source = @" #define A using System; class Program { static int Main() { int x = 0; #if A == A\uFFFB x=1; #endif Console.Write(x); return x; } } "; CompileAndVerify(source, expectedOutput: "1"); // Native print 0 } [Fact, WorkItem(530614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530614")] public void CS1718WRN_ComparisonToSelf_Roslyn() { string source = @" enum esbyte : sbyte { e0, e1 }; public class z_1495j12 { public static void Main() { if (esbyte.e0 == esbyte.e0) { System.Console.WriteLine(""T""); } }} "; // Native compiler no warn CreateCompilation(source).VerifyDiagnostics( // (7,5): warning CS1718: Comparison made to same variable; did you mean to compare something else? Diagnostic(ErrorCode.WRN_ComparisonToSelf, "esbyte.e0 == esbyte.e0")); } [Fact, WorkItem(530629, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530629")] public void CS0414WRN_UnreferencedFieldAssg_Roslyn() { string source = @" namespace VS7_336319 { public sealed class PredefinedTypes { public class Kind { public static int Decimal; } } public class ExpressionBinder { private static PredefinedTypes PredefinedTypes = null; private void Goo() { if (0 == (int)PredefinedTypes.Kind.Decimal) { } } } } "; // Native compiler no warn CreateCompilation(source).VerifyDiagnostics( // (10,40): warning CS0414: The field 'VS7_336319.ExpressionBinder.PredefinedTypes' is assigned but its value is never used // private static PredefinedTypes PredefinedTypes = null; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "PredefinedTypes").WithArguments("VS7_336319.ExpressionBinder.PredefinedTypes")); } [WorkItem(530666, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530666")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30160")] public void ExpressionTreeWithNullableUDCandOperator() { string source = @" using System; using System.Linq.Expressions; struct B { public static implicit operator int?(B x) { return 1; } public static int operator +(B x, int y) { return 2 + y; } static int Main() { Expression<Func<B, int?>> f = x => x + x; var ret = f.Compile()(new B()); Console.WriteLine(ret); return ret.Value - 3; } } "; // Native compiler throw CompileAndVerify(source, expectedOutput: "3"); } [Fact, WorkItem(530696, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530696")] public void CS0121Err_AmbiguousMethodCall() { string source = @" class G<T> { } class C { static void M(params double[] x) { System.Console.WriteLine(1); } static void M(params G<int>[] x) { System.Console.WriteLine(2); } static void Main() { M(); } } "; CreateCompilation(source).VerifyDiagnostics( // (15,13): error CS0121: The call is ambiguous between the following methods or properties: 'C.M(params double[])' and 'C.M(params G<int>[])' // M(); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C.M(params double[])", "C.M(params G<int>[])")); } [Fact, WorkItem(530653, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530653")] public void RepeatedObsoleteWarnings() { // <quote source="Srivatsn's comments from bug 16642"> // Inside a method body if you access a static field twice thus: // // var x = ObsoleteType.field1; // var y = ObsoleteType.field1; // // then the native compiler reports ObsoleteType as obsolete only once. This is because the native compiler caches // the lookup of type names for certain cases and doesn't report errors on the second lookup as that just comes // from the cache. Note how I said caches sometimes. If you simply say - // // var x= new ObsoleteType(); // var y = new ObsoleteType(); // // Then the native compiler reports the error twice. I don't think we should replicate this in Roslyn. Note however // that this is a breaking change because if the first line had been #pragma disabled, then the code would compile // without warnings in Dev11 but we will report warnings. I think it's a corner enough scenario and the native // behavior is quirky enough to warrant a break. // </quote> CompileAndVerify(@" using System; [Obsolete] public class ObsoleteType { public static readonly int field = 0; } public class Program { public static void Main() { #pragma warning disable 0612 var x = ObsoleteType.field; #pragma warning restore 0612 var y = ObsoleteType.field; // In Dev11, this line doesn't produce a warning. } }").VerifyDiagnostics( // (15,17): warning CS0612: 'ObsoleteType' is obsolete // var y = ObsoleteType.field; Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "ObsoleteType").WithArguments("ObsoleteType")); } [Fact, WorkItem(530303, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530303")] public void TestReferenceResolution() { var cs1Compilation = CreateCSharpCompilation("CS1", @"public class CS1 {}", compilationOptions: TestOptions.ReleaseDll); var cs1Verifier = CompileAndVerify(cs1Compilation); cs1Verifier.VerifyDiagnostics(); var cs2Compilation = CreateCSharpCompilation("CS2", @"public class CS2<T> {}", compilationOptions: TestOptions.ReleaseDll, referencedCompilations: new Compilation[] { cs1Compilation }); var cs2Verifier = CompileAndVerify(cs2Compilation); cs2Verifier.VerifyDiagnostics(); var cs3Compilation = CreateCSharpCompilation("CS3", @"public class CS3 : CS2<CS1> {}", compilationOptions: TestOptions.ReleaseDll, referencedCompilations: new Compilation[] { cs1Compilation, cs2Compilation }); var cs3Verifier = CompileAndVerify(cs3Compilation); cs3Verifier.VerifyDiagnostics(); var cs4Compilation = CreateCSharpCompilation("CS4", @"public class Program { static void Main() { System.Console.WriteLine(typeof(CS3)); } }", compilationOptions: TestOptions.ReleaseExe, referencedCompilations: new Compilation[] { cs2Compilation, cs3Compilation }); cs4Compilation.VerifyDiagnostics(); } [Fact, WorkItem(531014, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531014")] public void TestVariableAndTypeNameClashes() { CompileAndVerify(@" using System; public class Class1 { internal class A4 { internal class B { } internal static string F() { return ""A4""; } } internal class A5 { internal class B { } internal static string F() { return ""A5""; } } internal class A6 { internal class B { } internal static string F() { return ""A6""; } } internal delegate void D(); // Check the weird E.M cases. internal class Outer2 { internal static void F(A4 A4) { A5 A5; const A6 A6 = null; Console.WriteLine(typeof(A4.B)); Console.WriteLine(typeof(A5.B)); Console.WriteLine(typeof(A6.B)); Console.WriteLine(A4.F()); Console.WriteLine(A5.F()); Console.WriteLine(A6.F()); Console.WriteLine(default(A4) == null); Console.WriteLine(default(A5) == null); Console.WriteLine(default(A6) == null); } } }").VerifyDiagnostics( // Breaking Change: See bug 17395. Dev11 had a bug because of which it didn't report the below warnings. // (13,16): warning CS0168: The variable 'A5' is declared but never used // A5 A5; const A6 A6 = null; Diagnostic(ErrorCode.WRN_UnreferencedVar, "A5").WithArguments("A5"), // (13,29): warning CS0219: The variable 'A6' is assigned but its value is never used // A5 A5; const A6 A6 = null; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "A6").WithArguments("A6")); } [WorkItem(530584, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530584")] [Fact] public void NotRuntimeAmbiguousBecauseOfReturnTypes() { var source = @" using System; class Base<T, S> { public virtual int Goo(ref S x) { return 0; } public virtual string Goo(out T x) { x = default(T); return ""Base.Out""; } } class Derived : Base<int, int> { public override string Goo(out int x) { x = 0; return ""Derived.Out""; } static void Main() { int x; Console.WriteLine(new Derived().Goo(out x)); } } "; // BREAK: Dev11 reports WRN_MultipleRuntimeOverrideMatches, but there // is no runtime ambiguity because the return types differ. CompileAndVerify(source, expectedOutput: "Derived.Out"); } [WorkItem(695311, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/695311")] [Fact] public void NestedCollectionInitializerOnGenericProperty() { var libSource = @" using System.Collections; public interface IAdd { void Add(object o); } public struct S : IEnumerable, IAdd { private ArrayList list; public void Add(object o) { list = list ?? new ArrayList(); list.Add(o); } public IEnumerator GetEnumerator() { return (list ?? new ArrayList()).GetEnumerator(); } } public class C : IEnumerable, IAdd { private readonly ArrayList list = new ArrayList(); public void Add(object o) { list.Add(o); } public IEnumerator GetEnumerator() { return list.GetEnumerator(); } } public class Wrapper<T> : IEnumerable where T : IEnumerable, new() { public Wrapper() { this.Item = new T(); } public T Item { get; private set; } public IEnumerator GetEnumerator() { return Item.GetEnumerator(); } } public static class Util { public static int Count(IEnumerable i) { int count = 0; foreach (var v in i) count++; return count; } } "; var libRef = CreateCompilation(libSource, assemblyName: "lib").EmitToImageReference(); { var source = @" using System; using System.Collections; class Test { static void Main() { Console.Write(Util.Count(Goo<S>())); Console.Write(Util.Count(Goo<C>())); } static Wrapper<T> Goo<T>() where T : IEnumerable, IAdd, new() { return new Wrapper<T> { Item = { 1, 2, 3} }; } } "; // As in dev11. var comp = CreateCompilation(source, new[] { libRef }, TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "03"); } { var source = @" using System; using System.Collections; class Test { static void Main() { Console.Write(Util.Count(Goo<C>())); } static Wrapper<T> Goo<T>() where T : class, IEnumerable, IAdd, new() { return new Wrapper<T> { Item = { 1, 2, 3} }; } } "; // As in dev11. // NOTE: The spec will likely be updated to make this illegal. var comp = CreateCompilation(source, new[] { libRef }, TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "3"); } { var source = @" using System; using System.Collections; class Test { static void Main() { Console.Write(Util.Count(Goo<S>())); } static Wrapper<T> Goo<T>() where T : struct, IEnumerable, IAdd { return new Wrapper<T> { Item = { 1, 2, 3} }; } } "; // BREAK: dev11 compiles and prints "0" var comp = CreateCompilation(source, new[] { libRef }, TestOptions.ReleaseExe); comp.VerifyDiagnostics( // (15,33): error CS1918: Members of property 'Wrapper<T>.Item' of type 'T' cannot be assigned with an object initializer because it is of a value type // return new Wrapper<T> { Item = { 1, 2, 3} }; Diagnostic(ErrorCode.ERR_ValueTypePropertyInObjectInitializer, "Item").WithArguments("Wrapper<T>.Item", "T")); } } [Fact, WorkItem(770424, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/770424"), WorkItem(1079034, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1079034")] public void UserDefinedShortCircuitingOperators() { var source = @" public class Base { public static bool operator true(Base x) { System.Console.Write(""Base.op_True""); return x != null; } public static bool operator false(Base x) { System.Console.Write(""Base.op_False""); return x == null; } } public class Derived : Base { public static Derived operator&(Derived x, Derived y) { return x; } public static Derived operator|(Derived x, Derived y) { return y; } static void Main() { Derived d = new Derived(); var b = (d && d) || d; } } "; CompileAndVerify(source, expectedOutput: "Base.op_FalseBase.op_True"); } } }
-1
dotnet/roslyn
56,419
Fix partial method doc comments
Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
RikkiGibson
"2021-09-15T20:47:39Z"
"2021-09-21T23:49:10Z"
0f60b3e9446f5d0fc14a570998c81a5d6c40cc23
8cda7462843d43d9b72039eede2f4cb43126cac2
Fix partial method doc comments. Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
./src/Compilers/Core/MSBuildTaskTests/MiscTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Linq; using Microsoft.Build.Framework; using Microsoft.CodeAnalysis.BuildTasks; using Xunit; using Moq; using Roslyn.Test.Utilities; using Microsoft.CodeAnalysis.CSharp; using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.BuildTasks.UnitTests { public sealed class MiscTests { /// <summary> /// The build task very deliberately does not depend on any of our shipping binaries. This is to avoid /// potential load conflicts for dependencies when loading custom versions of our task. /// </summary> [Fact] [WorkItem(1183, "https://github.com/Microsoft/msbuild/issues/1183")] public void EnsureDependencies() { var assembly = typeof(ManagedCompiler).Assembly; foreach (var name in assembly.GetReferencedAssemblies()) { var isBadRef = name.Name == typeof(Compilation).Assembly.GetName().Name || name.Name == typeof(CSharpCompilation).Assembly.GetName().Name || name.Name == typeof(ImmutableArray<string>).Assembly.GetName().Name; Assert.False(isBadRef); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Linq; using Microsoft.Build.Framework; using Microsoft.CodeAnalysis.BuildTasks; using Xunit; using Moq; using Roslyn.Test.Utilities; using Microsoft.CodeAnalysis.CSharp; using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.BuildTasks.UnitTests { public sealed class MiscTests { /// <summary> /// The build task very deliberately does not depend on any of our shipping binaries. This is to avoid /// potential load conflicts for dependencies when loading custom versions of our task. /// </summary> [Fact] [WorkItem(1183, "https://github.com/Microsoft/msbuild/issues/1183")] public void EnsureDependencies() { var assembly = typeof(ManagedCompiler).Assembly; foreach (var name in assembly.GetReferencedAssemblies()) { var isBadRef = name.Name == typeof(Compilation).Assembly.GetName().Name || name.Name == typeof(CSharpCompilation).Assembly.GetName().Name || name.Name == typeof(ImmutableArray<string>).Assembly.GetName().Name; Assert.False(isBadRef); } } } }
-1
dotnet/roslyn
56,419
Fix partial method doc comments
Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
RikkiGibson
"2021-09-15T20:47:39Z"
"2021-09-21T23:49:10Z"
0f60b3e9446f5d0fc14a570998c81a5d6c40cc23
8cda7462843d43d9b72039eede2f4cb43126cac2
Fix partial method doc comments. Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
./src/Features/Core/Portable/QuickInfo/QuickInfoSection.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Linq; using System.Threading; namespace Microsoft.CodeAnalysis.QuickInfo { /// <summary> /// Sections are used to make up a <see cref="QuickInfoItem"/>. /// </summary> public sealed class QuickInfoSection { /// <summary> /// The kind of this section. Use <see cref="QuickInfoSectionKinds"/> for the most common kinds. /// </summary> public string Kind { get; } /// <summary> /// The individual tagged parts of this section. /// </summary> public ImmutableArray<TaggedText> TaggedParts { get; } private QuickInfoSection(string? kind, ImmutableArray<TaggedText> taggedParts) { Kind = kind ?? string.Empty; TaggedParts = taggedParts.NullToEmpty(); } /// <summary> /// Creates a new instance of <see cref="QuickInfoSection"/>. /// </summary> /// <param name="kind">The kind of the section. Use <see cref="QuickInfoSectionKinds"/> for the most common kinds.</param> /// <param name="taggedParts">The individual tagged parts of the section.</param> public static QuickInfoSection Create(string? kind, ImmutableArray<TaggedText> taggedParts) => new(kind, taggedParts); private string? _text; /// <summary> /// The text of the section without tags. /// </summary> public string Text { get { if (_text == null) { if (TaggedParts.Length == 0) { _text = string.Empty; } else { Interlocked.CompareExchange(ref _text, string.Concat(TaggedParts.Select(t => t.Text)), null); } } return _text; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Linq; using System.Threading; namespace Microsoft.CodeAnalysis.QuickInfo { /// <summary> /// Sections are used to make up a <see cref="QuickInfoItem"/>. /// </summary> public sealed class QuickInfoSection { /// <summary> /// The kind of this section. Use <see cref="QuickInfoSectionKinds"/> for the most common kinds. /// </summary> public string Kind { get; } /// <summary> /// The individual tagged parts of this section. /// </summary> public ImmutableArray<TaggedText> TaggedParts { get; } private QuickInfoSection(string? kind, ImmutableArray<TaggedText> taggedParts) { Kind = kind ?? string.Empty; TaggedParts = taggedParts.NullToEmpty(); } /// <summary> /// Creates a new instance of <see cref="QuickInfoSection"/>. /// </summary> /// <param name="kind">The kind of the section. Use <see cref="QuickInfoSectionKinds"/> for the most common kinds.</param> /// <param name="taggedParts">The individual tagged parts of the section.</param> public static QuickInfoSection Create(string? kind, ImmutableArray<TaggedText> taggedParts) => new(kind, taggedParts); private string? _text; /// <summary> /// The text of the section without tags. /// </summary> public string Text { get { if (_text == null) { if (TaggedParts.Length == 0) { _text = string.Empty; } else { Interlocked.CompareExchange(ref _text, string.Concat(TaggedParts.Select(t => t.Text)), null); } } return _text; } } } }
-1
dotnet/roslyn
56,419
Fix partial method doc comments
Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
RikkiGibson
"2021-09-15T20:47:39Z"
"2021-09-21T23:49:10Z"
0f60b3e9446f5d0fc14a570998c81a5d6c40cc23
8cda7462843d43d9b72039eede2f4cb43126cac2
Fix partial method doc comments. Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
./src/Workspaces/Core/Portable/PatternMatching/PatternMatcher.TextChunk.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Shared.Collections; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.PatternMatching { internal partial class PatternMatcher { /// <summary> /// Information about a chunk of text from the pattern. The chunk is a piece of text, with /// cached information about the character spans within in. Character spans separate out /// capitalized runs and lowercase runs. i.e. if you have AAbb, then there will be two /// character spans, one for AA and one for BB. /// </summary> [NonCopyable] private struct TextChunk : IDisposable { public readonly string Text; /// <summary> /// Character spans separate out /// capitalized runs and lowercase runs. i.e. if you have AAbb, then there will be two /// character spans, one for AA and one for BB. /// </summary> public TemporaryArray<TextSpan> PatternHumps; public readonly WordSimilarityChecker SimilarityChecker; public readonly bool IsLowercase; public TextChunk(string text, bool allowFuzzingMatching) { this.Text = text; PatternHumps = TemporaryArray<TextSpan>.Empty; StringBreaker.AddCharacterParts(text, ref PatternHumps); this.SimilarityChecker = allowFuzzingMatching ? WordSimilarityChecker.Allocate(text, substringsAreSimilar: false) : null; IsLowercase = !ContainsUpperCaseLetter(text); } public void Dispose() { this.PatternHumps.Dispose(); this.SimilarityChecker?.Free(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Shared.Collections; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.PatternMatching { internal partial class PatternMatcher { /// <summary> /// Information about a chunk of text from the pattern. The chunk is a piece of text, with /// cached information about the character spans within in. Character spans separate out /// capitalized runs and lowercase runs. i.e. if you have AAbb, then there will be two /// character spans, one for AA and one for BB. /// </summary> [NonCopyable] private struct TextChunk : IDisposable { public readonly string Text; /// <summary> /// Character spans separate out /// capitalized runs and lowercase runs. i.e. if you have AAbb, then there will be two /// character spans, one for AA and one for BB. /// </summary> public TemporaryArray<TextSpan> PatternHumps; public readonly WordSimilarityChecker SimilarityChecker; public readonly bool IsLowercase; public TextChunk(string text, bool allowFuzzingMatching) { this.Text = text; PatternHumps = TemporaryArray<TextSpan>.Empty; StringBreaker.AddCharacterParts(text, ref PatternHumps); this.SimilarityChecker = allowFuzzingMatching ? WordSimilarityChecker.Allocate(text, substringsAreSimilar: false) : null; IsLowercase = !ContainsUpperCaseLetter(text); } public void Dispose() { this.PatternHumps.Dispose(); this.SimilarityChecker?.Free(); } } } }
-1
dotnet/roslyn
56,419
Fix partial method doc comments
Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
RikkiGibson
"2021-09-15T20:47:39Z"
"2021-09-21T23:49:10Z"
0f60b3e9446f5d0fc14a570998c81a5d6c40cc23
8cda7462843d43d9b72039eede2f4cb43126cac2
Fix partial method doc comments. Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/Matcher.SequenceMatcher.cs
// Licensed to the .NET Foundation under one or more agreements. // 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; namespace Microsoft.CodeAnalysis.Shared.Utilities { internal partial class Matcher<T> { private class SequenceMatcher : Matcher<T> { private readonly Matcher<T>[] _matchers; public SequenceMatcher(params Matcher<T>[] matchers) => _matchers = matchers; public override bool TryMatch(IList<T> sequence, ref int index) { var currentIndex = index; foreach (var matcher in _matchers) { if (!matcher.TryMatch(sequence, ref currentIndex)) { return false; } } index = currentIndex; return true; } public override string ToString() => string.Format("({0})", string.Join(",", (object[])_matchers)); } } }
// Licensed to the .NET Foundation under one or more agreements. // 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; namespace Microsoft.CodeAnalysis.Shared.Utilities { internal partial class Matcher<T> { private class SequenceMatcher : Matcher<T> { private readonly Matcher<T>[] _matchers; public SequenceMatcher(params Matcher<T>[] matchers) => _matchers = matchers; public override bool TryMatch(IList<T> sequence, ref int index) { var currentIndex = index; foreach (var matcher in _matchers) { if (!matcher.TryMatch(sequence, ref currentIndex)) { return false; } } index = currentIndex; return true; } public override string ToString() => string.Format("({0})", string.Join(",", (object[])_matchers)); } } }
-1
dotnet/roslyn
56,419
Fix partial method doc comments
Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
RikkiGibson
"2021-09-15T20:47:39Z"
"2021-09-21T23:49:10Z"
0f60b3e9446f5d0fc14a570998c81a5d6c40cc23
8cda7462843d43d9b72039eede2f4cb43126cac2
Fix partial method doc comments. Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
./src/Compilers/CSharp/Portable/Binder/WithLambdaParametersBinder.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal class WithLambdaParametersBinder : LocalScopeBinder { protected readonly LambdaSymbol lambdaSymbol; protected readonly MultiDictionary<string, ParameterSymbol> parameterMap; private readonly SmallDictionary<string, ParameterSymbol> _definitionMap; public WithLambdaParametersBinder(LambdaSymbol lambdaSymbol, Binder enclosing) : base(enclosing) { this.lambdaSymbol = lambdaSymbol; this.parameterMap = new MultiDictionary<string, ParameterSymbol>(); var parameters = lambdaSymbol.Parameters; if (!parameters.IsDefaultOrEmpty) { _definitionMap = new SmallDictionary<string, ParameterSymbol>(); foreach (var parameter in parameters) { if (!parameter.IsDiscard) { var name = parameter.Name; this.parameterMap.Add(name, parameter); if (!_definitionMap.ContainsKey(name)) { _definitionMap.Add(name, parameter); } } } } } protected override TypeSymbol GetCurrentReturnType(out RefKind refKind) { refKind = lambdaSymbol.RefKind; return lambdaSymbol.ReturnType; } internal override Symbol ContainingMemberOrLambda { get { return this.lambdaSymbol; } } internal override bool IsNestedFunctionBinder => true; internal override bool IsDirectlyInIterator { get { return false; } } // NOTE: Specifically not overriding IsIndirectlyInIterator. internal override TypeWithAnnotations GetIteratorElementType() { return TypeWithAnnotations.Create(CreateErrorType()); } protected override void ValidateYield(YieldStatementSyntax node, BindingDiagnosticBag diagnostics) { if (node != null) { diagnostics.Add(ErrorCode.ERR_YieldInAnonMeth, node.YieldKeyword.GetLocation()); } } internal override void LookupSymbolsInSingleBinder( LookupResult result, string name, int arity, ConsList<TypeSymbol> basesBeingResolved, LookupOptions options, Binder originalBinder, bool diagnose, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(result.IsClear); if ((options & LookupOptions.NamespaceAliasesOnly) != 0) { return; } foreach (var parameterSymbol in parameterMap[name]) { result.MergeEqual(originalBinder.CheckViability(parameterSymbol, arity, options, null, diagnose, ref useSiteInfo)); } } protected override void AddLookupSymbolsInfoInSingleBinder(LookupSymbolsInfo result, LookupOptions options, Binder originalBinder) { if (options.CanConsiderMembers()) { foreach (var parameter in lambdaSymbol.Parameters) { if (originalBinder.CanAddLookupSymbolInfo(parameter, options, result, null)) { result.AddSymbol(parameter, parameter.Name, 0); } } } } private static bool ReportConflictWithParameter(ParameterSymbol parameter, Symbol newSymbol, string name, Location newLocation, BindingDiagnosticBag diagnostics) { var oldLocation = parameter.Locations[0]; if (oldLocation == newLocation) { // a query variable and its corresponding lambda parameter, for example return false; } // Quirk of the way we represent lambda parameters. SymbolKind newSymbolKind = (object)newSymbol == null ? SymbolKind.Parameter : newSymbol.Kind; switch (newSymbolKind) { case SymbolKind.ErrorType: return true; case SymbolKind.Parameter: case SymbolKind.Local: // Error: A local or parameter named '{0}' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter diagnostics.Add(ErrorCode.ERR_LocalIllegallyOverrides, newLocation, name); return true; case SymbolKind.Method: // Local function declaration name conflicts are not reported, for backwards compatibility. return false; case SymbolKind.TypeParameter: // Type parameter declaration name conflicts are not reported, for backwards compatibility. return false; case SymbolKind.RangeVariable: // The range variable '{0}' conflicts with a previous declaration of '{0}' diagnostics.Add(ErrorCode.ERR_QueryRangeVariableOverrides, newLocation, name); return true; } Debug.Assert(false, "what else could be defined in a lambda?"); diagnostics.Add(ErrorCode.ERR_InternalError, newLocation); return false; } internal override bool EnsureSingleDefinition(Symbol symbol, string name, Location location, BindingDiagnosticBag diagnostics) { ParameterSymbol existingDeclaration; var map = _definitionMap; if (map != null && map.TryGetValue(name, out existingDeclaration)) { return ReportConflictWithParameter(existingDeclaration, symbol, name, location, diagnostics); } return false; } internal override ImmutableArray<LocalSymbol> GetDeclaredLocalsForScope(SyntaxNode scopeDesignator) { throw ExceptionUtilities.Unreachable; } internal override ImmutableArray<LocalFunctionSymbol> GetDeclaredLocalFunctionsForScope(CSharpSyntaxNode scopeDesignator) { throw ExceptionUtilities.Unreachable; } internal override uint LocalScopeDepth => Binder.TopLevelScope; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal class WithLambdaParametersBinder : LocalScopeBinder { protected readonly LambdaSymbol lambdaSymbol; protected readonly MultiDictionary<string, ParameterSymbol> parameterMap; private readonly SmallDictionary<string, ParameterSymbol> _definitionMap; public WithLambdaParametersBinder(LambdaSymbol lambdaSymbol, Binder enclosing) : base(enclosing) { this.lambdaSymbol = lambdaSymbol; this.parameterMap = new MultiDictionary<string, ParameterSymbol>(); var parameters = lambdaSymbol.Parameters; if (!parameters.IsDefaultOrEmpty) { _definitionMap = new SmallDictionary<string, ParameterSymbol>(); foreach (var parameter in parameters) { if (!parameter.IsDiscard) { var name = parameter.Name; this.parameterMap.Add(name, parameter); if (!_definitionMap.ContainsKey(name)) { _definitionMap.Add(name, parameter); } } } } } protected override TypeSymbol GetCurrentReturnType(out RefKind refKind) { refKind = lambdaSymbol.RefKind; return lambdaSymbol.ReturnType; } internal override Symbol ContainingMemberOrLambda { get { return this.lambdaSymbol; } } internal override bool IsNestedFunctionBinder => true; internal override bool IsDirectlyInIterator { get { return false; } } // NOTE: Specifically not overriding IsIndirectlyInIterator. internal override TypeWithAnnotations GetIteratorElementType() { return TypeWithAnnotations.Create(CreateErrorType()); } protected override void ValidateYield(YieldStatementSyntax node, BindingDiagnosticBag diagnostics) { if (node != null) { diagnostics.Add(ErrorCode.ERR_YieldInAnonMeth, node.YieldKeyword.GetLocation()); } } internal override void LookupSymbolsInSingleBinder( LookupResult result, string name, int arity, ConsList<TypeSymbol> basesBeingResolved, LookupOptions options, Binder originalBinder, bool diagnose, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(result.IsClear); if ((options & LookupOptions.NamespaceAliasesOnly) != 0) { return; } foreach (var parameterSymbol in parameterMap[name]) { result.MergeEqual(originalBinder.CheckViability(parameterSymbol, arity, options, null, diagnose, ref useSiteInfo)); } } protected override void AddLookupSymbolsInfoInSingleBinder(LookupSymbolsInfo result, LookupOptions options, Binder originalBinder) { if (options.CanConsiderMembers()) { foreach (var parameter in lambdaSymbol.Parameters) { if (originalBinder.CanAddLookupSymbolInfo(parameter, options, result, null)) { result.AddSymbol(parameter, parameter.Name, 0); } } } } private static bool ReportConflictWithParameter(ParameterSymbol parameter, Symbol newSymbol, string name, Location newLocation, BindingDiagnosticBag diagnostics) { var oldLocation = parameter.Locations[0]; if (oldLocation == newLocation) { // a query variable and its corresponding lambda parameter, for example return false; } // Quirk of the way we represent lambda parameters. SymbolKind newSymbolKind = (object)newSymbol == null ? SymbolKind.Parameter : newSymbol.Kind; switch (newSymbolKind) { case SymbolKind.ErrorType: return true; case SymbolKind.Parameter: case SymbolKind.Local: // Error: A local or parameter named '{0}' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter diagnostics.Add(ErrorCode.ERR_LocalIllegallyOverrides, newLocation, name); return true; case SymbolKind.Method: // Local function declaration name conflicts are not reported, for backwards compatibility. return false; case SymbolKind.TypeParameter: // Type parameter declaration name conflicts are not reported, for backwards compatibility. return false; case SymbolKind.RangeVariable: // The range variable '{0}' conflicts with a previous declaration of '{0}' diagnostics.Add(ErrorCode.ERR_QueryRangeVariableOverrides, newLocation, name); return true; } Debug.Assert(false, "what else could be defined in a lambda?"); diagnostics.Add(ErrorCode.ERR_InternalError, newLocation); return false; } internal override bool EnsureSingleDefinition(Symbol symbol, string name, Location location, BindingDiagnosticBag diagnostics) { ParameterSymbol existingDeclaration; var map = _definitionMap; if (map != null && map.TryGetValue(name, out existingDeclaration)) { return ReportConflictWithParameter(existingDeclaration, symbol, name, location, diagnostics); } return false; } internal override ImmutableArray<LocalSymbol> GetDeclaredLocalsForScope(SyntaxNode scopeDesignator) { throw ExceptionUtilities.Unreachable; } internal override ImmutableArray<LocalFunctionSymbol> GetDeclaredLocalFunctionsForScope(CSharpSyntaxNode scopeDesignator) { throw ExceptionUtilities.Unreachable; } internal override uint LocalScopeDepth => Binder.TopLevelScope; } }
-1
dotnet/roslyn
56,419
Fix partial method doc comments
Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
RikkiGibson
"2021-09-15T20:47:39Z"
"2021-09-21T23:49:10Z"
0f60b3e9446f5d0fc14a570998c81a5d6c40cc23
8cda7462843d43d9b72039eede2f4cb43126cac2
Fix partial method doc comments. Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
./src/Tools/ExternalAccess/FSharp/DocumentHighlighting/IFSharpDocumentHighlightsService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.DocumentHighlighting { internal enum FSharpHighlightSpanKind { None, Definition, Reference, WrittenReference, } internal readonly struct FSharpHighlightSpan { public TextSpan TextSpan { get; } public FSharpHighlightSpanKind Kind { get; } public FSharpHighlightSpan(TextSpan textSpan, FSharpHighlightSpanKind kind) : this() { this.TextSpan = textSpan; this.Kind = kind; } } internal readonly struct FSharpDocumentHighlights { public Document Document { get; } public ImmutableArray<FSharpHighlightSpan> HighlightSpans { get; } public FSharpDocumentHighlights(Document document, ImmutableArray<FSharpHighlightSpan> highlightSpans) { this.Document = document; this.HighlightSpans = highlightSpans; } } /// <summary> /// Note: This is the new version of the language service and superceded the same named type /// in the EditorFeatures layer. /// </summary> internal interface IFSharpDocumentHighlightsService { Task<ImmutableArray<FSharpDocumentHighlights>> GetDocumentHighlightsAsync( Document document, int position, IImmutableSet<Document> documentsToSearch, CancellationToken cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.DocumentHighlighting { internal enum FSharpHighlightSpanKind { None, Definition, Reference, WrittenReference, } internal readonly struct FSharpHighlightSpan { public TextSpan TextSpan { get; } public FSharpHighlightSpanKind Kind { get; } public FSharpHighlightSpan(TextSpan textSpan, FSharpHighlightSpanKind kind) : this() { this.TextSpan = textSpan; this.Kind = kind; } } internal readonly struct FSharpDocumentHighlights { public Document Document { get; } public ImmutableArray<FSharpHighlightSpan> HighlightSpans { get; } public FSharpDocumentHighlights(Document document, ImmutableArray<FSharpHighlightSpan> highlightSpans) { this.Document = document; this.HighlightSpans = highlightSpans; } } /// <summary> /// Note: This is the new version of the language service and superceded the same named type /// in the EditorFeatures layer. /// </summary> internal interface IFSharpDocumentHighlightsService { Task<ImmutableArray<FSharpDocumentHighlights>> GetDocumentHighlightsAsync( Document document, int position, IImmutableSet<Document> documentsToSearch, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
56,419
Fix partial method doc comments
Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
RikkiGibson
"2021-09-15T20:47:39Z"
"2021-09-21T23:49:10Z"
0f60b3e9446f5d0fc14a570998c81a5d6c40cc23
8cda7462843d43d9b72039eede2f4cb43126cac2
Fix partial method doc comments. Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
./src/Compilers/Core/Portable/Symbols/Attributes/IMemberNotNullAttributeTarget.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis { interface IMemberNotNullAttributeTarget { void AddNotNullMember(string memberName); void AddNotNullMember(ArrayBuilder<string> memberNames); ImmutableArray<string> NotNullMembers { get; } void AddNotNullWhenMember(bool sense, string memberName); void AddNotNullWhenMember(bool sense, ArrayBuilder<string> memberNames); ImmutableArray<string> NotNullWhenTrueMembers { get; } ImmutableArray<string> NotNullWhenFalseMembers { get; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis { interface IMemberNotNullAttributeTarget { void AddNotNullMember(string memberName); void AddNotNullMember(ArrayBuilder<string> memberNames); ImmutableArray<string> NotNullMembers { get; } void AddNotNullWhenMember(bool sense, string memberName); void AddNotNullWhenMember(bool sense, ArrayBuilder<string> memberNames); ImmutableArray<string> NotNullWhenTrueMembers { get; } ImmutableArray<string> NotNullWhenFalseMembers { get; } } }
-1
dotnet/roslyn
56,419
Fix partial method doc comments
Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
RikkiGibson
"2021-09-15T20:47:39Z"
"2021-09-21T23:49:10Z"
0f60b3e9446f5d0fc14a570998c81a5d6c40cc23
8cda7462843d43d9b72039eede2f4cb43126cac2
Fix partial method doc comments. Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
./src/VisualStudio/Core/Impl/SolutionExplorer/DiagnosticItem/BaseDiagnosticAndGeneratorItemSource.DiagnosticDescriptorComparer.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Globalization; using Microsoft.CodeAnalysis; namespace Microsoft.VisualStudio.LanguageServices.Implementation.SolutionExplorer { internal abstract partial class BaseDiagnosticAndGeneratorItemSource { internal sealed class DiagnosticDescriptorComparer : IComparer<DiagnosticDescriptor> { public int Compare(DiagnosticDescriptor x, DiagnosticDescriptor y) { var comparison = StringComparer.CurrentCulture.Compare(x.Id, y.Id); if (comparison != 0) { return comparison; } comparison = StringComparer.CurrentCulture.Compare(x.Title.ToString(CultureInfo.CurrentUICulture), y.Title.ToString(CultureInfo.CurrentUICulture)); if (comparison != 0) { return comparison; } comparison = StringComparer.CurrentCulture.Compare(x.MessageFormat.ToString(CultureInfo.CurrentUICulture), y.MessageFormat.ToString(CultureInfo.CurrentUICulture)); return comparison; } } } }
// Licensed to the .NET Foundation under one or more agreements. // 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.Globalization; using Microsoft.CodeAnalysis; namespace Microsoft.VisualStudio.LanguageServices.Implementation.SolutionExplorer { internal abstract partial class BaseDiagnosticAndGeneratorItemSource { internal sealed class DiagnosticDescriptorComparer : IComparer<DiagnosticDescriptor> { public int Compare(DiagnosticDescriptor x, DiagnosticDescriptor y) { var comparison = StringComparer.CurrentCulture.Compare(x.Id, y.Id); if (comparison != 0) { return comparison; } comparison = StringComparer.CurrentCulture.Compare(x.Title.ToString(CultureInfo.CurrentUICulture), y.Title.ToString(CultureInfo.CurrentUICulture)); if (comparison != 0) { return comparison; } comparison = StringComparer.CurrentCulture.Compare(x.MessageFormat.ToString(CultureInfo.CurrentUICulture), y.MessageFormat.ToString(CultureInfo.CurrentUICulture)); return comparison; } } } }
-1
dotnet/roslyn
56,419
Fix partial method doc comments
Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
RikkiGibson
"2021-09-15T20:47:39Z"
"2021-09-21T23:49:10Z"
0f60b3e9446f5d0fc14a570998c81a5d6c40cc23
8cda7462843d43d9b72039eede2f4cb43126cac2
Fix partial method doc comments. Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
./src/EditorFeatures/CSharpTest2/Recommendations/ThrowKeywordRecommenderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class ThrowKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtRoot_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClass_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalStatement_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalVariableDeclaration_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestEmptyStatement() { await VerifyKeywordAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestBeforeStatement() { await VerifyKeywordAsync(AddInsideMethod( @"$$ return true;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterStatement() { await VerifyKeywordAsync(AddInsideMethod( @"return true; $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterBlock() { await VerifyKeywordAsync(AddInsideMethod( @"if (true) { } $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIf() { await VerifyKeywordAsync(AddInsideMethod( @"if (true) $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDo() { await VerifyKeywordAsync(AddInsideMethod( @"do $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterWhile() { await VerifyKeywordAsync(AddInsideMethod( @"while (true) $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterFor() { await VerifyKeywordAsync(AddInsideMethod( @"for (int i = 0; i < 10; i++) $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterForeach() { await VerifyKeywordAsync(AddInsideMethod( @"foreach (var v in bar) $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterThrow() { await VerifyAbsenceAsync(AddInsideMethod( @"throw $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInClass() { await VerifyAbsenceAsync(@"class C { $$ }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInNestedIf() { await VerifyKeywordAsync(AddInsideMethod( @"if (caseOrDefaultKeywordOpt != null) { if (caseOrDefaultKeyword.Kind != SyntaxKind.CaseKeyword && caseOrDefaultKeyword.Kind != SyntaxKind.DefaultKeyword) $$")); } [WorkItem(9099, "https://github.com/dotnet/roslyn/issues/9099")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterArrow() { await VerifyKeywordAsync( @"class C { void Goo() => $$ "); } [WorkItem(9099, "https://github.com/dotnet/roslyn/issues/9099")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterQuestionQuestion() { await VerifyKeywordAsync( @"class C { public C(object o) { _o = o ?? $$ "); } [WorkItem(9099, "https://github.com/dotnet/roslyn/issues/9099")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInConditional1() { await VerifyKeywordAsync( @"class C { public C(object o) { var v= true ? $$ "); } [WorkItem(9099, "https://github.com/dotnet/roslyn/issues/9099")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInConditional2() { await VerifyKeywordAsync( @"class C { public C(object o) { var v= true ? 0 : $$ "); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class ThrowKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtRoot_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClass_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalStatement_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalVariableDeclaration_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestEmptyStatement() { await VerifyKeywordAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestBeforeStatement() { await VerifyKeywordAsync(AddInsideMethod( @"$$ return true;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterStatement() { await VerifyKeywordAsync(AddInsideMethod( @"return true; $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterBlock() { await VerifyKeywordAsync(AddInsideMethod( @"if (true) { } $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIf() { await VerifyKeywordAsync(AddInsideMethod( @"if (true) $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDo() { await VerifyKeywordAsync(AddInsideMethod( @"do $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterWhile() { await VerifyKeywordAsync(AddInsideMethod( @"while (true) $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterFor() { await VerifyKeywordAsync(AddInsideMethod( @"for (int i = 0; i < 10; i++) $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterForeach() { await VerifyKeywordAsync(AddInsideMethod( @"foreach (var v in bar) $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterThrow() { await VerifyAbsenceAsync(AddInsideMethod( @"throw $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInClass() { await VerifyAbsenceAsync(@"class C { $$ }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInNestedIf() { await VerifyKeywordAsync(AddInsideMethod( @"if (caseOrDefaultKeywordOpt != null) { if (caseOrDefaultKeyword.Kind != SyntaxKind.CaseKeyword && caseOrDefaultKeyword.Kind != SyntaxKind.DefaultKeyword) $$")); } [WorkItem(9099, "https://github.com/dotnet/roslyn/issues/9099")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterArrow() { await VerifyKeywordAsync( @"class C { void Goo() => $$ "); } [WorkItem(9099, "https://github.com/dotnet/roslyn/issues/9099")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterQuestionQuestion() { await VerifyKeywordAsync( @"class C { public C(object o) { _o = o ?? $$ "); } [WorkItem(9099, "https://github.com/dotnet/roslyn/issues/9099")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInConditional1() { await VerifyKeywordAsync( @"class C { public C(object o) { var v= true ? $$ "); } [WorkItem(9099, "https://github.com/dotnet/roslyn/issues/9099")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInConditional2() { await VerifyKeywordAsync( @"class C { public C(object o) { var v= true ? 0 : $$ "); } } }
-1
dotnet/roslyn
56,419
Fix partial method doc comments
Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
RikkiGibson
"2021-09-15T20:47:39Z"
"2021-09-21T23:49:10Z"
0f60b3e9446f5d0fc14a570998c81a5d6c40cc23
8cda7462843d43d9b72039eede2f4cb43126cac2
Fix partial method doc comments. Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
./src/ExpressionEvaluator/Core/Source/ResultProvider/NetFX20/Helpers/Placeholders.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Reflection; using System.Runtime.Versioning; [assembly: TargetFramework(".NETFramework,Version=v2.0")] namespace Microsoft.CodeAnalysis { internal static class ReflectionTypeExtensions { // Replaces a missing 4.5 method. internal static Type GetTypeInfo(this Type type) { return type; } // Replaces a missing 4.5 method. public static FieldInfo GetDeclaredField(this Type type, string name) { return type.GetField(name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly); } // Replaces a missing 4.5 method. public static MethodInfo GetDeclaredMethod(this Type type, string name, Type[] parameterTypes) { return type.GetMethod(name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly, null, parameterTypes, null); } } /// <summary> /// Required by <see cref="SymbolDisplayPartKind"/>. /// </summary> internal static class IErrorTypeSymbol { } /// <summary> /// Required by <see cref="Microsoft.CodeAnalysis.FailFast"/> /// </summary> internal static class Environment { public static void FailFast(string message) => System.Environment.FailFast(message); public static void FailFast(string message, Exception exception) => System.Environment.FailFast(exception.ToString()); public static string NewLine => System.Environment.NewLine; public static int ProcessorCount => System.Environment.ProcessorCount; } } namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = false)] // To allow this dll to use extension methods even though we are targeting CLR v2, re-define ExtensionAttribute internal class ExtensionAttribute : Attribute { } /// <summary> /// This satisfies a cref on <see cref="Microsoft.CodeAnalysis.ExpressionEvaluator.DynamicFlagsCustomTypeInfo.CopyTo"/>. /// </summary> [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue)] internal class DynamicAttribute : Attribute { } /// <summary> /// This satisfies a cref on <see cref="Microsoft.CodeAnalysis.WellKnownMemberNames"/>. /// </summary> internal interface INotifyCompletion { void OnCompleted(); } } namespace System.Text { internal static class StringBuilderExtensions { public static void Clear(this StringBuilder builder) { builder.Length = 0; // Matches the real definition. } } } namespace System.Runtime.Versioning { [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false, Inherited = false)] internal sealed class TargetFrameworkAttribute : Attribute { public string FrameworkName { get; } public string FrameworkDisplayName { get; set; } public TargetFrameworkAttribute(string frameworkName) => FrameworkName = frameworkName; } } namespace System.Threading { public readonly struct CancellationToken { /// <summary> /// .NET Framework 2.0 does not support cancellation via <see cref="CancellationToken"/>. /// </summary> public bool IsCancellationRequested => false; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Reflection; using System.Runtime.Versioning; [assembly: TargetFramework(".NETFramework,Version=v2.0")] namespace Microsoft.CodeAnalysis { internal static class ReflectionTypeExtensions { // Replaces a missing 4.5 method. internal static Type GetTypeInfo(this Type type) { return type; } // Replaces a missing 4.5 method. public static FieldInfo GetDeclaredField(this Type type, string name) { return type.GetField(name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly); } // Replaces a missing 4.5 method. public static MethodInfo GetDeclaredMethod(this Type type, string name, Type[] parameterTypes) { return type.GetMethod(name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly, null, parameterTypes, null); } } /// <summary> /// Required by <see cref="SymbolDisplayPartKind"/>. /// </summary> internal static class IErrorTypeSymbol { } /// <summary> /// Required by <see cref="Microsoft.CodeAnalysis.FailFast"/> /// </summary> internal static class Environment { public static void FailFast(string message) => System.Environment.FailFast(message); public static void FailFast(string message, Exception exception) => System.Environment.FailFast(exception.ToString()); public static string NewLine => System.Environment.NewLine; public static int ProcessorCount => System.Environment.ProcessorCount; } } namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = false)] // To allow this dll to use extension methods even though we are targeting CLR v2, re-define ExtensionAttribute internal class ExtensionAttribute : Attribute { } /// <summary> /// This satisfies a cref on <see cref="Microsoft.CodeAnalysis.ExpressionEvaluator.DynamicFlagsCustomTypeInfo.CopyTo"/>. /// </summary> [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue)] internal class DynamicAttribute : Attribute { } /// <summary> /// This satisfies a cref on <see cref="Microsoft.CodeAnalysis.WellKnownMemberNames"/>. /// </summary> internal interface INotifyCompletion { void OnCompleted(); } } namespace System.Text { internal static class StringBuilderExtensions { public static void Clear(this StringBuilder builder) { builder.Length = 0; // Matches the real definition. } } } namespace System.Runtime.Versioning { [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false, Inherited = false)] internal sealed class TargetFrameworkAttribute : Attribute { public string FrameworkName { get; } public string FrameworkDisplayName { get; set; } public TargetFrameworkAttribute(string frameworkName) => FrameworkName = frameworkName; } } namespace System.Threading { public readonly struct CancellationToken { /// <summary> /// .NET Framework 2.0 does not support cancellation via <see cref="CancellationToken"/>. /// </summary> public bool IsCancellationRequested => false; } }
-1
dotnet/roslyn
56,419
Fix partial method doc comments
Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
RikkiGibson
"2021-09-15T20:47:39Z"
"2021-09-21T23:49:10Z"
0f60b3e9446f5d0fc14a570998c81a5d6c40cc23
8cda7462843d43d9b72039eede2f4cb43126cac2
Fix partial method doc comments. Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
./src/Features/Core/Portable/Common/Glyph.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Microsoft.CodeAnalysis { internal enum Glyph { None, Assembly, BasicFile, BasicProject, ClassPublic, ClassProtected, ClassPrivate, ClassInternal, CSharpFile, CSharpProject, ConstantPublic, ConstantProtected, ConstantPrivate, ConstantInternal, DelegatePublic, DelegateProtected, DelegatePrivate, DelegateInternal, EnumPublic, EnumProtected, EnumPrivate, EnumInternal, EnumMemberPublic, EnumMemberProtected, EnumMemberPrivate, EnumMemberInternal, Error, StatusInformation, EventPublic, EventProtected, EventPrivate, EventInternal, ExtensionMethodPublic, ExtensionMethodProtected, ExtensionMethodPrivate, ExtensionMethodInternal, FieldPublic, FieldProtected, FieldPrivate, FieldInternal, InterfacePublic, InterfaceProtected, InterfacePrivate, InterfaceInternal, Intrinsic, Keyword, Label, Local, Namespace, MethodPublic, MethodProtected, MethodPrivate, MethodInternal, ModulePublic, ModuleProtected, ModulePrivate, ModuleInternal, OpenFolder, Operator, Parameter, PropertyPublic, PropertyProtected, PropertyPrivate, PropertyInternal, RangeVariable, Reference, StructurePublic, StructureProtected, StructurePrivate, StructureInternal, TypeParameter, Snippet, CompletionWarning, AddReference, NuGet, TargetTypeMatch } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Microsoft.CodeAnalysis { internal enum Glyph { None, Assembly, BasicFile, BasicProject, ClassPublic, ClassProtected, ClassPrivate, ClassInternal, CSharpFile, CSharpProject, ConstantPublic, ConstantProtected, ConstantPrivate, ConstantInternal, DelegatePublic, DelegateProtected, DelegatePrivate, DelegateInternal, EnumPublic, EnumProtected, EnumPrivate, EnumInternal, EnumMemberPublic, EnumMemberProtected, EnumMemberPrivate, EnumMemberInternal, Error, StatusInformation, EventPublic, EventProtected, EventPrivate, EventInternal, ExtensionMethodPublic, ExtensionMethodProtected, ExtensionMethodPrivate, ExtensionMethodInternal, FieldPublic, FieldProtected, FieldPrivate, FieldInternal, InterfacePublic, InterfaceProtected, InterfacePrivate, InterfaceInternal, Intrinsic, Keyword, Label, Local, Namespace, MethodPublic, MethodProtected, MethodPrivate, MethodInternal, ModulePublic, ModuleProtected, ModulePrivate, ModuleInternal, OpenFolder, Operator, Parameter, PropertyPublic, PropertyProtected, PropertyPrivate, PropertyInternal, RangeVariable, Reference, StructurePublic, StructureProtected, StructurePrivate, StructureInternal, TypeParameter, Snippet, CompletionWarning, AddReference, NuGet, TargetTypeMatch } }
-1
dotnet/roslyn
56,419
Fix partial method doc comments
Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
RikkiGibson
"2021-09-15T20:47:39Z"
"2021-09-21T23:49:10Z"
0f60b3e9446f5d0fc14a570998c81a5d6c40cc23
8cda7462843d43d9b72039eede2f4cb43126cac2
Fix partial method doc comments. Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
./src/EditorFeatures/CSharpTest/Completion/CompletionProviders/TypeImportCompletionProviderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.CSharp.Completion.Providers; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Completion.CompletionProviders { [UseExportProvider] public class TypeImportCompletionProviderTests : AbstractCSharpCompletionProviderTests { internal override Type GetCompletionProviderType() => typeof(TypeImportCompletionProvider); private bool? ShowImportCompletionItemsOptionValue { get; set; } = true; private bool IsExpandedCompletion { get; set; } = true; private bool HideAdvancedMembers { get; set; } protected override OptionSet WithChangedOptions(OptionSet options) { return base.WithChangedOptions(options) .WithChangedOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, LanguageNames.CSharp, ShowImportCompletionItemsOptionValue) .WithChangedOption(CompletionServiceOptions.IsExpandedCompletion, IsExpandedCompletion) .WithChangedOption(CompletionOptions.HideAdvancedMembers, LanguageNames.CSharp, HideAdvancedMembers); } #region "Option tests" [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task OptionSetToNull_ExpEnabled() { TypeImportCompletionFeatureFlag = true; ShowImportCompletionItemsOptionValue = null; var markup = @" class Bar { $$ }"; await VerifyAnyItemExistsAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task OptionSetToNull_ExpDisabled() { ShowImportCompletionItemsOptionValue = null; IsExpandedCompletion = false; var markup = @" class Bar { $$ }"; await VerifyNoItemsExistAsync(markup); } [InlineData(true)] [InlineData(false)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task OptionSetToFalse(bool isExperimentEnabled) { TypeImportCompletionFeatureFlag = isExperimentEnabled; ShowImportCompletionItemsOptionValue = false; IsExpandedCompletion = false; var markup = @" class Bar { $$ }"; await VerifyNoItemsExistAsync(markup); } [InlineData(true)] [InlineData(false)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task OptionSetToTrue(bool isExperimentEnabled) { TypeImportCompletionFeatureFlag = isExperimentEnabled; ShowImportCompletionItemsOptionValue = true; var markup = @" class Bar { $$ }"; await VerifyAnyItemExistsAsync(markup); } #endregion #region "CompletionItem tests" [InlineData("class", (int)Glyph.ClassPublic)] [InlineData("record", (int)Glyph.ClassPublic)] [InlineData("struct", (int)Glyph.StructurePublic)] [InlineData("enum", (int)Glyph.EnumPublic)] [InlineData("interface", (int)Glyph.InterfacePublic)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Show_TopLevel_NoImport_InProject(string typeKind, int glyph) { var file1 = $@" namespace Foo {{ public {typeKind} Bar {{}} }}"; var file2 = @" namespace Baz { class Bat { $$ } }"; await VerifyTypeImportItemExistsAsync( CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp), "Bar", glyph: glyph, inlineDescription: "Foo"); } [InlineData("class", (int)Glyph.ClassPublic)] [InlineData("record", (int)Glyph.ClassPublic)] [InlineData("struct", (int)Glyph.StructurePublic)] [InlineData("enum", (int)Glyph.EnumPublic)] [InlineData("interface", (int)Glyph.InterfacePublic)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Show_TopLevelStatement_NoImport_InProject(string typeKind, int glyph) { var file1 = $@" namespace Foo {{ public {typeKind} Bar {{}} }}"; var file2 = @" $$ "; await VerifyTypeImportItemExistsAsync( CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp), "Bar", glyph: glyph, inlineDescription: "Foo"); } [InlineData("class")] [InlineData("record")] [InlineData("struct")] [InlineData("enum")] [InlineData("interface")] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DoNotShow_TopLevel_SameNamespace_InProject(string typeKind) { var file1 = $@" namespace Foo {{ public {typeKind} Bar {{}} }}"; var file2 = @" namespace Foo { class Bat { $$ } }"; await VerifyTypeImportItemIsAbsentAsync( CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp), "Bar", inlineDescription: "Foo"); } [InlineData("class", (int)Glyph.ClassPublic)] [InlineData("record", (int)Glyph.ClassPublic)] [InlineData("struct", (int)Glyph.StructurePublic)] [InlineData("interface", (int)Glyph.InterfacePublic)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Show_TopLevel_MutipleOverrides_NoImport_InProject(string typeKind, int glyph) { var file1 = $@" namespace Foo {{ public {typeKind} Bar {{}} public {typeKind} Bar<T> {{}} public {typeKind} Bar<T1, T2> {{}} }}"; var file2 = @" namespace Baz { class Bat { $$ } }"; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); await VerifyTypeImportItemExistsAsync(markup, "Bar", glyph: glyph, inlineDescription: "Foo"); await VerifyTypeImportItemExistsAsync(markup, "Bar", displayTextSuffix: "<>", glyph: glyph, inlineDescription: "Foo"); } [InlineData("class")] [InlineData("record")] [InlineData("struct")] [InlineData("enum")] [InlineData("interface")] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DoNotShow_NestedType_NoImport_InProject(string typeKind) { var file1 = $@" namespace Foo {{ public class Bar {{ public {typeKind} Faz {{}} }} }}"; var file2 = @" namespace Baz { class Bat { $$ } }"; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); await VerifyTypeImportItemIsAbsentAsync(markup, "Faz", inlineDescription: "Foo"); await VerifyTypeImportItemIsAbsentAsync(markup, "Faz", inlineDescription: "Foo.Bar"); } [InlineData("class")] [InlineData("record")] [InlineData("struct")] [InlineData("enum")] [InlineData("interface")] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DoNotShow_TopLevel_WithImport_InProject(string typeKind) { var file1 = $@" namespace Foo {{ public {typeKind} Bar {{}} }}"; var file2 = @" namespace Baz { using Foo; class Bat { $$ } }"; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar", inlineDescription: "Foo"); } [InlineData(true)] [InlineData(false)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Show_TopLevel_Public_NoImport_InReference(bool isProjectReference) { var file1 = $@" namespace Foo {{ public class Bar {{}} public record Bar2 {{}} }}"; var file2 = @" namespace Baz { class Bat { $$ } }"; var markup = GetMarkupWithReference(file2, file1, LanguageNames.CSharp, LanguageNames.CSharp, isProjectReference); await VerifyTypeImportItemExistsAsync(markup, "Bar", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo"); await VerifyTypeImportItemExistsAsync(markup, "Bar2", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo"); } [InlineData(true)] [InlineData(false)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DoNotShow_TopLevel_Public_WithImport_InReference(bool isProjectReference) { var file1 = $@" namespace Foo {{ public class Bar {{}} public record Bar2 {{}} }}"; var file2 = @" using Foo; namespace Baz { class Bat { $$ } }"; var markup = GetMarkupWithReference(file2, file1, LanguageNames.CSharp, LanguageNames.CSharp, isProjectReference); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar", inlineDescription: "Foo"); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar2", inlineDescription: "Foo"); } [InlineData(true)] [InlineData(false)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DoNotShow_TopLevel_Internal_NoImport_InReference(bool isProjectReference) { var file1 = $@" namespace Foo {{ internal class Bar {{}} internal record Bar2 {{}} }}"; var file2 = @" namespace Baz { class Bat { $$ } }"; var markup = GetMarkupWithReference(file2, file1, LanguageNames.CSharp, LanguageNames.CSharp, isProjectReference); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar", inlineDescription: "Foo"); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar2", inlineDescription: "Foo"); } [InlineData(true)] [InlineData(false)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TopLevel_OverloadsWithMixedAccessibility_Internal_NoImport_InReference1(bool isProjectReference) { var file1 = $@" namespace Foo {{ internal class Bar {{}} public class Bar<T> {{}} }}"; var file2 = @" namespace Baz { class Bat { $$ } }"; var markup = GetMarkupWithReference(file2, file1, LanguageNames.CSharp, LanguageNames.CSharp, isProjectReference); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar", displayTextSuffix: "", inlineDescription: "Foo"); await VerifyTypeImportItemExistsAsync(markup, "Bar", displayTextSuffix: "<>", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo"); } [InlineData(true)] [InlineData(false)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DoNotShow_TopLevel_OverloadsWithMixedAccessibility_Internal_WithImport_InReference1(bool isProjectReference) { var file1 = $@" namespace Foo {{ internal class Bar {{}} public class Bar<T> {{}} }}"; var file2 = @" using Foo; namespace Baz { class Bat { $$ } }"; var markup = GetMarkupWithReference(file2, file1, LanguageNames.CSharp, LanguageNames.CSharp, isProjectReference); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar", displayTextSuffix: "", inlineDescription: "Foo"); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar", displayTextSuffix: "<>", inlineDescription: "Foo"); } [InlineData(true)] [InlineData(false)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TopLevel_OverloadsWithMixedAccessibility_InternalWithIVT_NoImport_InReference1(bool isProjectReference) { var file1 = $@" [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""Project1"")] namespace Foo {{ internal class Bar {{}} public class Bar<T> {{}} }}"; var file2 = @" namespace Baz { class Bat { $$ } }"; var markup = GetMarkupWithReference(file2, file1, LanguageNames.CSharp, LanguageNames.CSharp, isProjectReference); await VerifyTypeImportItemExistsAsync(markup, "Bar", glyph: (int)Glyph.ClassInternal, inlineDescription: "Foo"); await VerifyTypeImportItemExistsAsync(markup, "Bar", displayTextSuffix: "<>", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo"); } [InlineData(true)] [InlineData(false)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DoNotShow_TopLevel_OverloadsWithMixedAccessibility_InternalWithIVT_WithImport_InReference1(bool isProjectReference) { var file1 = $@" [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""Project1"")] namespace Foo {{ internal class Bar {{}} public class Bar<T> {{}} }}"; var file2 = @" using Foo; namespace Baz { class Bat { $$ } }"; var markup = GetMarkupWithReference(file2, file1, LanguageNames.CSharp, LanguageNames.CSharp, isProjectReference); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar", inlineDescription: "Foo"); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar", displayTextSuffix: "<>", inlineDescription: "Foo"); } [InlineData(true)] [InlineData(false)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TopLevel_OverloadsWithMixedAccessibility_Internal_NoImport_InReference2(bool isProjectReference) { var file1 = $@" namespace Foo {{ public class Bar {{}} public class Bar<T> {{}} internal class Bar<T1, T2> {{}} }}"; var file2 = @" namespace Baz { class Bat { $$ } }"; var markup = GetMarkupWithReference(file2, file1, LanguageNames.CSharp, LanguageNames.CSharp, isProjectReference); await VerifyTypeImportItemExistsAsync(markup, "Bar", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo"); await VerifyTypeImportItemExistsAsync(markup, "Bar", displayTextSuffix: "<>", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo"); } [InlineData(true)] [InlineData(false)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DoNotShow_TopLevel_OverloadsWithMixedAccessibility_Internal_SameNamespace_InReference2(bool isProjectReference) { var file1 = $@" namespace Foo {{ public class Bar {{}} public class Bar<T> {{}} internal class Bar<T1, T2> {{}} }}"; var file2 = @" namespace Foo.Baz { class Bat { $$ } }"; var markup = GetMarkupWithReference(file2, file1, LanguageNames.CSharp, LanguageNames.CSharp, isProjectReference); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar", inlineDescription: "Foo"); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar", displayTextSuffix: "<>", inlineDescription: "Foo"); } [InlineData(true)] [InlineData(false)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TopLevel_OverloadsWithMixedAccessibility_InternalWithIVT_NoImport_InReference2(bool isProjectReference) { var file1 = $@" [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""Project1"")] namespace Foo {{ internal class Bar {{}} internal class Bar<T> {{}} internal class Bar<T1, T2> {{}} }}"; var file2 = @" namespace Baz { class Bat { $$ } }"; var markup = GetMarkupWithReference(file2, file1, LanguageNames.CSharp, LanguageNames.CSharp, isProjectReference); await VerifyTypeImportItemExistsAsync(markup, "Bar", glyph: (int)Glyph.ClassInternal, inlineDescription: "Foo"); await VerifyTypeImportItemExistsAsync(markup, "Bar", displayTextSuffix: "<>", glyph: (int)Glyph.ClassInternal, inlineDescription: "Foo"); } [InlineData(true)] [InlineData(false)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Show_TopLevel_Internal_WithIVT_NoImport_InReference(bool isProjectReference) { var file1 = $@" [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""Project1"")] namespace Foo {{ internal class Bar {{}} }}"; var file2 = @" namespace Baz { class Bat { $$ } }"; var markup = GetMarkupWithReference(file2, file1, LanguageNames.CSharp, LanguageNames.CSharp, isProjectReference); await VerifyTypeImportItemExistsAsync(markup, "Bar", glyph: (int)Glyph.ClassInternal, inlineDescription: "Foo"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Show_TopLevel_NoImport_InVBReference() { var file1 = $@" Namespace Bar Public Class Barr End CLass End Namespace"; var file2 = @" namespace Baz { class Bat { $$ } }"; var markup = CreateMarkupForProjecWithVBProjectReference(file2, file1, sourceLanguage: LanguageNames.CSharp, rootNamespace: "Foo"); await VerifyTypeImportItemExistsAsync(markup, "Barr", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo.Bar"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task VB_MixedCapitalization_Test() { var file1 = $@" Namespace Na Public Class Foo End Class End Namespace Namespace na Public Class Bar End Class End Namespace "; var file2 = @" namespace Baz { class Bat { $$ } }"; var markup = CreateMarkupForProjecWithVBProjectReference(file2, file1, sourceLanguage: LanguageNames.CSharp, rootNamespace: ""); await VerifyTypeImportItemExistsAsync(markup, "Bar", glyph: (int)Glyph.ClassPublic, inlineDescription: "Na"); await VerifyTypeImportItemExistsAsync(markup, "Foo", glyph: (int)Glyph.ClassPublic, inlineDescription: "Na"); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar", inlineDescription: "na"); await VerifyTypeImportItemIsAbsentAsync(markup, "Foo", inlineDescription: "na"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task VB_MixedCapitalization_WithImport_Test() { var file1 = $@" Namespace Na Public Class Foo End Class End Namespace Namespace na Public Class Bar End Class End Namespace "; var file2 = @" using Na; namespace Baz { class Bat { $$ } }"; var markup = CreateMarkupForProjecWithVBProjectReference(file2, file1, sourceLanguage: LanguageNames.CSharp, rootNamespace: ""); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar", inlineDescription: "Na"); await VerifyTypeImportItemIsAbsentAsync(markup, "Foo", inlineDescription: "Na"); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar", inlineDescription: "na"); await VerifyTypeImportItemIsAbsentAsync(markup, "Foo", inlineDescription: "na"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DoNotShow_TopLevel_Internal_NoImport_InVBReference() { var file1 = $@" Namespace Bar Friend Class Barr End CLass End Namespace"; var file2 = @" namespace Baz { class Bat { $$ } }"; var markup = CreateMarkupForProjecWithVBProjectReference(file2, file1, sourceLanguage: LanguageNames.CSharp, rootNamespace: "Foo"); await VerifyTypeImportItemIsAbsentAsync(markup, "Barr", inlineDescription: "Foo.Bar"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DoNotShow_TopLevel_WithImport_InVBReference() { var file1 = $@" Namespace Bar Public Class Barr End CLass End Namespace"; var file2 = @" using Foo.Bar; namespace Baz { class Bat { $$ } }"; var markup = CreateMarkupForProjecWithVBProjectReference(file2, file1, sourceLanguage: LanguageNames.CSharp, rootNamespace: "Foo"); await VerifyTypeImportItemIsAbsentAsync(markup, "Barr", inlineDescription: "Foo.Bar"); } [InlineData(true)] [InlineData(false)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypesWithIdenticalNameButDifferentNamespaces(bool isProjectReference) { var file1 = $@" namespace Foo {{ public class Bar {{}} public class Bar<T> {{}} }} namespace Baz {{ public class Bar<T> {{}} public class Bar {{}} }}"; var file2 = @" namespace NS { class C { $$ } }"; var markup = GetMarkupWithReference(file2, file1, LanguageNames.CSharp, LanguageNames.CSharp, isProjectReference); await VerifyTypeImportItemExistsAsync(markup, "Bar", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo"); await VerifyTypeImportItemExistsAsync(markup, "Bar", displayTextSuffix: "<>", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo"); await VerifyTypeImportItemExistsAsync(markup, "Bar", glyph: (int)Glyph.ClassPublic, inlineDescription: "Baz"); await VerifyTypeImportItemExistsAsync(markup, "Bar", displayTextSuffix: "<>", glyph: (int)Glyph.ClassPublic, inlineDescription: "Baz"); } [InlineData(true)] [InlineData(false)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestNoCompletionItemWhenThereIsAlias(bool isProjectReference) { var file1 = @" using AliasFoo1 = Foo1.Foo2.Foo3.Foo4; using AliasFoo2 = Foo1.Foo2.Foo3.Foo4.Foo6; namespace Bar { using AliasFoo3 = Foo1.Foo2.Foo3.Foo5; using AliasFoo4 = Foo1.Foo2.Foo3.Foo5.Foo7; public class CC { public static void Main() { F$$ } } }"; var file2 = @" namespace Foo1 { namespace Foo2 { namespace Foo3 { public class Foo4 { public class Foo6 { } } public class Foo5 { public class Foo7 { } } } } }"; var markup = GetMarkupWithReference(file1, file2, LanguageNames.CSharp, LanguageNames.CSharp, isProjectReference); await VerifyTypeImportItemIsAbsentAsync(markup, "Foo4", "Foo1.Foo2.Foo3"); await VerifyTypeImportItemIsAbsentAsync(markup, "Foo6", "Foo1.Foo2.Foo3"); await VerifyTypeImportItemIsAbsentAsync(markup, "Foo5", "Foo1.Foo2.Foo3"); await VerifyTypeImportItemIsAbsentAsync(markup, "Foo7", "Foo1.Foo2.Foo3"); } [InlineData(true)] [InlineData(false)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestAttributesAlias(bool isProjectReference) { var file1 = @" using myAlias = Foo.BarAttribute; using myAlia2 = Foo.BarAttributeDifferentEnding; namespace Foo2 { public class Main { $$ } }"; var file2 = @" namespace Foo { public class BarAttribute: System.Attribute { } public class BarAttributeDifferentEnding: System.Attribute { } }"; var markup = GetMarkupWithReference(file1, file2, LanguageNames.CSharp, LanguageNames.CSharp, isProjectReference); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar", "Foo"); await VerifyTypeImportItemIsAbsentAsync(markup, "BarAttribute", "Foo"); await VerifyTypeImportItemIsAbsentAsync(markup, "BarAttributeDifferentEnding", "Foo"); } [InlineData(true)] [InlineData(false)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestGenericsAliasHasNoEffect(bool isProjectReference) { var file1 = @" using AliasFoo1 = Foo1.Foo2.Foo3.Foo4<int>; namespace Bar { using AliasFoo2 = Foo1.Foo2.Foo3.Foo5<string>; public class CC { public static void Main() { F$$ } } }"; var file2 = @" namespace Foo1 { namespace Foo2 { namespace Foo3 { public class Foo4<T> { } public class Foo5<U> { } } } }"; var markup = GetMarkupWithReference(file1, file2, LanguageNames.CSharp, LanguageNames.CSharp, isProjectReference); await VerifyTypeImportItemExistsAsync(markup, "Foo4", (int)Glyph.ClassPublic, "Foo1.Foo2.Foo3", displayTextSuffix: "<>"); await VerifyTypeImportItemExistsAsync(markup, "Foo5", (int)Glyph.ClassPublic, "Foo1.Foo2.Foo3", displayTextSuffix: "<>"); } #endregion #region "Commit Change Tests" [InlineData(SourceCodeKind.Regular)] [InlineData(SourceCodeKind.Script)] [WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Commit_NoImport_InProject(SourceCodeKind kind) { var file1 = $@" namespace Foo {{ public class Bar {{ }} }}"; var file2 = @" namespace Baz { class Bat { $$ } }"; var expectedCodeAfterCommit = @" using Foo; namespace Baz { class Bat { Bar$$ } }"; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); await VerifyCustomCommitProviderAsync(markup, "Bar", expectedCodeAfterCommit, sourceCodeKind: kind); } [InlineData(SourceCodeKind.Regular)] [InlineData(SourceCodeKind.Script)] [WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Commit_TopLevelStatement_NoImport_InProject(SourceCodeKind kind) { var file1 = $@" namespace Foo {{ public class Bar {{ }} }}"; var file2 = @" $$ "; var expectedCodeAfterCommit = @"using Foo; Bar$$ "; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); await VerifyCustomCommitProviderAsync(markup, "Bar", expectedCodeAfterCommit, sourceCodeKind: kind); } [InlineData(SourceCodeKind.Regular)] [InlineData(SourceCodeKind.Script)] [WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Commit_TopLevelStatement_UnrelatedImport_InProject(SourceCodeKind kind) { var file1 = $@" namespace Foo {{ public class Bar {{ }} }}"; var file2 = @" using System; $$ "; var expectedCodeAfterCommit = @" using System; using Foo; Bar$$ "; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); await VerifyCustomCommitProviderAsync(markup, "Bar", expectedCodeAfterCommit, sourceCodeKind: kind); } [InlineData(SourceCodeKind.Regular)] [InlineData(SourceCodeKind.Script)] [WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Commit_NoImport_InVBReference(SourceCodeKind kind) { var file1 = $@" Namespace Bar Public Class Barr End CLass End Namespace"; var file2 = @" namespace Baz { class Bat { $$ } }"; var expectedCodeAfterCommit = @" using Foo.Bar; namespace Baz { class Bat { Barr$$ } }"; var markup = CreateMarkupForProjecWithVBProjectReference(file2, file1, sourceLanguage: LanguageNames.CSharp, rootNamespace: "Foo"); await VerifyCustomCommitProviderAsync(markup, "Barr", expectedCodeAfterCommit, sourceCodeKind: kind); } [InlineData(SourceCodeKind.Regular)] [InlineData(SourceCodeKind.Script)] [WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Commit_NoImport_InPEReference(SourceCodeKind kind) { var markup = $@"<Workspace> <Project Language=""{LanguageNames.CSharp}"" CommonReferences=""true""> <Document FilePath=""CSharpDocument""> class Bar {{ $$ }}</Document> </Project> </Workspace>"; var expectedCodeAfterCommit = @" using System; class Bar { Console$$ }"; await VerifyCustomCommitProviderAsync(markup, "Console", expectedCodeAfterCommit, sourceCodeKind: kind); } #endregion [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DoNotShow_TopLevel_Public_NoImport_InNonGlobalAliasedMetadataReference() { var file1 = $@" namespace Foo {{ public class Bar {{}} }}"; var file2 = @" namespace Baz { class Bat { $$ } }"; var markup = CreateMarkupForProjectWithAliasedMetadataReference(file2, "alias1", file1, LanguageNames.CSharp, LanguageNames.CSharp, hasGlobalAlias: false); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar", inlineDescription: "Foo"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Show_TopLevel_Public_NoImport_InGlobalAliasedMetadataReference() { var file1 = $@" namespace Foo {{ public class Bar {{}} }}"; var file2 = @" namespace Baz { class Bat { $$ } }"; var markup = CreateMarkupForProjectWithAliasedMetadataReference(file2, "alias1", file1, LanguageNames.CSharp, LanguageNames.CSharp, hasGlobalAlias: true); await VerifyTypeImportItemExistsAsync(markup, "Bar", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DoNotShow_TopLevel_Public_NoImport_InNonGlobalAliasedProjectReference() { var file1 = $@" namespace Foo {{ public class Bar {{}} }}"; var file2 = @" namespace Baz { class Bat { $$ } }"; var markup = CreateMarkupForProjectWithAliasedProjectReference(file2, "alias1", file1, LanguageNames.CSharp, LanguageNames.CSharp); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar", inlineDescription: "Foo"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ShorterTypeNameShouldShowBeforeLongerTypeName() { var file1 = $@" namespace Foo {{ public class SomeType {{}} public class SomeTypeWithLongerName {{}} }}"; var file2 = @" namespace Baz { class Bat { $$ } }"; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); var completionList = await GetCompletionListAsync(markup).ConfigureAwait(false); AssertRelativeOrder(new List<string>() { "SomeType", "SomeTypeWithLongerName" }, completionList.Items); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(35540, "https://github.com/dotnet/roslyn/issues/35540")] public async Task AttributeTypeInAttributeNameContext() { var file1 = @" namespace Foo { public class MyAttribute : System.Attribute { } public class MyAttributeWithoutSuffix : System.Attribute { } public class MyClass { } }"; var file2 = @" namespace Test { [$$ class Program { } }"; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); await VerifyTypeImportItemExistsAsync(markup, "My", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo", expectedDescriptionOrNull: "class Foo.MyAttribute", flags: CompletionItemFlags.Expanded); await VerifyTypeImportItemIsAbsentAsync(markup, "MyAttributeWithoutSuffix", inlineDescription: "Foo"); // We intentionally ignore attribute types without proper suffix for perf reason await VerifyTypeImportItemIsAbsentAsync(markup, "MyAttribute", inlineDescription: "Foo"); await VerifyTypeImportItemIsAbsentAsync(markup, "MyClass", inlineDescription: "Foo"); } [InlineData(SourceCodeKind.Regular)] [InlineData(SourceCodeKind.Script)] [WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(35540, "https://github.com/dotnet/roslyn/issues/35540")] public async Task CommitAttributeTypeInAttributeNameContext(SourceCodeKind kind) { var file1 = @" namespace Foo { public class MyAttribute : System.Attribute { } }"; var file2 = @" namespace Test { [$$ class Program { } }"; var expectedCodeAfterCommit = @" using Foo; namespace Test { [My$$ class Program { } }"; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); await VerifyCustomCommitProviderAsync(markup, "My", expectedCodeAfterCommit, sourceCodeKind: kind); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(35540, "https://github.com/dotnet/roslyn/issues/35540")] public async Task AttributeTypeInNonAttributeNameContext() { var file1 = @" namespace Foo { public class MyAttribute : System.Attribute { } public class MyAttributeWithoutSuffix : System.Attribute { } public class MyClass { } }"; var file2 = @" namespace Test { class Program { $$ } }"; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); await VerifyTypeImportItemExistsAsync(markup, "MyAttribute", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo", expectedDescriptionOrNull: "class Foo.MyAttribute", flags: CompletionItemFlags.CachedAndExpanded); await VerifyTypeImportItemExistsAsync(markup, "MyAttributeWithoutSuffix", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo", expectedDescriptionOrNull: "class Foo.MyAttributeWithoutSuffix", flags: CompletionItemFlags.CachedAndExpanded); await VerifyTypeImportItemIsAbsentAsync(markup, "My", inlineDescription: "Foo"); await VerifyTypeImportItemExistsAsync(markup, "MyClass", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo", expectedDescriptionOrNull: "class Foo.MyClass", flags: CompletionItemFlags.CachedAndExpanded); } [InlineData(SourceCodeKind.Regular)] [InlineData(SourceCodeKind.Script)] [WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(35540, "https://github.com/dotnet/roslyn/issues/35540")] public async Task CommitAttributeTypeInNonAttributeNameContext(SourceCodeKind kind) { var file1 = @" namespace Foo { public class MyAttribute : System.Attribute { } }"; var file2 = @" namespace Test { class Program { $$ } }"; var expectedCodeAfterCommit = @" using Foo; namespace Test { class Program { MyAttribute$$ } }"; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); await VerifyCustomCommitProviderAsync(markup, "MyAttribute", expectedCodeAfterCommit, sourceCodeKind: kind); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(35540, "https://github.com/dotnet/roslyn/issues/35540")] public async Task AttributeTypeWithoutSuffixInAttributeNameContext() { // attribute suffix isn't capitalized var file1 = @" namespace Foo { public class Myattribute : System.Attribute { } public class MyClass { } }"; var file2 = @" namespace Test { [$$ class Program { } }"; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); await VerifyTypeImportItemExistsAsync(markup, "Myattribute", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo", expectedDescriptionOrNull: "class Foo.Myattribute", flags: CompletionItemFlags.CachedAndExpanded); await VerifyTypeImportItemIsAbsentAsync(markup, "My", inlineDescription: "Foo"); await VerifyTypeImportItemIsAbsentAsync(markup, "MyClass", inlineDescription: "Foo"); } [InlineData(SourceCodeKind.Regular)] [InlineData(SourceCodeKind.Script)] [WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(35540, "https://github.com/dotnet/roslyn/issues/35540")] public async Task CommitAttributeTypeWithoutSuffixInAttributeNameContext(SourceCodeKind kind) { // attribute suffix isn't capitalized var file1 = @" namespace Foo { public class Myattribute : System.Attribute { } }"; var file2 = @" namespace Test { [$$ class Program { } }"; var expectedCodeAfterCommit = @" using Foo; namespace Test { [Myattribute$$ class Program { } }"; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); await VerifyCustomCommitProviderAsync(markup, "Myattribute", expectedCodeAfterCommit, sourceCodeKind: kind); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(35540, "https://github.com/dotnet/roslyn/issues/35540")] public async Task AttributeTypeWithoutSuffixInNonAttributeNameContext() { // attribute suffix isn't capitalized var file1 = @" namespace Foo { public class Myattribute : System.Attribute { } public class MyClass { } }"; var file2 = @" namespace Test { class Program { $$ } }"; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); await VerifyTypeImportItemExistsAsync(markup, "Myattribute", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo", expectedDescriptionOrNull: "class Foo.Myattribute", flags: CompletionItemFlags.Expanded); await VerifyTypeImportItemIsAbsentAsync(markup, "My", inlineDescription: "Foo"); await VerifyTypeImportItemExistsAsync(markup, "MyClass", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo", expectedDescriptionOrNull: "class Foo.MyClass", flags: CompletionItemFlags.CachedAndExpanded); } [InlineData(SourceCodeKind.Regular)] [InlineData(SourceCodeKind.Script)] [WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(35540, "https://github.com/dotnet/roslyn/issues/35540")] public async Task CommitAttributeTypeWithoutSuffixInNonAttributeNameContext(SourceCodeKind kind) { // attribute suffix isn't capitalized var file1 = @" namespace Foo { public class Myattribute : System.Attribute { } }"; var file2 = @" namespace Test { class Program { $$ } }"; var expectedCodeAfterCommit = @" using Foo; namespace Test { class Program { Myattribute$$ } }"; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); await VerifyCustomCommitProviderAsync(markup, "Myattribute", expectedCodeAfterCommit, sourceCodeKind: kind); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(35540, "https://github.com/dotnet/roslyn/issues/35540")] public async Task VBAttributeTypeWithoutSuffixInAttributeNameContext() { var file1 = @" Namespace Foo Public Class Myattribute Inherits System.Attribute End Class Public Class MyVBClass End Class End Namespace"; var file2 = @" namespace Test { [$$ class Program { } }"; var markup = CreateMarkupForProjectWithProjectReference(file2, file1, LanguageNames.CSharp, LanguageNames.VisualBasic); await VerifyTypeImportItemExistsAsync(markup, "Myattribute", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo", expectedDescriptionOrNull: "class Foo.Myattribute", flags: CompletionItemFlags.Expanded); await VerifyTypeImportItemIsAbsentAsync(markup, "My", inlineDescription: "Foo"); await VerifyTypeImportItemIsAbsentAsync(markup, "MyVBClass", inlineDescription: "Foo"); } [InlineData(SourceCodeKind.Regular)] [InlineData(SourceCodeKind.Script)] [WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37038, "https://github.com/dotnet/roslyn/issues/37038")] public async Task CommitTypeInUsingStaticContextShouldUseFullyQualifiedName(SourceCodeKind kind) { var file1 = @" namespace Foo { public class MyClass { } }"; var file2 = @" using static $$"; var expectedCodeAfterCommit = @" using static Foo.MyClass$$"; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); await VerifyCustomCommitProviderAsync(markup, "MyClass", expectedCodeAfterCommit, sourceCodeKind: kind); } [InlineData(SourceCodeKind.Regular)] [InlineData(SourceCodeKind.Script)] [WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37038, "https://github.com/dotnet/roslyn/issues/37038")] public async Task CommitGenericTypeParameterInUsingAliasContextShouldUseFullyQualifiedName(SourceCodeKind kind) { var file1 = @" namespace Foo { public class MyClass { } }"; var file2 = @" using CollectionOfStringBuilders = System.Collections.Generic.List<$$>"; var expectedCodeAfterCommit = @" using CollectionOfStringBuilders = System.Collections.Generic.List<Foo.MyClass$$>"; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); await VerifyCustomCommitProviderAsync(markup, "MyClass", expectedCodeAfterCommit, sourceCodeKind: kind); } [InlineData(SourceCodeKind.Regular)] [InlineData(SourceCodeKind.Script)] [WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37038, "https://github.com/dotnet/roslyn/issues/37038")] public async Task CommitGenericTypeParameterInUsingAliasContextShouldUseFullyQualifiedName2(SourceCodeKind kind) { var file1 = @" namespace Foo.Bar { public class MyClass { } }"; var file2 = @" namespace Foo { using CollectionOfStringBuilders = System.Collections.Generic.List<$$> }"; // Completion is not fully qualified var expectedCodeAfterCommit = @" namespace Foo { using CollectionOfStringBuilders = System.Collections.Generic.List<Foo.Bar.MyClass$$> }"; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); await VerifyCustomCommitProviderAsync(markup, "MyClass", expectedCodeAfterCommit, sourceCodeKind: kind); } [Fact] [Trait(Traits.Feature, Traits.Features.Completion)] [Trait(Traits.Feature, Traits.Features.Interactive)] [WorkItem(39027, "https://github.com/dotnet/roslyn/issues/39027")] public async Task TriggerCompletionInSubsequentSubmission() { var markup = @" <Workspace> <Submission Language=""C#"" CommonReferences=""true""> var x = ""10""; </Submission> <Submission Language=""C#"" CommonReferences=""true""> var y = $$ </Submission> </Workspace> "; var completionList = await GetCompletionListAsync(markup, workspaceKind: WorkspaceKind.Interactive).ConfigureAwait(false); Assert.NotEmpty(completionList.Items); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ShouldNotTriggerInsideTrivia() { var file1 = $@" namespace Foo {{ public class Bar {{}} }}"; var file2 = @" namespace Baz { /// <summary> /// <see cref=""B$$""/> /// </summary> class Bat { } }"; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar", inlineDescription: "Foo"); } private static void AssertRelativeOrder(List<string> expectedTypesInRelativeOrder, ImmutableArray<CompletionItem> allCompletionItems) { var hashset = new HashSet<string>(expectedTypesInRelativeOrder); var actualTypesInRelativeOrder = allCompletionItems.SelectAsArray(item => hashset.Contains(item.DisplayText), item => item.DisplayText); Assert.Equal(expectedTypesInRelativeOrder.Count, actualTypesInRelativeOrder.Length); for (var i = 0; i < expectedTypesInRelativeOrder.Count; ++i) { Assert.Equal(expectedTypesInRelativeOrder[i], actualTypesInRelativeOrder[i]); } } [InlineData(true)] [InlineData(false)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestBrowsableAwaysFromReferences(bool isProjectReference) { var srcDoc = @" class Program { void M() { $$ } }"; var refDoc = @" namespace Foo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public class Goo { } }"; var markup = isProjectReference switch { true => CreateMarkupForProjectWithProjectReference(srcDoc, refDoc, LanguageNames.CSharp, LanguageNames.CSharp), false => CreateMarkupForProjectWithMetadataReference(srcDoc, refDoc, LanguageNames.CSharp, LanguageNames.CSharp) }; await VerifyTypeImportItemExistsAsync( markup, "Goo", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo"); } [InlineData(true)] [InlineData(false)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestBrowsableNeverFromReferences(bool isProjectReference) { var srcDoc = @" class Program { void M() { $$ } }"; var refDoc = @" namespace Foo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public class Goo { } }"; var (markup, shouldContainItem) = isProjectReference switch { true => (CreateMarkupForProjectWithProjectReference(srcDoc, refDoc, LanguageNames.CSharp, LanguageNames.CSharp), true), false => (CreateMarkupForProjectWithMetadataReference(srcDoc, refDoc, LanguageNames.CSharp, LanguageNames.CSharp), false), }; if (shouldContainItem) { await VerifyTypeImportItemExistsAsync( markup, "Goo", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo"); } else { await VerifyTypeImportItemIsAbsentAsync( markup, "Goo", inlineDescription: "Foo"); } } [InlineData(true, true)] [InlineData(true, false)] [InlineData(false, true)] [InlineData(false, false)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestBrowsableAdvancedFromReferences(bool isProjectReference, bool hideAdvancedMembers) { HideAdvancedMembers = hideAdvancedMembers; var srcDoc = @" class Program { void M() { $$ } }"; var refDoc = @" namespace Foo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] public class Goo { } }"; var (markup, shouldContainItem) = isProjectReference switch { true => (CreateMarkupForProjectWithProjectReference(srcDoc, refDoc, LanguageNames.CSharp, LanguageNames.CSharp), true), false => (CreateMarkupForProjectWithMetadataReference(srcDoc, refDoc, LanguageNames.CSharp, LanguageNames.CSharp), !hideAdvancedMembers), }; if (shouldContainItem) { await VerifyTypeImportItemExistsAsync( markup, "Goo", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo"); } else { await VerifyTypeImportItemIsAbsentAsync( markup, "Goo", inlineDescription: "Foo"); } } [Theory, Trait(Traits.Feature, Traits.Features.Completion)] [InlineData('.')] [InlineData(';')] public async Task TestCommitWithCustomizedCommitCharForParameterlessConstructor(char commitChar) { var markup = @" namespace AA { public class C { } } namespace BB { public class B { public void M() { var c = new $$ } } }"; var expected = $@" using AA; namespace AA {{ public class C {{ }} }} namespace BB {{ public class B {{ public void M() {{ var c = new C(){commitChar} }} }} }}"; await VerifyProviderCommitAsync(markup, "C", expected, commitChar: commitChar, sourceCodeKind: SourceCodeKind.Regular); } [Theory, Trait(Traits.Feature, Traits.Features.Completion)] [InlineData('.')] [InlineData(';')] public async Task TestCommitWithCustomizedCommitCharUnderNonObjectCreationContext(char commitChar) { var markup = @" namespace AA { public class C { } } namespace BB { public class B { public void M() { $$ } } }"; var expected = $@" using AA; namespace AA {{ public class C {{ }} }} namespace BB {{ public class B {{ public void M() {{ C{commitChar} }} }} }}"; await VerifyProviderCommitAsync(markup, "C", expected, commitChar: commitChar, sourceCodeKind: SourceCodeKind.Regular); } [InlineData(SourceCodeKind.Regular)] [InlineData(SourceCodeKind.Script)] [WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(54493, "https://github.com/dotnet/roslyn/issues/54493")] public async Task CommitInLocalFunctionContext(SourceCodeKind kind) { var markup = @" namespace Foo { public class MyClass { } } namespace Test { class Program { public static void Main() { static $$ } } }"; var expectedCodeAfterCommit = @" using Foo; namespace Foo { public class MyClass { } } namespace Test { class Program { public static void Main() { static MyClass } } }"; await VerifyProviderCommitAsync(markup, "MyClass", expectedCodeAfterCommit, commitChar: null, sourceCodeKind: kind); } private Task VerifyTypeImportItemExistsAsync(string markup, string expectedItem, int glyph, string inlineDescription, string displayTextSuffix = null, string expectedDescriptionOrNull = null, CompletionItemFlags? flags = null) => VerifyItemExistsAsync(markup, expectedItem, displayTextSuffix: displayTextSuffix, glyph: glyph, inlineDescription: inlineDescription, expectedDescriptionOrNull: expectedDescriptionOrNull, isComplexTextEdit: true, flags: flags); private Task VerifyTypeImportItemIsAbsentAsync(string markup, string expectedItem, string inlineDescription, string displayTextSuffix = null) => VerifyItemIsAbsentAsync(markup, expectedItem, displayTextSuffix: displayTextSuffix, inlineDescription: inlineDescription); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.CSharp.Completion.Providers; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Completion.CompletionProviders { [UseExportProvider] public class TypeImportCompletionProviderTests : AbstractCSharpCompletionProviderTests { internal override Type GetCompletionProviderType() => typeof(TypeImportCompletionProvider); private bool? ShowImportCompletionItemsOptionValue { get; set; } = true; private bool IsExpandedCompletion { get; set; } = true; private bool HideAdvancedMembers { get; set; } protected override OptionSet WithChangedOptions(OptionSet options) { return base.WithChangedOptions(options) .WithChangedOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, LanguageNames.CSharp, ShowImportCompletionItemsOptionValue) .WithChangedOption(CompletionServiceOptions.IsExpandedCompletion, IsExpandedCompletion) .WithChangedOption(CompletionOptions.HideAdvancedMembers, LanguageNames.CSharp, HideAdvancedMembers); } #region "Option tests" [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task OptionSetToNull_ExpEnabled() { TypeImportCompletionFeatureFlag = true; ShowImportCompletionItemsOptionValue = null; var markup = @" class Bar { $$ }"; await VerifyAnyItemExistsAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task OptionSetToNull_ExpDisabled() { ShowImportCompletionItemsOptionValue = null; IsExpandedCompletion = false; var markup = @" class Bar { $$ }"; await VerifyNoItemsExistAsync(markup); } [InlineData(true)] [InlineData(false)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task OptionSetToFalse(bool isExperimentEnabled) { TypeImportCompletionFeatureFlag = isExperimentEnabled; ShowImportCompletionItemsOptionValue = false; IsExpandedCompletion = false; var markup = @" class Bar { $$ }"; await VerifyNoItemsExistAsync(markup); } [InlineData(true)] [InlineData(false)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task OptionSetToTrue(bool isExperimentEnabled) { TypeImportCompletionFeatureFlag = isExperimentEnabled; ShowImportCompletionItemsOptionValue = true; var markup = @" class Bar { $$ }"; await VerifyAnyItemExistsAsync(markup); } #endregion #region "CompletionItem tests" [InlineData("class", (int)Glyph.ClassPublic)] [InlineData("record", (int)Glyph.ClassPublic)] [InlineData("struct", (int)Glyph.StructurePublic)] [InlineData("enum", (int)Glyph.EnumPublic)] [InlineData("interface", (int)Glyph.InterfacePublic)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Show_TopLevel_NoImport_InProject(string typeKind, int glyph) { var file1 = $@" namespace Foo {{ public {typeKind} Bar {{}} }}"; var file2 = @" namespace Baz { class Bat { $$ } }"; await VerifyTypeImportItemExistsAsync( CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp), "Bar", glyph: glyph, inlineDescription: "Foo"); } [InlineData("class", (int)Glyph.ClassPublic)] [InlineData("record", (int)Glyph.ClassPublic)] [InlineData("struct", (int)Glyph.StructurePublic)] [InlineData("enum", (int)Glyph.EnumPublic)] [InlineData("interface", (int)Glyph.InterfacePublic)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Show_TopLevelStatement_NoImport_InProject(string typeKind, int glyph) { var file1 = $@" namespace Foo {{ public {typeKind} Bar {{}} }}"; var file2 = @" $$ "; await VerifyTypeImportItemExistsAsync( CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp), "Bar", glyph: glyph, inlineDescription: "Foo"); } [InlineData("class")] [InlineData("record")] [InlineData("struct")] [InlineData("enum")] [InlineData("interface")] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DoNotShow_TopLevel_SameNamespace_InProject(string typeKind) { var file1 = $@" namespace Foo {{ public {typeKind} Bar {{}} }}"; var file2 = @" namespace Foo { class Bat { $$ } }"; await VerifyTypeImportItemIsAbsentAsync( CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp), "Bar", inlineDescription: "Foo"); } [InlineData("class", (int)Glyph.ClassPublic)] [InlineData("record", (int)Glyph.ClassPublic)] [InlineData("struct", (int)Glyph.StructurePublic)] [InlineData("interface", (int)Glyph.InterfacePublic)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Show_TopLevel_MutipleOverrides_NoImport_InProject(string typeKind, int glyph) { var file1 = $@" namespace Foo {{ public {typeKind} Bar {{}} public {typeKind} Bar<T> {{}} public {typeKind} Bar<T1, T2> {{}} }}"; var file2 = @" namespace Baz { class Bat { $$ } }"; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); await VerifyTypeImportItemExistsAsync(markup, "Bar", glyph: glyph, inlineDescription: "Foo"); await VerifyTypeImportItemExistsAsync(markup, "Bar", displayTextSuffix: "<>", glyph: glyph, inlineDescription: "Foo"); } [InlineData("class")] [InlineData("record")] [InlineData("struct")] [InlineData("enum")] [InlineData("interface")] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DoNotShow_NestedType_NoImport_InProject(string typeKind) { var file1 = $@" namespace Foo {{ public class Bar {{ public {typeKind} Faz {{}} }} }}"; var file2 = @" namespace Baz { class Bat { $$ } }"; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); await VerifyTypeImportItemIsAbsentAsync(markup, "Faz", inlineDescription: "Foo"); await VerifyTypeImportItemIsAbsentAsync(markup, "Faz", inlineDescription: "Foo.Bar"); } [InlineData("class")] [InlineData("record")] [InlineData("struct")] [InlineData("enum")] [InlineData("interface")] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DoNotShow_TopLevel_WithImport_InProject(string typeKind) { var file1 = $@" namespace Foo {{ public {typeKind} Bar {{}} }}"; var file2 = @" namespace Baz { using Foo; class Bat { $$ } }"; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar", inlineDescription: "Foo"); } [InlineData(true)] [InlineData(false)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Show_TopLevel_Public_NoImport_InReference(bool isProjectReference) { var file1 = $@" namespace Foo {{ public class Bar {{}} public record Bar2 {{}} }}"; var file2 = @" namespace Baz { class Bat { $$ } }"; var markup = GetMarkupWithReference(file2, file1, LanguageNames.CSharp, LanguageNames.CSharp, isProjectReference); await VerifyTypeImportItemExistsAsync(markup, "Bar", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo"); await VerifyTypeImportItemExistsAsync(markup, "Bar2", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo"); } [InlineData(true)] [InlineData(false)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DoNotShow_TopLevel_Public_WithImport_InReference(bool isProjectReference) { var file1 = $@" namespace Foo {{ public class Bar {{}} public record Bar2 {{}} }}"; var file2 = @" using Foo; namespace Baz { class Bat { $$ } }"; var markup = GetMarkupWithReference(file2, file1, LanguageNames.CSharp, LanguageNames.CSharp, isProjectReference); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar", inlineDescription: "Foo"); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar2", inlineDescription: "Foo"); } [InlineData(true)] [InlineData(false)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DoNotShow_TopLevel_Internal_NoImport_InReference(bool isProjectReference) { var file1 = $@" namespace Foo {{ internal class Bar {{}} internal record Bar2 {{}} }}"; var file2 = @" namespace Baz { class Bat { $$ } }"; var markup = GetMarkupWithReference(file2, file1, LanguageNames.CSharp, LanguageNames.CSharp, isProjectReference); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar", inlineDescription: "Foo"); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar2", inlineDescription: "Foo"); } [InlineData(true)] [InlineData(false)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TopLevel_OverloadsWithMixedAccessibility_Internal_NoImport_InReference1(bool isProjectReference) { var file1 = $@" namespace Foo {{ internal class Bar {{}} public class Bar<T> {{}} }}"; var file2 = @" namespace Baz { class Bat { $$ } }"; var markup = GetMarkupWithReference(file2, file1, LanguageNames.CSharp, LanguageNames.CSharp, isProjectReference); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar", displayTextSuffix: "", inlineDescription: "Foo"); await VerifyTypeImportItemExistsAsync(markup, "Bar", displayTextSuffix: "<>", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo"); } [InlineData(true)] [InlineData(false)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DoNotShow_TopLevel_OverloadsWithMixedAccessibility_Internal_WithImport_InReference1(bool isProjectReference) { var file1 = $@" namespace Foo {{ internal class Bar {{}} public class Bar<T> {{}} }}"; var file2 = @" using Foo; namespace Baz { class Bat { $$ } }"; var markup = GetMarkupWithReference(file2, file1, LanguageNames.CSharp, LanguageNames.CSharp, isProjectReference); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar", displayTextSuffix: "", inlineDescription: "Foo"); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar", displayTextSuffix: "<>", inlineDescription: "Foo"); } [InlineData(true)] [InlineData(false)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TopLevel_OverloadsWithMixedAccessibility_InternalWithIVT_NoImport_InReference1(bool isProjectReference) { var file1 = $@" [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""Project1"")] namespace Foo {{ internal class Bar {{}} public class Bar<T> {{}} }}"; var file2 = @" namespace Baz { class Bat { $$ } }"; var markup = GetMarkupWithReference(file2, file1, LanguageNames.CSharp, LanguageNames.CSharp, isProjectReference); await VerifyTypeImportItemExistsAsync(markup, "Bar", glyph: (int)Glyph.ClassInternal, inlineDescription: "Foo"); await VerifyTypeImportItemExistsAsync(markup, "Bar", displayTextSuffix: "<>", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo"); } [InlineData(true)] [InlineData(false)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DoNotShow_TopLevel_OverloadsWithMixedAccessibility_InternalWithIVT_WithImport_InReference1(bool isProjectReference) { var file1 = $@" [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""Project1"")] namespace Foo {{ internal class Bar {{}} public class Bar<T> {{}} }}"; var file2 = @" using Foo; namespace Baz { class Bat { $$ } }"; var markup = GetMarkupWithReference(file2, file1, LanguageNames.CSharp, LanguageNames.CSharp, isProjectReference); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar", inlineDescription: "Foo"); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar", displayTextSuffix: "<>", inlineDescription: "Foo"); } [InlineData(true)] [InlineData(false)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TopLevel_OverloadsWithMixedAccessibility_Internal_NoImport_InReference2(bool isProjectReference) { var file1 = $@" namespace Foo {{ public class Bar {{}} public class Bar<T> {{}} internal class Bar<T1, T2> {{}} }}"; var file2 = @" namespace Baz { class Bat { $$ } }"; var markup = GetMarkupWithReference(file2, file1, LanguageNames.CSharp, LanguageNames.CSharp, isProjectReference); await VerifyTypeImportItemExistsAsync(markup, "Bar", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo"); await VerifyTypeImportItemExistsAsync(markup, "Bar", displayTextSuffix: "<>", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo"); } [InlineData(true)] [InlineData(false)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DoNotShow_TopLevel_OverloadsWithMixedAccessibility_Internal_SameNamespace_InReference2(bool isProjectReference) { var file1 = $@" namespace Foo {{ public class Bar {{}} public class Bar<T> {{}} internal class Bar<T1, T2> {{}} }}"; var file2 = @" namespace Foo.Baz { class Bat { $$ } }"; var markup = GetMarkupWithReference(file2, file1, LanguageNames.CSharp, LanguageNames.CSharp, isProjectReference); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar", inlineDescription: "Foo"); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar", displayTextSuffix: "<>", inlineDescription: "Foo"); } [InlineData(true)] [InlineData(false)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TopLevel_OverloadsWithMixedAccessibility_InternalWithIVT_NoImport_InReference2(bool isProjectReference) { var file1 = $@" [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""Project1"")] namespace Foo {{ internal class Bar {{}} internal class Bar<T> {{}} internal class Bar<T1, T2> {{}} }}"; var file2 = @" namespace Baz { class Bat { $$ } }"; var markup = GetMarkupWithReference(file2, file1, LanguageNames.CSharp, LanguageNames.CSharp, isProjectReference); await VerifyTypeImportItemExistsAsync(markup, "Bar", glyph: (int)Glyph.ClassInternal, inlineDescription: "Foo"); await VerifyTypeImportItemExistsAsync(markup, "Bar", displayTextSuffix: "<>", glyph: (int)Glyph.ClassInternal, inlineDescription: "Foo"); } [InlineData(true)] [InlineData(false)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Show_TopLevel_Internal_WithIVT_NoImport_InReference(bool isProjectReference) { var file1 = $@" [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""Project1"")] namespace Foo {{ internal class Bar {{}} }}"; var file2 = @" namespace Baz { class Bat { $$ } }"; var markup = GetMarkupWithReference(file2, file1, LanguageNames.CSharp, LanguageNames.CSharp, isProjectReference); await VerifyTypeImportItemExistsAsync(markup, "Bar", glyph: (int)Glyph.ClassInternal, inlineDescription: "Foo"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Show_TopLevel_NoImport_InVBReference() { var file1 = $@" Namespace Bar Public Class Barr End CLass End Namespace"; var file2 = @" namespace Baz { class Bat { $$ } }"; var markup = CreateMarkupForProjecWithVBProjectReference(file2, file1, sourceLanguage: LanguageNames.CSharp, rootNamespace: "Foo"); await VerifyTypeImportItemExistsAsync(markup, "Barr", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo.Bar"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task VB_MixedCapitalization_Test() { var file1 = $@" Namespace Na Public Class Foo End Class End Namespace Namespace na Public Class Bar End Class End Namespace "; var file2 = @" namespace Baz { class Bat { $$ } }"; var markup = CreateMarkupForProjecWithVBProjectReference(file2, file1, sourceLanguage: LanguageNames.CSharp, rootNamespace: ""); await VerifyTypeImportItemExistsAsync(markup, "Bar", glyph: (int)Glyph.ClassPublic, inlineDescription: "Na"); await VerifyTypeImportItemExistsAsync(markup, "Foo", glyph: (int)Glyph.ClassPublic, inlineDescription: "Na"); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar", inlineDescription: "na"); await VerifyTypeImportItemIsAbsentAsync(markup, "Foo", inlineDescription: "na"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task VB_MixedCapitalization_WithImport_Test() { var file1 = $@" Namespace Na Public Class Foo End Class End Namespace Namespace na Public Class Bar End Class End Namespace "; var file2 = @" using Na; namespace Baz { class Bat { $$ } }"; var markup = CreateMarkupForProjecWithVBProjectReference(file2, file1, sourceLanguage: LanguageNames.CSharp, rootNamespace: ""); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar", inlineDescription: "Na"); await VerifyTypeImportItemIsAbsentAsync(markup, "Foo", inlineDescription: "Na"); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar", inlineDescription: "na"); await VerifyTypeImportItemIsAbsentAsync(markup, "Foo", inlineDescription: "na"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DoNotShow_TopLevel_Internal_NoImport_InVBReference() { var file1 = $@" Namespace Bar Friend Class Barr End CLass End Namespace"; var file2 = @" namespace Baz { class Bat { $$ } }"; var markup = CreateMarkupForProjecWithVBProjectReference(file2, file1, sourceLanguage: LanguageNames.CSharp, rootNamespace: "Foo"); await VerifyTypeImportItemIsAbsentAsync(markup, "Barr", inlineDescription: "Foo.Bar"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DoNotShow_TopLevel_WithImport_InVBReference() { var file1 = $@" Namespace Bar Public Class Barr End CLass End Namespace"; var file2 = @" using Foo.Bar; namespace Baz { class Bat { $$ } }"; var markup = CreateMarkupForProjecWithVBProjectReference(file2, file1, sourceLanguage: LanguageNames.CSharp, rootNamespace: "Foo"); await VerifyTypeImportItemIsAbsentAsync(markup, "Barr", inlineDescription: "Foo.Bar"); } [InlineData(true)] [InlineData(false)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypesWithIdenticalNameButDifferentNamespaces(bool isProjectReference) { var file1 = $@" namespace Foo {{ public class Bar {{}} public class Bar<T> {{}} }} namespace Baz {{ public class Bar<T> {{}} public class Bar {{}} }}"; var file2 = @" namespace NS { class C { $$ } }"; var markup = GetMarkupWithReference(file2, file1, LanguageNames.CSharp, LanguageNames.CSharp, isProjectReference); await VerifyTypeImportItemExistsAsync(markup, "Bar", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo"); await VerifyTypeImportItemExistsAsync(markup, "Bar", displayTextSuffix: "<>", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo"); await VerifyTypeImportItemExistsAsync(markup, "Bar", glyph: (int)Glyph.ClassPublic, inlineDescription: "Baz"); await VerifyTypeImportItemExistsAsync(markup, "Bar", displayTextSuffix: "<>", glyph: (int)Glyph.ClassPublic, inlineDescription: "Baz"); } [InlineData(true)] [InlineData(false)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestNoCompletionItemWhenThereIsAlias(bool isProjectReference) { var file1 = @" using AliasFoo1 = Foo1.Foo2.Foo3.Foo4; using AliasFoo2 = Foo1.Foo2.Foo3.Foo4.Foo6; namespace Bar { using AliasFoo3 = Foo1.Foo2.Foo3.Foo5; using AliasFoo4 = Foo1.Foo2.Foo3.Foo5.Foo7; public class CC { public static void Main() { F$$ } } }"; var file2 = @" namespace Foo1 { namespace Foo2 { namespace Foo3 { public class Foo4 { public class Foo6 { } } public class Foo5 { public class Foo7 { } } } } }"; var markup = GetMarkupWithReference(file1, file2, LanguageNames.CSharp, LanguageNames.CSharp, isProjectReference); await VerifyTypeImportItemIsAbsentAsync(markup, "Foo4", "Foo1.Foo2.Foo3"); await VerifyTypeImportItemIsAbsentAsync(markup, "Foo6", "Foo1.Foo2.Foo3"); await VerifyTypeImportItemIsAbsentAsync(markup, "Foo5", "Foo1.Foo2.Foo3"); await VerifyTypeImportItemIsAbsentAsync(markup, "Foo7", "Foo1.Foo2.Foo3"); } [InlineData(true)] [InlineData(false)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestAttributesAlias(bool isProjectReference) { var file1 = @" using myAlias = Foo.BarAttribute; using myAlia2 = Foo.BarAttributeDifferentEnding; namespace Foo2 { public class Main { $$ } }"; var file2 = @" namespace Foo { public class BarAttribute: System.Attribute { } public class BarAttributeDifferentEnding: System.Attribute { } }"; var markup = GetMarkupWithReference(file1, file2, LanguageNames.CSharp, LanguageNames.CSharp, isProjectReference); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar", "Foo"); await VerifyTypeImportItemIsAbsentAsync(markup, "BarAttribute", "Foo"); await VerifyTypeImportItemIsAbsentAsync(markup, "BarAttributeDifferentEnding", "Foo"); } [InlineData(true)] [InlineData(false)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestGenericsAliasHasNoEffect(bool isProjectReference) { var file1 = @" using AliasFoo1 = Foo1.Foo2.Foo3.Foo4<int>; namespace Bar { using AliasFoo2 = Foo1.Foo2.Foo3.Foo5<string>; public class CC { public static void Main() { F$$ } } }"; var file2 = @" namespace Foo1 { namespace Foo2 { namespace Foo3 { public class Foo4<T> { } public class Foo5<U> { } } } }"; var markup = GetMarkupWithReference(file1, file2, LanguageNames.CSharp, LanguageNames.CSharp, isProjectReference); await VerifyTypeImportItemExistsAsync(markup, "Foo4", (int)Glyph.ClassPublic, "Foo1.Foo2.Foo3", displayTextSuffix: "<>"); await VerifyTypeImportItemExistsAsync(markup, "Foo5", (int)Glyph.ClassPublic, "Foo1.Foo2.Foo3", displayTextSuffix: "<>"); } #endregion #region "Commit Change Tests" [InlineData(SourceCodeKind.Regular)] [InlineData(SourceCodeKind.Script)] [WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Commit_NoImport_InProject(SourceCodeKind kind) { var file1 = $@" namespace Foo {{ public class Bar {{ }} }}"; var file2 = @" namespace Baz { class Bat { $$ } }"; var expectedCodeAfterCommit = @" using Foo; namespace Baz { class Bat { Bar$$ } }"; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); await VerifyCustomCommitProviderAsync(markup, "Bar", expectedCodeAfterCommit, sourceCodeKind: kind); } [InlineData(SourceCodeKind.Regular)] [InlineData(SourceCodeKind.Script)] [WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Commit_TopLevelStatement_NoImport_InProject(SourceCodeKind kind) { var file1 = $@" namespace Foo {{ public class Bar {{ }} }}"; var file2 = @" $$ "; var expectedCodeAfterCommit = @"using Foo; Bar$$ "; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); await VerifyCustomCommitProviderAsync(markup, "Bar", expectedCodeAfterCommit, sourceCodeKind: kind); } [InlineData(SourceCodeKind.Regular)] [InlineData(SourceCodeKind.Script)] [WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Commit_TopLevelStatement_UnrelatedImport_InProject(SourceCodeKind kind) { var file1 = $@" namespace Foo {{ public class Bar {{ }} }}"; var file2 = @" using System; $$ "; var expectedCodeAfterCommit = @" using System; using Foo; Bar$$ "; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); await VerifyCustomCommitProviderAsync(markup, "Bar", expectedCodeAfterCommit, sourceCodeKind: kind); } [InlineData(SourceCodeKind.Regular)] [InlineData(SourceCodeKind.Script)] [WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Commit_NoImport_InVBReference(SourceCodeKind kind) { var file1 = $@" Namespace Bar Public Class Barr End CLass End Namespace"; var file2 = @" namespace Baz { class Bat { $$ } }"; var expectedCodeAfterCommit = @" using Foo.Bar; namespace Baz { class Bat { Barr$$ } }"; var markup = CreateMarkupForProjecWithVBProjectReference(file2, file1, sourceLanguage: LanguageNames.CSharp, rootNamespace: "Foo"); await VerifyCustomCommitProviderAsync(markup, "Barr", expectedCodeAfterCommit, sourceCodeKind: kind); } [InlineData(SourceCodeKind.Regular)] [InlineData(SourceCodeKind.Script)] [WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Commit_NoImport_InPEReference(SourceCodeKind kind) { var markup = $@"<Workspace> <Project Language=""{LanguageNames.CSharp}"" CommonReferences=""true""> <Document FilePath=""CSharpDocument""> class Bar {{ $$ }}</Document> </Project> </Workspace>"; var expectedCodeAfterCommit = @" using System; class Bar { Console$$ }"; await VerifyCustomCommitProviderAsync(markup, "Console", expectedCodeAfterCommit, sourceCodeKind: kind); } #endregion [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DoNotShow_TopLevel_Public_NoImport_InNonGlobalAliasedMetadataReference() { var file1 = $@" namespace Foo {{ public class Bar {{}} }}"; var file2 = @" namespace Baz { class Bat { $$ } }"; var markup = CreateMarkupForProjectWithAliasedMetadataReference(file2, "alias1", file1, LanguageNames.CSharp, LanguageNames.CSharp, hasGlobalAlias: false); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar", inlineDescription: "Foo"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Show_TopLevel_Public_NoImport_InGlobalAliasedMetadataReference() { var file1 = $@" namespace Foo {{ public class Bar {{}} }}"; var file2 = @" namespace Baz { class Bat { $$ } }"; var markup = CreateMarkupForProjectWithAliasedMetadataReference(file2, "alias1", file1, LanguageNames.CSharp, LanguageNames.CSharp, hasGlobalAlias: true); await VerifyTypeImportItemExistsAsync(markup, "Bar", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DoNotShow_TopLevel_Public_NoImport_InNonGlobalAliasedProjectReference() { var file1 = $@" namespace Foo {{ public class Bar {{}} }}"; var file2 = @" namespace Baz { class Bat { $$ } }"; var markup = CreateMarkupForProjectWithAliasedProjectReference(file2, "alias1", file1, LanguageNames.CSharp, LanguageNames.CSharp); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar", inlineDescription: "Foo"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ShorterTypeNameShouldShowBeforeLongerTypeName() { var file1 = $@" namespace Foo {{ public class SomeType {{}} public class SomeTypeWithLongerName {{}} }}"; var file2 = @" namespace Baz { class Bat { $$ } }"; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); var completionList = await GetCompletionListAsync(markup).ConfigureAwait(false); AssertRelativeOrder(new List<string>() { "SomeType", "SomeTypeWithLongerName" }, completionList.Items); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(35540, "https://github.com/dotnet/roslyn/issues/35540")] public async Task AttributeTypeInAttributeNameContext() { var file1 = @" namespace Foo { public class MyAttribute : System.Attribute { } public class MyAttributeWithoutSuffix : System.Attribute { } public class MyClass { } }"; var file2 = @" namespace Test { [$$ class Program { } }"; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); await VerifyTypeImportItemExistsAsync(markup, "My", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo", expectedDescriptionOrNull: "class Foo.MyAttribute", flags: CompletionItemFlags.Expanded); await VerifyTypeImportItemIsAbsentAsync(markup, "MyAttributeWithoutSuffix", inlineDescription: "Foo"); // We intentionally ignore attribute types without proper suffix for perf reason await VerifyTypeImportItemIsAbsentAsync(markup, "MyAttribute", inlineDescription: "Foo"); await VerifyTypeImportItemIsAbsentAsync(markup, "MyClass", inlineDescription: "Foo"); } [InlineData(SourceCodeKind.Regular)] [InlineData(SourceCodeKind.Script)] [WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(35540, "https://github.com/dotnet/roslyn/issues/35540")] public async Task CommitAttributeTypeInAttributeNameContext(SourceCodeKind kind) { var file1 = @" namespace Foo { public class MyAttribute : System.Attribute { } }"; var file2 = @" namespace Test { [$$ class Program { } }"; var expectedCodeAfterCommit = @" using Foo; namespace Test { [My$$ class Program { } }"; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); await VerifyCustomCommitProviderAsync(markup, "My", expectedCodeAfterCommit, sourceCodeKind: kind); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(35540, "https://github.com/dotnet/roslyn/issues/35540")] public async Task AttributeTypeInNonAttributeNameContext() { var file1 = @" namespace Foo { public class MyAttribute : System.Attribute { } public class MyAttributeWithoutSuffix : System.Attribute { } public class MyClass { } }"; var file2 = @" namespace Test { class Program { $$ } }"; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); await VerifyTypeImportItemExistsAsync(markup, "MyAttribute", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo", expectedDescriptionOrNull: "class Foo.MyAttribute", flags: CompletionItemFlags.CachedAndExpanded); await VerifyTypeImportItemExistsAsync(markup, "MyAttributeWithoutSuffix", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo", expectedDescriptionOrNull: "class Foo.MyAttributeWithoutSuffix", flags: CompletionItemFlags.CachedAndExpanded); await VerifyTypeImportItemIsAbsentAsync(markup, "My", inlineDescription: "Foo"); await VerifyTypeImportItemExistsAsync(markup, "MyClass", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo", expectedDescriptionOrNull: "class Foo.MyClass", flags: CompletionItemFlags.CachedAndExpanded); } [InlineData(SourceCodeKind.Regular)] [InlineData(SourceCodeKind.Script)] [WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(35540, "https://github.com/dotnet/roslyn/issues/35540")] public async Task CommitAttributeTypeInNonAttributeNameContext(SourceCodeKind kind) { var file1 = @" namespace Foo { public class MyAttribute : System.Attribute { } }"; var file2 = @" namespace Test { class Program { $$ } }"; var expectedCodeAfterCommit = @" using Foo; namespace Test { class Program { MyAttribute$$ } }"; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); await VerifyCustomCommitProviderAsync(markup, "MyAttribute", expectedCodeAfterCommit, sourceCodeKind: kind); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(35540, "https://github.com/dotnet/roslyn/issues/35540")] public async Task AttributeTypeWithoutSuffixInAttributeNameContext() { // attribute suffix isn't capitalized var file1 = @" namespace Foo { public class Myattribute : System.Attribute { } public class MyClass { } }"; var file2 = @" namespace Test { [$$ class Program { } }"; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); await VerifyTypeImportItemExistsAsync(markup, "Myattribute", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo", expectedDescriptionOrNull: "class Foo.Myattribute", flags: CompletionItemFlags.CachedAndExpanded); await VerifyTypeImportItemIsAbsentAsync(markup, "My", inlineDescription: "Foo"); await VerifyTypeImportItemIsAbsentAsync(markup, "MyClass", inlineDescription: "Foo"); } [InlineData(SourceCodeKind.Regular)] [InlineData(SourceCodeKind.Script)] [WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(35540, "https://github.com/dotnet/roslyn/issues/35540")] public async Task CommitAttributeTypeWithoutSuffixInAttributeNameContext(SourceCodeKind kind) { // attribute suffix isn't capitalized var file1 = @" namespace Foo { public class Myattribute : System.Attribute { } }"; var file2 = @" namespace Test { [$$ class Program { } }"; var expectedCodeAfterCommit = @" using Foo; namespace Test { [Myattribute$$ class Program { } }"; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); await VerifyCustomCommitProviderAsync(markup, "Myattribute", expectedCodeAfterCommit, sourceCodeKind: kind); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(35540, "https://github.com/dotnet/roslyn/issues/35540")] public async Task AttributeTypeWithoutSuffixInNonAttributeNameContext() { // attribute suffix isn't capitalized var file1 = @" namespace Foo { public class Myattribute : System.Attribute { } public class MyClass { } }"; var file2 = @" namespace Test { class Program { $$ } }"; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); await VerifyTypeImportItemExistsAsync(markup, "Myattribute", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo", expectedDescriptionOrNull: "class Foo.Myattribute", flags: CompletionItemFlags.Expanded); await VerifyTypeImportItemIsAbsentAsync(markup, "My", inlineDescription: "Foo"); await VerifyTypeImportItemExistsAsync(markup, "MyClass", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo", expectedDescriptionOrNull: "class Foo.MyClass", flags: CompletionItemFlags.CachedAndExpanded); } [InlineData(SourceCodeKind.Regular)] [InlineData(SourceCodeKind.Script)] [WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(35540, "https://github.com/dotnet/roslyn/issues/35540")] public async Task CommitAttributeTypeWithoutSuffixInNonAttributeNameContext(SourceCodeKind kind) { // attribute suffix isn't capitalized var file1 = @" namespace Foo { public class Myattribute : System.Attribute { } }"; var file2 = @" namespace Test { class Program { $$ } }"; var expectedCodeAfterCommit = @" using Foo; namespace Test { class Program { Myattribute$$ } }"; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); await VerifyCustomCommitProviderAsync(markup, "Myattribute", expectedCodeAfterCommit, sourceCodeKind: kind); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(35540, "https://github.com/dotnet/roslyn/issues/35540")] public async Task VBAttributeTypeWithoutSuffixInAttributeNameContext() { var file1 = @" Namespace Foo Public Class Myattribute Inherits System.Attribute End Class Public Class MyVBClass End Class End Namespace"; var file2 = @" namespace Test { [$$ class Program { } }"; var markup = CreateMarkupForProjectWithProjectReference(file2, file1, LanguageNames.CSharp, LanguageNames.VisualBasic); await VerifyTypeImportItemExistsAsync(markup, "Myattribute", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo", expectedDescriptionOrNull: "class Foo.Myattribute", flags: CompletionItemFlags.Expanded); await VerifyTypeImportItemIsAbsentAsync(markup, "My", inlineDescription: "Foo"); await VerifyTypeImportItemIsAbsentAsync(markup, "MyVBClass", inlineDescription: "Foo"); } [InlineData(SourceCodeKind.Regular)] [InlineData(SourceCodeKind.Script)] [WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37038, "https://github.com/dotnet/roslyn/issues/37038")] public async Task CommitTypeInUsingStaticContextShouldUseFullyQualifiedName(SourceCodeKind kind) { var file1 = @" namespace Foo { public class MyClass { } }"; var file2 = @" using static $$"; var expectedCodeAfterCommit = @" using static Foo.MyClass$$"; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); await VerifyCustomCommitProviderAsync(markup, "MyClass", expectedCodeAfterCommit, sourceCodeKind: kind); } [InlineData(SourceCodeKind.Regular)] [InlineData(SourceCodeKind.Script)] [WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37038, "https://github.com/dotnet/roslyn/issues/37038")] public async Task CommitGenericTypeParameterInUsingAliasContextShouldUseFullyQualifiedName(SourceCodeKind kind) { var file1 = @" namespace Foo { public class MyClass { } }"; var file2 = @" using CollectionOfStringBuilders = System.Collections.Generic.List<$$>"; var expectedCodeAfterCommit = @" using CollectionOfStringBuilders = System.Collections.Generic.List<Foo.MyClass$$>"; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); await VerifyCustomCommitProviderAsync(markup, "MyClass", expectedCodeAfterCommit, sourceCodeKind: kind); } [InlineData(SourceCodeKind.Regular)] [InlineData(SourceCodeKind.Script)] [WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37038, "https://github.com/dotnet/roslyn/issues/37038")] public async Task CommitGenericTypeParameterInUsingAliasContextShouldUseFullyQualifiedName2(SourceCodeKind kind) { var file1 = @" namespace Foo.Bar { public class MyClass { } }"; var file2 = @" namespace Foo { using CollectionOfStringBuilders = System.Collections.Generic.List<$$> }"; // Completion is not fully qualified var expectedCodeAfterCommit = @" namespace Foo { using CollectionOfStringBuilders = System.Collections.Generic.List<Foo.Bar.MyClass$$> }"; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); await VerifyCustomCommitProviderAsync(markup, "MyClass", expectedCodeAfterCommit, sourceCodeKind: kind); } [Fact] [Trait(Traits.Feature, Traits.Features.Completion)] [Trait(Traits.Feature, Traits.Features.Interactive)] [WorkItem(39027, "https://github.com/dotnet/roslyn/issues/39027")] public async Task TriggerCompletionInSubsequentSubmission() { var markup = @" <Workspace> <Submission Language=""C#"" CommonReferences=""true""> var x = ""10""; </Submission> <Submission Language=""C#"" CommonReferences=""true""> var y = $$ </Submission> </Workspace> "; var completionList = await GetCompletionListAsync(markup, workspaceKind: WorkspaceKind.Interactive).ConfigureAwait(false); Assert.NotEmpty(completionList.Items); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ShouldNotTriggerInsideTrivia() { var file1 = $@" namespace Foo {{ public class Bar {{}} }}"; var file2 = @" namespace Baz { /// <summary> /// <see cref=""B$$""/> /// </summary> class Bat { } }"; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar", inlineDescription: "Foo"); } private static void AssertRelativeOrder(List<string> expectedTypesInRelativeOrder, ImmutableArray<CompletionItem> allCompletionItems) { var hashset = new HashSet<string>(expectedTypesInRelativeOrder); var actualTypesInRelativeOrder = allCompletionItems.SelectAsArray(item => hashset.Contains(item.DisplayText), item => item.DisplayText); Assert.Equal(expectedTypesInRelativeOrder.Count, actualTypesInRelativeOrder.Length); for (var i = 0; i < expectedTypesInRelativeOrder.Count; ++i) { Assert.Equal(expectedTypesInRelativeOrder[i], actualTypesInRelativeOrder[i]); } } [InlineData(true)] [InlineData(false)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestBrowsableAwaysFromReferences(bool isProjectReference) { var srcDoc = @" class Program { void M() { $$ } }"; var refDoc = @" namespace Foo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public class Goo { } }"; var markup = isProjectReference switch { true => CreateMarkupForProjectWithProjectReference(srcDoc, refDoc, LanguageNames.CSharp, LanguageNames.CSharp), false => CreateMarkupForProjectWithMetadataReference(srcDoc, refDoc, LanguageNames.CSharp, LanguageNames.CSharp) }; await VerifyTypeImportItemExistsAsync( markup, "Goo", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo"); } [InlineData(true)] [InlineData(false)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestBrowsableNeverFromReferences(bool isProjectReference) { var srcDoc = @" class Program { void M() { $$ } }"; var refDoc = @" namespace Foo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public class Goo { } }"; var (markup, shouldContainItem) = isProjectReference switch { true => (CreateMarkupForProjectWithProjectReference(srcDoc, refDoc, LanguageNames.CSharp, LanguageNames.CSharp), true), false => (CreateMarkupForProjectWithMetadataReference(srcDoc, refDoc, LanguageNames.CSharp, LanguageNames.CSharp), false), }; if (shouldContainItem) { await VerifyTypeImportItemExistsAsync( markup, "Goo", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo"); } else { await VerifyTypeImportItemIsAbsentAsync( markup, "Goo", inlineDescription: "Foo"); } } [InlineData(true, true)] [InlineData(true, false)] [InlineData(false, true)] [InlineData(false, false)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestBrowsableAdvancedFromReferences(bool isProjectReference, bool hideAdvancedMembers) { HideAdvancedMembers = hideAdvancedMembers; var srcDoc = @" class Program { void M() { $$ } }"; var refDoc = @" namespace Foo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] public class Goo { } }"; var (markup, shouldContainItem) = isProjectReference switch { true => (CreateMarkupForProjectWithProjectReference(srcDoc, refDoc, LanguageNames.CSharp, LanguageNames.CSharp), true), false => (CreateMarkupForProjectWithMetadataReference(srcDoc, refDoc, LanguageNames.CSharp, LanguageNames.CSharp), !hideAdvancedMembers), }; if (shouldContainItem) { await VerifyTypeImportItemExistsAsync( markup, "Goo", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo"); } else { await VerifyTypeImportItemIsAbsentAsync( markup, "Goo", inlineDescription: "Foo"); } } [Theory, Trait(Traits.Feature, Traits.Features.Completion)] [InlineData('.')] [InlineData(';')] public async Task TestCommitWithCustomizedCommitCharForParameterlessConstructor(char commitChar) { var markup = @" namespace AA { public class C { } } namespace BB { public class B { public void M() { var c = new $$ } } }"; var expected = $@" using AA; namespace AA {{ public class C {{ }} }} namespace BB {{ public class B {{ public void M() {{ var c = new C(){commitChar} }} }} }}"; await VerifyProviderCommitAsync(markup, "C", expected, commitChar: commitChar, sourceCodeKind: SourceCodeKind.Regular); } [Theory, Trait(Traits.Feature, Traits.Features.Completion)] [InlineData('.')] [InlineData(';')] public async Task TestCommitWithCustomizedCommitCharUnderNonObjectCreationContext(char commitChar) { var markup = @" namespace AA { public class C { } } namespace BB { public class B { public void M() { $$ } } }"; var expected = $@" using AA; namespace AA {{ public class C {{ }} }} namespace BB {{ public class B {{ public void M() {{ C{commitChar} }} }} }}"; await VerifyProviderCommitAsync(markup, "C", expected, commitChar: commitChar, sourceCodeKind: SourceCodeKind.Regular); } [InlineData(SourceCodeKind.Regular)] [InlineData(SourceCodeKind.Script)] [WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(54493, "https://github.com/dotnet/roslyn/issues/54493")] public async Task CommitInLocalFunctionContext(SourceCodeKind kind) { var markup = @" namespace Foo { public class MyClass { } } namespace Test { class Program { public static void Main() { static $$ } } }"; var expectedCodeAfterCommit = @" using Foo; namespace Foo { public class MyClass { } } namespace Test { class Program { public static void Main() { static MyClass } } }"; await VerifyProviderCommitAsync(markup, "MyClass", expectedCodeAfterCommit, commitChar: null, sourceCodeKind: kind); } private Task VerifyTypeImportItemExistsAsync(string markup, string expectedItem, int glyph, string inlineDescription, string displayTextSuffix = null, string expectedDescriptionOrNull = null, CompletionItemFlags? flags = null) => VerifyItemExistsAsync(markup, expectedItem, displayTextSuffix: displayTextSuffix, glyph: glyph, inlineDescription: inlineDescription, expectedDescriptionOrNull: expectedDescriptionOrNull, isComplexTextEdit: true, flags: flags); private Task VerifyTypeImportItemIsAbsentAsync(string markup, string expectedItem, string inlineDescription, string displayTextSuffix = null) => VerifyItemIsAbsentAsync(markup, expectedItem, displayTextSuffix: displayTextSuffix, inlineDescription: inlineDescription); } }
-1
dotnet/roslyn
56,419
Fix partial method doc comments
Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
RikkiGibson
"2021-09-15T20:47:39Z"
"2021-09-21T23:49:10Z"
0f60b3e9446f5d0fc14a570998c81a5d6c40cc23
8cda7462843d43d9b72039eede2f4cb43126cac2
Fix partial method doc comments. Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
./src/Features/Core/Portable/RQName/Nodes/RQOutParameter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Features.RQName.SimpleTree; namespace Microsoft.CodeAnalysis.Features.RQName.Nodes { internal class RQOutParameter : RQParameter { public RQOutParameter(RQType type) : base(type) { } public override SimpleTreeNode CreateSimpleTreeForType() => new SimpleGroupNode(RQNameStrings.ParamMod, new SimpleLeafNode(RQNameStrings.Out), Type.ToSimpleTree()); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Features.RQName.SimpleTree; namespace Microsoft.CodeAnalysis.Features.RQName.Nodes { internal class RQOutParameter : RQParameter { public RQOutParameter(RQType type) : base(type) { } public override SimpleTreeNode CreateSimpleTreeForType() => new SimpleGroupNode(RQNameStrings.ParamMod, new SimpleLeafNode(RQNameStrings.Out), Type.ToSimpleTree()); } }
-1
dotnet/roslyn
56,419
Fix partial method doc comments
Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
RikkiGibson
"2021-09-15T20:47:39Z"
"2021-09-21T23:49:10Z"
0f60b3e9446f5d0fc14a570998c81a5d6c40cc23
8cda7462843d43d9b72039eede2f4cb43126cac2
Fix partial method doc comments. Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
./src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_IPointerIndirectionReferenceOperation.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.Semantic.UnitTests.IOperation { public class IOperationTests_IPointerIndirectionReferenceOperation : SemanticModelTestBase { //Currently, we are not creating the IPointerIndirectionReferenceOperation node [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void PointerIndirectionFlow_01() { string source = @" class C { unsafe static void M(S s, S* sp) /*<bind>*/ { s = *sp; }/*</bind>*/ struct S { } } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 's = *sp;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C.S) (Syntax: 's = *sp') Left: IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: C.S) (Syntax: 's') Right: IOperation: (OperationKind.None, Type: null) (Syntax: '*sp') Children(1): IParameterReferenceOperation: sp (OperationKind.ParameterReference, Type: C.S*) (Syntax: 'sp') Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics, compilationOptions: TestOptions.UnsafeDebugDll); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void PointerIndirectionFlow_02() { string source = @" class C { unsafe static void M(S* sp, int i) /*<bind>*/ { sp->x = 1; i = sp->x; }/*</bind>*/ struct S { public int x; } } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'sp->x = 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'sp->x = 1') Left: IFieldReferenceOperation: System.Int32 C.S.x (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'sp->x') Instance Receiver: IOperation: (OperationKind.None, Type: null, IsImplicit) (Syntax: 'sp') Children(1): IParameterReferenceOperation: sp (OperationKind.ParameterReference, Type: C.S*) (Syntax: 'sp') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i = sp->x;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i = sp->x') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') Right: IFieldReferenceOperation: System.Int32 C.S.x (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'sp->x') Instance Receiver: IOperation: (OperationKind.None, Type: null, IsImplicit) (Syntax: 'sp') Children(1): IParameterReferenceOperation: sp (OperationKind.ParameterReference, Type: C.S*) (Syntax: 'sp') Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics, compilationOptions: TestOptions.UnsafeDebugDll); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.Semantic.UnitTests.IOperation { public class IOperationTests_IPointerIndirectionReferenceOperation : SemanticModelTestBase { //Currently, we are not creating the IPointerIndirectionReferenceOperation node [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void PointerIndirectionFlow_01() { string source = @" class C { unsafe static void M(S s, S* sp) /*<bind>*/ { s = *sp; }/*</bind>*/ struct S { } } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 's = *sp;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C.S) (Syntax: 's = *sp') Left: IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: C.S) (Syntax: 's') Right: IOperation: (OperationKind.None, Type: null) (Syntax: '*sp') Children(1): IParameterReferenceOperation: sp (OperationKind.ParameterReference, Type: C.S*) (Syntax: 'sp') Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics, compilationOptions: TestOptions.UnsafeDebugDll); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void PointerIndirectionFlow_02() { string source = @" class C { unsafe static void M(S* sp, int i) /*<bind>*/ { sp->x = 1; i = sp->x; }/*</bind>*/ struct S { public int x; } } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'sp->x = 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'sp->x = 1') Left: IFieldReferenceOperation: System.Int32 C.S.x (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'sp->x') Instance Receiver: IOperation: (OperationKind.None, Type: null, IsImplicit) (Syntax: 'sp') Children(1): IParameterReferenceOperation: sp (OperationKind.ParameterReference, Type: C.S*) (Syntax: 'sp') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i = sp->x;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i = sp->x') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') Right: IFieldReferenceOperation: System.Int32 C.S.x (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'sp->x') Instance Receiver: IOperation: (OperationKind.None, Type: null, IsImplicit) (Syntax: 'sp') Children(1): IParameterReferenceOperation: sp (OperationKind.ParameterReference, Type: C.S*) (Syntax: 'sp') Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics, compilationOptions: TestOptions.UnsafeDebugDll); } } }
-1
dotnet/roslyn
56,419
Fix partial method doc comments
Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
RikkiGibson
"2021-09-15T20:47:39Z"
"2021-09-21T23:49:10Z"
0f60b3e9446f5d0fc14a570998c81a5d6c40cc23
8cda7462843d43d9b72039eede2f4cb43126cac2
Fix partial method doc comments. Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
./src/EditorFeatures/Core/Implementation/NavigationBar/NavigationBarControllerFactoryService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.ComponentModel.Composition; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.NavigationBar { [Export(typeof(INavigationBarControllerFactoryService))] internal class NavigationBarControllerFactoryService : INavigationBarControllerFactoryService { private readonly IThreadingContext _threadingContext; private readonly IUIThreadOperationExecutor _uIThreadOperationExecutor; private readonly IAsynchronousOperationListener _asyncListener; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public NavigationBarControllerFactoryService( IThreadingContext threadingContext, IUIThreadOperationExecutor uIThreadOperationExecutor, IAsynchronousOperationListenerProvider listenerProvider) { _threadingContext = threadingContext; _uIThreadOperationExecutor = uIThreadOperationExecutor; _asyncListener = listenerProvider.GetListener(FeatureAttribute.NavigationBar); } public IDisposable CreateController(INavigationBarPresenter presenter, ITextBuffer textBuffer) { return new NavigationBarController( _threadingContext, presenter, textBuffer, _uIThreadOperationExecutor, _asyncListener); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.ComponentModel.Composition; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.NavigationBar { [Export(typeof(INavigationBarControllerFactoryService))] internal class NavigationBarControllerFactoryService : INavigationBarControllerFactoryService { private readonly IThreadingContext _threadingContext; private readonly IUIThreadOperationExecutor _uIThreadOperationExecutor; private readonly IAsynchronousOperationListener _asyncListener; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public NavigationBarControllerFactoryService( IThreadingContext threadingContext, IUIThreadOperationExecutor uIThreadOperationExecutor, IAsynchronousOperationListenerProvider listenerProvider) { _threadingContext = threadingContext; _uIThreadOperationExecutor = uIThreadOperationExecutor; _asyncListener = listenerProvider.GetListener(FeatureAttribute.NavigationBar); } public IDisposable CreateController(INavigationBarPresenter presenter, ITextBuffer textBuffer) { return new NavigationBarController( _threadingContext, presenter, textBuffer, _uIThreadOperationExecutor, _asyncListener); } } }
-1
dotnet/roslyn
56,419
Fix partial method doc comments
Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
RikkiGibson
"2021-09-15T20:47:39Z"
"2021-09-21T23:49:10Z"
0f60b3e9446f5d0fc14a570998c81a5d6c40cc23
8cda7462843d43d9b72039eede2f4cb43126cac2
Fix partial method doc comments. Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
./src/Features/Core/Portable/ExtractInterface/ExtractInterfaceOptionsResult.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.ExtractInterface { internal class ExtractInterfaceOptionsResult { public enum ExtractLocation { SameFile, NewFile } public static readonly ExtractInterfaceOptionsResult Cancelled = new(isCancelled: true); public bool IsCancelled { get; } public ImmutableArray<ISymbol> IncludedMembers { get; } public string InterfaceName { get; } public string FileName { get; } public ExtractLocation Location { get; } public ExtractInterfaceOptionsResult(bool isCancelled, ImmutableArray<ISymbol> includedMembers, string interfaceName, string fileName, ExtractLocation location) { IsCancelled = isCancelled; IncludedMembers = includedMembers; InterfaceName = interfaceName; Location = location; FileName = fileName; } private ExtractInterfaceOptionsResult(bool isCancelled) => IsCancelled = isCancelled; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.ExtractInterface { internal class ExtractInterfaceOptionsResult { public enum ExtractLocation { SameFile, NewFile } public static readonly ExtractInterfaceOptionsResult Cancelled = new(isCancelled: true); public bool IsCancelled { get; } public ImmutableArray<ISymbol> IncludedMembers { get; } public string InterfaceName { get; } public string FileName { get; } public ExtractLocation Location { get; } public ExtractInterfaceOptionsResult(bool isCancelled, ImmutableArray<ISymbol> includedMembers, string interfaceName, string fileName, ExtractLocation location) { IsCancelled = isCancelled; IncludedMembers = includedMembers; InterfaceName = interfaceName; Location = location; FileName = fileName; } private ExtractInterfaceOptionsResult(bool isCancelled) => IsCancelled = isCancelled; } }
-1
dotnet/roslyn
56,419
Fix partial method doc comments
Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
RikkiGibson
"2021-09-15T20:47:39Z"
"2021-09-21T23:49:10Z"
0f60b3e9446f5d0fc14a570998c81a5d6c40cc23
8cda7462843d43d9b72039eede2f4cb43126cac2
Fix partial method doc comments. Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
./src/Compilers/CSharp/Test/Symbol/Symbols/CompilationCreationTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Text; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using static Roslyn.Test.Utilities.TestMetadata; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class CompilationCreationTests : CSharpTestBase { #region Helpers private static SyntaxTree CreateSyntaxTree(string className) { var text = string.Format("public partial class {0} {{ }}", className); var path = string.Format("{0}.cs", className); return SyntaxFactory.ParseSyntaxTree(text, path: path); } private static void CheckCompilationSyntaxTrees(CSharpCompilation compilation, params SyntaxTree[] expectedSyntaxTrees) { ImmutableArray<SyntaxTree> actualSyntaxTrees = compilation.SyntaxTrees; int numTrees = expectedSyntaxTrees.Length; Assert.Equal(numTrees, actualSyntaxTrees.Length); for (int i = 0; i < numTrees; i++) { Assert.Equal(expectedSyntaxTrees[i], actualSyntaxTrees[i]); } for (int i = 0; i < numTrees; i++) { for (int j = 0; j < numTrees; j++) { Assert.Equal(Math.Sign(compilation.CompareSyntaxTreeOrdering(expectedSyntaxTrees[i], expectedSyntaxTrees[j])), Math.Sign(i.CompareTo(j))); } } var types = expectedSyntaxTrees.Select(tree => compilation.GetSemanticModel(tree).GetDeclaredSymbol(tree.GetCompilationUnitRoot().Members.Single())).ToArray(); for (int i = 0; i < numTrees; i++) { for (int j = 0; j < numTrees; j++) { Assert.Equal(Math.Sign(compilation.CompareSourceLocations(types[i].Locations[0], types[j].Locations[0])), Math.Sign(i.CompareTo(j))); } } } #endregion [Fact] public void CorLibTypes() { var mdTestLib1 = TestReferences.SymbolsTests.MDTestLib1; var c1 = CSharpCompilation.Create("Test", references: new MetadataReference[] { MscorlibRef_v4_0_30316_17626, mdTestLib1 }); TypeSymbol c107 = c1.GlobalNamespace.GetTypeMembers("C107").Single(); Assert.Equal(SpecialType.None, c107.SpecialType); for (int i = 1; i <= (int)SpecialType.Count; i++) { NamedTypeSymbol type = c1.GetSpecialType((SpecialType)i); if (i == (int)SpecialType.System_Runtime_CompilerServices_RuntimeFeature || i == (int)SpecialType.System_Runtime_CompilerServices_PreserveBaseOverridesAttribute) { Assert.True(type.IsErrorType()); // Not available } else { Assert.False(type.IsErrorType()); } Assert.Equal((SpecialType)i, type.SpecialType); } Assert.Equal(SpecialType.None, c107.SpecialType); var arrayOfc107 = ArrayTypeSymbol.CreateCSharpArray(c1.Assembly, TypeWithAnnotations.Create(c107)); Assert.Equal(SpecialType.None, arrayOfc107.SpecialType); var c2 = CSharpCompilation.Create("Test", references: new[] { mdTestLib1 }); Assert.Equal(SpecialType.None, c2.GlobalNamespace.GetTypeMembers("C107").Single().SpecialType); } [Fact] public void CyclicReference() { var mscorlibRef = Net451.mscorlib; var cyclic2Ref = TestReferences.SymbolsTests.Cyclic.Cyclic2.dll; var tc1 = CSharpCompilation.Create("Cyclic1", references: new[] { mscorlibRef, cyclic2Ref }); Assert.NotNull(tc1.Assembly); // force creation of SourceAssemblySymbol var cyclic1Asm = (SourceAssemblySymbol)tc1.Assembly; var cyclic1Mod = (SourceModuleSymbol)cyclic1Asm.Modules[0]; var cyclic2Asm = (PEAssemblySymbol)tc1.GetReferencedAssemblySymbol(cyclic2Ref); var cyclic2Mod = (PEModuleSymbol)cyclic2Asm.Modules[0]; Assert.Same(cyclic2Mod.GetReferencedAssemblySymbols()[1], cyclic1Asm); Assert.Same(cyclic1Mod.GetReferencedAssemblySymbols()[1], cyclic2Asm); } [Fact] public void MultiTargeting1() { var varV1MTTestLib2Ref = TestReferences.SymbolsTests.V1.MTTestLib2.dll; var asm1 = MetadataTestHelpers.GetSymbolsForReferences(mrefs: new[] { Net451.mscorlib, varV1MTTestLib2Ref }); Assert.Equal("mscorlib", asm1[0].Identity.Name); Assert.Equal(0, asm1[0].BoundReferences().Length); Assert.Equal("MTTestLib2", asm1[1].Identity.Name); Assert.Equal(1, (from a in asm1[1].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm1[1].BoundReferences() where object.ReferenceEquals(a, asm1[0]) select a).Count()); Assert.Equal(SymbolKind.ErrorType, asm1[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Foo").OfType<MethodSymbol>().Single().ReturnType.Kind); var asm2 = MetadataTestHelpers.GetSymbolsForReferences(new[] { Net451.mscorlib, varV1MTTestLib2Ref, TestReferences.SymbolsTests.V1.MTTestLib1.dll }); Assert.Same(asm2[0], asm1[0]); Assert.Equal("MTTestLib2", asm2[1].Identity.Name); Assert.NotSame(asm2[1], asm1[1]); Assert.Same(((PEAssemblySymbol)asm2[1]).Assembly, ((PEAssemblySymbol)asm1[1]).Assembly); Assert.Equal(2, (from a in asm2[1].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm2[1].BoundReferences() where object.ReferenceEquals(a, asm2[0]) select a).Count()); Assert.Equal(1, (from a in asm2[1].BoundReferences() where object.ReferenceEquals(a, asm2[2]) select a).Count()); var retval1 = asm2[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Foo").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval1.Kind); Assert.Same(retval1, asm2[2].GlobalNamespace.GetMembers("Class1").Single()); Assert.Equal("MTTestLib1", asm2[2].Identity.Name); Assert.Equal(1, asm2[2].Identity.Version.Major); Assert.Equal(1, (from a in asm2[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm2[2].BoundReferences() where object.ReferenceEquals(a, asm2[0]) select a).Count()); var varV2MTTestLib3Ref = TestReferences.SymbolsTests.V2.MTTestLib3.dll; var asm3 = MetadataTestHelpers.GetSymbolsForReferences(new[] { Net451.mscorlib, varV1MTTestLib2Ref, TestReferences.SymbolsTests.V2.MTTestLib1.dll, varV2MTTestLib3Ref }); Assert.Same(asm3[0], asm1[0]); Assert.Equal("MTTestLib2", asm3[1].Identity.Name); Assert.NotSame(asm3[1], asm1[1]); Assert.NotSame(asm3[1], asm2[1]); Assert.Same(((PEAssemblySymbol)asm3[1]).Assembly, ((PEAssemblySymbol)asm1[1]).Assembly); Assert.Equal(2, (from a in asm3[1].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm3[1].BoundReferences() where object.ReferenceEquals(a, asm3[0]) select a).Count()); Assert.Equal(1, (from a in asm3[1].BoundReferences() where object.ReferenceEquals(a, asm3[2]) select a).Count()); var retval2 = asm3[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Foo").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval2.Kind); Assert.Same(retval2, asm3[2].GlobalNamespace.GetMembers("Class1").Single()); Assert.Equal("MTTestLib1", asm3[2].Identity.Name); Assert.NotSame(asm3[2], asm2[2]); Assert.NotSame(((PEAssemblySymbol)asm3[2]).Assembly, ((PEAssemblySymbol)asm2[2]).Assembly); Assert.Equal(2, asm3[2].Identity.Version.Major); Assert.Equal(1, (from a in asm3[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm3[2].BoundReferences() where object.ReferenceEquals(a, asm3[0]) select a).Count()); Assert.Equal("MTTestLib3", asm3[3].Identity.Name); Assert.Equal(3, (from a in asm3[3].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm3[3].BoundReferences() where object.ReferenceEquals(a, asm3[0]) select a).Count()); Assert.Equal(1, (from a in asm3[3].BoundReferences() where object.ReferenceEquals(a, asm3[1]) select a).Count()); Assert.Equal(1, (from a in asm3[3].BoundReferences() where object.ReferenceEquals(a, asm3[2]) select a).Count()); var type1 = asm3[3].GlobalNamespace.GetTypeMembers("Class5"). Single(); var retval3 = type1.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval3.Kind); Assert.Same(retval3, asm3[2].GlobalNamespace.GetMembers("Class1").Single()); var retval4 = type1.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval4.Kind); Assert.Same(retval4, asm3[2].GlobalNamespace.GetMembers("Class2").Single()); var retval5 = type1.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval5.Kind); Assert.Same(retval5, asm3[1].GlobalNamespace.GetMembers("Class4").Single()); var varV3MTTestLib4Ref = TestReferences.SymbolsTests.V3.MTTestLib4.dll; var asm4 = MetadataTestHelpers.GetSymbolsForReferences(new MetadataReference[] { Net451.mscorlib, varV1MTTestLib2Ref, TestReferences.SymbolsTests.V3.MTTestLib1.dll, varV2MTTestLib3Ref, varV3MTTestLib4Ref }); Assert.Same(asm3[0], asm1[0]); Assert.Equal("MTTestLib2", asm4[1].Identity.Name); Assert.NotSame(asm4[1], asm1[1]); Assert.NotSame(asm4[1], asm2[1]); Assert.NotSame(asm4[1], asm3[1]); Assert.Same(((PEAssemblySymbol)asm4[1]).Assembly, ((PEAssemblySymbol)asm1[1]).Assembly); Assert.Equal(2, (from a in asm4[1].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm4[1].BoundReferences() where object.ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal(1, (from a in asm4[1].BoundReferences() where object.ReferenceEquals(a, asm4[2]) select a).Count()); var retval6 = asm4[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Foo").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval6.Kind); Assert.Same(retval6, asm4[2].GlobalNamespace.GetMembers("Class1").Single()); Assert.Equal("MTTestLib1", asm4[2].Identity.Name); Assert.NotSame(asm4[2], asm2[2]); Assert.NotSame(asm4[2], asm3[2]); Assert.NotSame(((PEAssemblySymbol)asm4[2]).Assembly, ((PEAssemblySymbol)asm2[2]).Assembly); Assert.NotSame(((PEAssemblySymbol)asm4[2]).Assembly, ((PEAssemblySymbol)asm3[2]).Assembly); Assert.Equal(3, asm4[2].Identity.Version.Major); Assert.Equal(1, (from a in asm4[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm4[2].BoundReferences() where object.ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal("MTTestLib3", asm4[3].Identity.Name); Assert.NotSame(asm4[3], asm3[3]); Assert.Same(((PEAssemblySymbol)asm4[3]).Assembly, ((PEAssemblySymbol)asm3[3]).Assembly); Assert.Equal(3, (from a in asm4[3].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm4[3].BoundReferences() where object.ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal(1, (from a in asm4[3].BoundReferences() where object.ReferenceEquals(a, asm4[1]) select a).Count()); Assert.Equal(1, (from a in asm4[3].BoundReferences() where object.ReferenceEquals(a, asm4[2]) select a).Count()); var type2 = asm4[3].GlobalNamespace.GetTypeMembers("Class5"). Single(); var retval7 = type2.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval7.Kind); Assert.Same(retval7, asm4[2].GlobalNamespace.GetMembers("Class1").Single()); var retval8 = type2.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval8.Kind); Assert.Same(retval8, asm4[2].GlobalNamespace.GetMembers("Class2").Single()); var retval9 = type2.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval9.Kind); Assert.Same(retval9, asm4[1].GlobalNamespace.GetMembers("Class4").Single()); Assert.Equal("MTTestLib4", asm4[4].Identity.Name); Assert.Equal(4, (from a in asm4[4].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm4[4].BoundReferences() where object.ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal(1, (from a in asm4[4].BoundReferences() where object.ReferenceEquals(a, asm4[1]) select a).Count()); Assert.Equal(1, (from a in asm4[4].BoundReferences() where object.ReferenceEquals(a, asm4[2]) select a).Count()); Assert.Equal(1, (from a in asm4[4].BoundReferences() where object.ReferenceEquals(a, asm4[3]) select a).Count()); var type3 = asm4[4].GlobalNamespace.GetTypeMembers("Class6"). Single(); var retval10 = type3.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval10.Kind); Assert.Same(retval10, asm4[2].GlobalNamespace.GetMembers("Class1").Single()); var retval11 = type3.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval11.Kind); Assert.Same(retval11, asm4[2].GlobalNamespace.GetMembers("Class2").Single()); var retval12 = type3.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval12.Kind); Assert.Same(retval12, asm4[2].GlobalNamespace.GetMembers("Class3").Single()); var retval13 = type3.GetMembers("Foo4").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval13.Kind); Assert.Same(retval13, asm4[1].GlobalNamespace.GetMembers("Class4").Single()); var retval14 = type3.GetMembers("Foo5").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval14.Kind); Assert.Same(retval14, asm4[3].GlobalNamespace.GetMembers("Class5").Single()); var asm5 = MetadataTestHelpers.GetSymbolsForReferences(new[] { Net451.mscorlib, varV2MTTestLib3Ref }); Assert.Same(asm5[0], asm1[0]); Assert.True(asm5[1].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(asm3[3])); var asm6 = MetadataTestHelpers.GetSymbolsForReferences(new[] { Net451.mscorlib, varV1MTTestLib2Ref }); Assert.Same(asm6[0], asm1[0]); Assert.Same(asm6[1], asm1[1]); var asm7 = MetadataTestHelpers.GetSymbolsForReferences(new[] { Net451.mscorlib, varV1MTTestLib2Ref, varV2MTTestLib3Ref, varV3MTTestLib4Ref }); Assert.Same(asm7[0], asm1[0]); Assert.Same(asm7[1], asm1[1]); Assert.NotSame(asm7[2], asm3[3]); Assert.NotSame(asm7[2], asm4[3]); Assert.NotSame(asm7[3], asm4[4]); Assert.Equal("MTTestLib3", asm7[2].Identity.Name); Assert.Same(((PEAssemblySymbol)asm7[2]).Assembly, ((PEAssemblySymbol)asm3[3]).Assembly); Assert.Equal(2, (from a in asm7[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm7[2].BoundReferences() where object.ReferenceEquals(a, asm7[0]) select a).Count()); Assert.Equal(1, (from a in asm7[2].BoundReferences() where object.ReferenceEquals(a, asm7[1]) select a).Count()); var type4 = asm7[2].GlobalNamespace.GetTypeMembers("Class5"). Single(); var retval15 = type4.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal(SymbolKind.ErrorType, retval15.Kind); var retval16 = type4.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal(SymbolKind.ErrorType, retval16.Kind); var retval17 = type4.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval17.Kind); Assert.Same(retval17, asm7[1].GlobalNamespace.GetMembers("Class4").Single()); Assert.Equal("MTTestLib4", asm7[3].Identity.Name); Assert.Same(((PEAssemblySymbol)asm7[3]).Assembly, ((PEAssemblySymbol)asm4[4]).Assembly); Assert.Equal(3, (from a in asm7[3].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm7[3].BoundReferences() where object.ReferenceEquals(a, asm7[0]) select a).Count()); Assert.Equal(1, (from a in asm7[3].BoundReferences() where object.ReferenceEquals(a, asm7[1]) select a).Count()); Assert.Equal(1, (from a in asm7[3].BoundReferences() where object.ReferenceEquals(a, asm7[2]) select a).Count()); var type5 = asm7[3].GlobalNamespace.GetTypeMembers("Class6"). Single(); var retval18 = type5.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal(SymbolKind.ErrorType, retval18.Kind); var retval19 = type5.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal(SymbolKind.ErrorType, retval19.Kind); var retval20 = type5.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal(SymbolKind.ErrorType, retval20.Kind); var retval21 = type5.GetMembers("Foo4").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval21.Kind); Assert.Same(retval21, asm7[1].GlobalNamespace.GetMembers("Class4").Single()); var retval22 = type5.GetMembers("Foo5").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval22.Kind); Assert.Same(retval22, asm7[2].GlobalNamespace.GetMembers("Class5").Single()); // This test shows that simple reordering of references doesn't pick different set of assemblies var asm8 = MetadataTestHelpers.GetSymbolsForReferences(new[] { Net451.mscorlib, varV3MTTestLib4Ref, varV1MTTestLib2Ref, varV2MTTestLib3Ref }); Assert.Same(asm8[0], asm1[0]); Assert.Same(asm8[0], asm1[0]); Assert.Same(asm8[2], asm7[1]); Assert.True(asm8[3].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(asm4[3])); Assert.Same(asm8[3], asm7[2]); Assert.True(asm8[1].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(asm4[4])); Assert.Same(asm8[1], asm7[3]); var asm9 = MetadataTestHelpers.GetSymbolsForReferences(new[] { Net451.mscorlib, varV3MTTestLib4Ref }); Assert.Same(asm9[0], asm1[0]); Assert.True(asm9[1].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(asm4[4])); var asm10 = MetadataTestHelpers.GetSymbolsForReferences(new[] { Net451.mscorlib, varV1MTTestLib2Ref, TestReferences.SymbolsTests.V3.MTTestLib1.dll, varV2MTTestLib3Ref, varV3MTTestLib4Ref }); Assert.Same(asm10[0], asm1[0]); Assert.Same(asm10[1], asm4[1]); Assert.Same(asm10[2], asm4[2]); Assert.Same(asm10[3], asm4[3]); Assert.Same(asm10[4], asm4[4]); // Run the same tests again to make sure we didn't corrupt prior state by loading additional assemblies Assert.Equal("MTTestLib2", asm1[1].Identity.Name); Assert.Equal(1, (from a in asm1[1].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm1[1].BoundReferences() where ReferenceEquals(a, asm1[0]) select a).Count()); Assert.Equal(SymbolKind.ErrorType, asm1[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Foo").OfType<MethodSymbol>().Single().ReturnType.Kind); Assert.Same(asm2[0], asm1[0]); Assert.Equal("MTTestLib2", asm2[1].Identity.Name); Assert.NotSame(asm2[1], asm1[1]); Assert.Same(((PEAssemblySymbol)asm2[1]).Assembly, ((PEAssemblySymbol)asm1[1]).Assembly); Assert.Equal(2, (from a in asm2[1].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm2[1].BoundReferences() where ReferenceEquals(a, asm2[0]) select a).Count()); Assert.Equal(1, (from a in asm2[1].BoundReferences() where ReferenceEquals(a, asm2[2]) select a).Count()); retval1 = asm2[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Foo").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval1.Kind); Assert.Same(retval1, asm2[2].GlobalNamespace.GetMembers("Class1").Single()); Assert.Equal("MTTestLib1", asm2[2].Identity.Name); Assert.Equal(1, asm2[2].Identity.Version.Major); Assert.Equal(1, (from a in asm2[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm2[2].BoundReferences() where ReferenceEquals(a, asm2[0]) select a).Count()); Assert.Same(asm3[0], asm1[0]); Assert.Equal("MTTestLib2", asm3[1].Identity.Name); Assert.NotSame(asm3[1], asm1[1]); Assert.NotSame(asm3[1], asm2[1]); Assert.Same(((PEAssemblySymbol)asm3[1]).Assembly, ((PEAssemblySymbol)asm1[1]).Assembly); Assert.Equal(2, (from a in asm3[1].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm3[1].BoundReferences() where ReferenceEquals(a, asm3[0]) select a).Count()); Assert.Equal(1, (from a in asm3[1].BoundReferences() where ReferenceEquals(a, asm3[2]) select a).Count()); retval2 = asm3[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Foo").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval2.Kind); Assert.Same(retval2, asm3[2].GlobalNamespace.GetMembers("Class1").Single()); Assert.Equal("MTTestLib1", asm3[2].Identity.Name); Assert.NotSame(asm3[2], asm2[2]); Assert.NotSame(((PEAssemblySymbol)asm3[2]).Assembly, ((PEAssemblySymbol)asm2[2]).Assembly); Assert.Equal(2, asm3[2].Identity.Version.Major); Assert.Equal(1, (from a in asm3[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm3[2].BoundReferences() where ReferenceEquals(a, asm3[0]) select a).Count()); Assert.Equal("MTTestLib3", asm3[3].Identity.Name); Assert.Equal(3, (from a in asm3[3].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm3[3].BoundReferences() where ReferenceEquals(a, asm3[0]) select a).Count()); Assert.Equal(1, (from a in asm3[3].BoundReferences() where ReferenceEquals(a, asm3[1]) select a).Count()); Assert.Equal(1, (from a in asm3[3].BoundReferences() where ReferenceEquals(a, asm3[2]) select a).Count()); type1 = asm3[3].GlobalNamespace.GetTypeMembers("Class5"). Single(); retval3 = type1.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval3.Kind); Assert.Same(retval3, asm3[2].GlobalNamespace.GetMembers("Class1").Single()); retval4 = type1.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval4.Kind); Assert.Same(retval4, asm3[2].GlobalNamespace.GetMembers("Class2").Single()); retval5 = type1.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval5.Kind); Assert.Same(retval5, asm3[1].GlobalNamespace.GetMembers("Class4").Single()); Assert.Same(asm3[0], asm1[0]); Assert.Equal("MTTestLib2", asm4[1].Identity.Name); Assert.NotSame(asm4[1], asm1[1]); Assert.NotSame(asm4[1], asm2[1]); Assert.NotSame(asm4[1], asm3[1]); Assert.Same(((PEAssemblySymbol)asm4[1]).Assembly, ((PEAssemblySymbol)asm1[1]).Assembly); Assert.Equal(2, (from a in asm4[1].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm4[1].BoundReferences() where ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal(1, (from a in asm4[1].BoundReferences() where ReferenceEquals(a, asm4[2]) select a).Count()); retval6 = asm4[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Foo").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval6.Kind); Assert.Same(retval6, asm4[2].GlobalNamespace.GetMembers("Class1").Single()); Assert.Equal("MTTestLib1", asm4[2].Identity.Name); Assert.NotSame(asm4[2], asm2[2]); Assert.NotSame(asm4[2], asm3[2]); Assert.NotSame(((PEAssemblySymbol)asm4[2]).Assembly, ((PEAssemblySymbol)asm2[2]).Assembly); Assert.NotSame(((PEAssemblySymbol)asm4[2]).Assembly, ((PEAssemblySymbol)asm3[2]).Assembly); Assert.Equal(3, asm4[2].Identity.Version.Major); Assert.Equal(1, (from a in asm4[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm4[2].BoundReferences() where ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal("MTTestLib3", asm4[3].Identity.Name); Assert.NotSame(asm4[3], asm3[3]); Assert.Same(((PEAssemblySymbol)asm4[3]).Assembly, ((PEAssemblySymbol)asm3[3]).Assembly); Assert.Equal(3, (from a in asm4[3].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm4[3].BoundReferences() where ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal(1, (from a in asm4[3].BoundReferences() where ReferenceEquals(a, asm4[1]) select a).Count()); Assert.Equal(1, (from a in asm4[3].BoundReferences() where ReferenceEquals(a, asm4[2]) select a).Count()); type2 = asm4[3].GlobalNamespace.GetTypeMembers("Class5"). Single(); retval7 = type2.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval7.Kind); Assert.Same(retval7, asm4[2].GlobalNamespace.GetMembers("Class1").Single()); retval8 = type2.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval8.Kind); Assert.Same(retval8, asm4[2].GlobalNamespace.GetMembers("Class2").Single()); retval9 = type2.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval9.Kind); Assert.Same(retval9, asm4[1].GlobalNamespace.GetMembers("Class4").Single()); Assert.Equal("MTTestLib4", asm4[4].Identity.Name); Assert.Equal(4, (from a in asm4[4].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm4[4].BoundReferences() where ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal(1, (from a in asm4[4].BoundReferences() where ReferenceEquals(a, asm4[1]) select a).Count()); Assert.Equal(1, (from a in asm4[4].BoundReferences() where ReferenceEquals(a, asm4[2]) select a).Count()); Assert.Equal(1, (from a in asm4[4].BoundReferences() where ReferenceEquals(a, asm4[3]) select a).Count()); type3 = asm4[4].GlobalNamespace.GetTypeMembers("Class6"). Single(); retval10 = type3.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval10.Kind); Assert.Same(retval10, asm4[2].GlobalNamespace.GetMembers("Class1").Single()); retval11 = type3.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval11.Kind); Assert.Same(retval11, asm4[2].GlobalNamespace.GetMembers("Class2").Single()); retval12 = type3.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval12.Kind); Assert.Same(retval12, asm4[2].GlobalNamespace.GetMembers("Class3").Single()); retval13 = type3.GetMembers("Foo4").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval13.Kind); Assert.Same(retval13, asm4[1].GlobalNamespace.GetMembers("Class4").Single()); retval14 = type3.GetMembers("Foo5").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval14.Kind); Assert.Same(retval14, asm4[3].GlobalNamespace.GetMembers("Class5").Single()); Assert.Same(asm7[0], asm1[0]); Assert.Same(asm7[1], asm1[1]); Assert.NotSame(asm7[2], asm3[3]); Assert.NotSame(asm7[2], asm4[3]); Assert.NotSame(asm7[3], asm4[4]); Assert.Equal("MTTestLib3", asm7[2].Identity.Name); Assert.Same(((PEAssemblySymbol)asm7[2]).Assembly, ((PEAssemblySymbol)asm3[3]).Assembly); Assert.Equal(2, (from a in asm7[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm7[2].BoundReferences() where ReferenceEquals(a, asm7[0]) select a).Count()); Assert.Equal(1, (from a in asm7[2].BoundReferences() where ReferenceEquals(a, asm7[1]) select a).Count()); type4 = asm7[2].GlobalNamespace.GetTypeMembers("Class5"). Single(); retval15 = type4.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal(SymbolKind.ErrorType, retval15.Kind); retval16 = type4.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal(SymbolKind.ErrorType, retval16.Kind); retval17 = type4.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval17.Kind); Assert.Same(retval17, asm7[1].GlobalNamespace.GetMembers("Class4").Single()); Assert.Equal("MTTestLib4", asm7[3].Identity.Name); Assert.Same(((PEAssemblySymbol)asm7[3]).Assembly, ((PEAssemblySymbol)asm4[4]).Assembly); Assert.Equal(3, (from a in asm7[3].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm7[3].BoundReferences() where ReferenceEquals(a, asm7[0]) select a).Count()); Assert.Equal(1, (from a in asm7[3].BoundReferences() where ReferenceEquals(a, asm7[1]) select a).Count()); Assert.Equal(1, (from a in asm7[3].BoundReferences() where ReferenceEquals(a, asm7[2]) select a).Count()); type5 = asm7[3].GlobalNamespace.GetTypeMembers("Class6"). Single(); retval18 = type5.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal(SymbolKind.ErrorType, retval18.Kind); retval19 = type5.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal(SymbolKind.ErrorType, retval19.Kind); retval20 = type5.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal(SymbolKind.ErrorType, retval20.Kind); retval21 = type5.GetMembers("Foo4").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval21.Kind); Assert.Same(retval21, asm7[1].GlobalNamespace.GetMembers("Class4").Single()); retval22 = type5.GetMembers("Foo5").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval22.Kind); Assert.Same(retval22, asm7[2].GlobalNamespace.GetMembers("Class5").Single()); } [Fact] public void MultiTargeting2() { var varMTTestLib1_V1_Name = new AssemblyIdentity("MTTestLib1", new Version("1.0.0.0")); var varC_MTTestLib1_V1 = CreateCompilation(varMTTestLib1_V1_Name, new string[] { // AssemblyPaths.SymbolsTests.V1.MTTestModule1.netmodule @" public class Class1 { } " }, new[] { Net451.mscorlib }); var asm_MTTestLib1_V1 = varC_MTTestLib1_V1.SourceAssembly().BoundReferences(); var varMTTestLib2_Name = new AssemblyIdentity("MTTestLib2"); var varC_MTTestLib2 = CreateCompilation(varMTTestLib2_Name, new string[] { // AssemblyPaths.SymbolsTests.V1.MTTestModule2.netmodule @" public class Class4 { Class1 Foo() { return null; } public Class1 Bar; } " }, new MetadataReference[] { Net451.mscorlib, varC_MTTestLib1_V1.ToMetadataReference() }); var asm_MTTestLib2 = varC_MTTestLib2.SourceAssembly().BoundReferences(); Assert.Same(asm_MTTestLib2[0], asm_MTTestLib1_V1[0]); Assert.Same(asm_MTTestLib2[1], varC_MTTestLib1_V1.SourceAssembly()); var c2 = CreateCompilation(new AssemblyIdentity("c2"), null, new MetadataReference[] { Net451.mscorlib, varC_MTTestLib2.ToMetadataReference(), varC_MTTestLib1_V1.ToMetadataReference() }); var asm2 = c2.SourceAssembly().BoundReferences(); Assert.Same(asm2[0], asm_MTTestLib1_V1[0]); Assert.Same(asm2[1], varC_MTTestLib2.SourceAssembly()); Assert.Same(asm2[2], varC_MTTestLib1_V1.SourceAssembly()); Assert.Equal("MTTestLib2", asm2[1].Identity.Name); Assert.Equal(2, (from a in asm2[1].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm2[1].BoundReferences() where object.ReferenceEquals(a, asm2[0]) select a).Count()); Assert.Equal(1, (from a in asm2[1].BoundReferences() where object.ReferenceEquals(a, asm2[2]) select a).Count()); var retval1 = asm2[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Foo").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval1.Kind); Assert.Same(retval1, asm2[2].GlobalNamespace.GetMembers("Class1").Single()); Assert.Equal("MTTestLib1", asm2[2].Identity.Name); Assert.Equal(1, asm2[2].Identity.Version.Major); Assert.Equal(1, (from a in asm2[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm2[2].BoundReferences() where object.ReferenceEquals(a, asm2[0]) select a).Count()); var varMTTestLib1_V2_Name = new AssemblyIdentity("MTTestLib1", new Version("2.0.0.0")); var varC_MTTestLib1_V2 = CreateCompilation(varMTTestLib1_V2_Name, new string[] { // AssemblyPaths.SymbolsTests.V2.MTTestModule1.netmodule @" public class Class1 { } public class Class2 { } " }, new MetadataReference[] { Net451.mscorlib }); var asm_MTTestLib1_V2 = varC_MTTestLib1_V2.SourceAssembly().BoundReferences(); var varMTTestLib3_Name = new AssemblyIdentity("MTTestLib3"); var varC_MTTestLib3 = CreateCompilation(varMTTestLib3_Name, new string[] { // AssemblyPaths.SymbolsTests.V2.MTTestModule3.netmodule @" public class Class5 { Class1 Foo1() { return null; } Class2 Foo2() { return null; } Class4 Foo3() { return null; } Class1 Bar1; Class2 Bar2; Class4 Bar3; } " }, new MetadataReference[] { Net451.mscorlib, varC_MTTestLib2.ToMetadataReference(), varC_MTTestLib1_V2.ToMetadataReference() }); var asm_MTTestLib3 = varC_MTTestLib3.SourceAssembly().BoundReferences(); Assert.Same(asm_MTTestLib3[0], asm_MTTestLib1_V1[0]); Assert.NotSame(asm_MTTestLib3[1], varC_MTTestLib2.SourceAssembly()); Assert.NotSame(asm_MTTestLib3[2], varC_MTTestLib1_V1.SourceAssembly()); var c3 = CreateCompilation(new AssemblyIdentity("c3"), null, new MetadataReference[] { Net451.mscorlib, varC_MTTestLib2.ToMetadataReference(), varC_MTTestLib1_V2.ToMetadataReference(), varC_MTTestLib3.ToMetadataReference() }); var asm3 = c3.SourceAssembly().BoundReferences(); Assert.Same(asm3[0], asm_MTTestLib1_V1[0]); Assert.Same(asm3[1], asm_MTTestLib3[1]); Assert.Same(asm3[2], asm_MTTestLib3[2]); Assert.Same(asm3[3], varC_MTTestLib3.SourceAssembly()); Assert.Equal("MTTestLib2", asm3[1].Identity.Name); Assert.Same(((RetargetingAssemblySymbol)asm3[1]).UnderlyingAssembly, varC_MTTestLib2.SourceAssembly()); Assert.Equal(2, (from a in asm3[1].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm3[1].BoundReferences() where object.ReferenceEquals(a, asm3[0]) select a).Count()); Assert.Equal(1, (from a in asm3[1].BoundReferences() where object.ReferenceEquals(a, asm3[2]) select a).Count()); var retval2 = asm3[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Foo").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval2.Kind); Assert.Same(retval2, asm3[2].GlobalNamespace.GetMembers("Class1").Single()); Assert.Equal("MTTestLib1", asm3[2].Identity.Name); Assert.NotSame(asm3[2], asm2[2]); Assert.NotSame(asm3[2].DeclaringCompilation, asm2[2].DeclaringCompilation); Assert.Equal(2, asm3[2].Identity.Version.Major); Assert.Equal(1, (from a in asm3[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm3[2].BoundReferences() where object.ReferenceEquals(a, asm3[0]) select a).Count()); Assert.Equal("MTTestLib3", asm3[3].Identity.Name); Assert.Equal(3, (from a in asm3[3].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm3[3].BoundReferences() where object.ReferenceEquals(a, asm3[0]) select a).Count()); Assert.Equal(1, (from a in asm3[3].BoundReferences() where object.ReferenceEquals(a, asm3[1]) select a).Count()); Assert.Equal(1, (from a in asm3[3].BoundReferences() where object.ReferenceEquals(a, asm3[2]) select a).Count()); var type1 = asm3[3].GlobalNamespace.GetTypeMembers("Class5"). Single(); var retval3 = type1.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval3.Kind); Assert.Same(retval3, asm3[2].GlobalNamespace.GetMembers("Class1").Single()); var retval4 = type1.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval4.Kind); Assert.Same(retval4, asm3[2].GlobalNamespace.GetMembers("Class2").Single()); var retval5 = type1.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval5.Kind); Assert.Same(retval5, asm3[1].GlobalNamespace.GetMembers("Class4").Single()); var varMTTestLib1_V3_Name = new AssemblyIdentity("MTTestLib1", new Version("3.0.0.0")); var varC_MTTestLib1_V3 = CreateCompilation(varMTTestLib1_V3_Name, new string[] { // AssemblyPaths.SymbolsTests.V3.MTTestModule1.netmodule @" public class Class1 { } public class Class2 { } public class Class3 { } " }, new MetadataReference[] { Net451.mscorlib }); var asm_MTTestLib1_V3 = varC_MTTestLib1_V3.SourceAssembly().BoundReferences(); var varMTTestLib4_Name = new AssemblyIdentity("MTTestLib4"); var varC_MTTestLib4 = CreateCompilation(varMTTestLib4_Name, new string[] { // AssemblyPaths.SymbolsTests.V3.MTTestModule4.netmodule @" public class Class6 { Class1 Foo1() { return null; } Class2 Foo2() { return null; } Class3 Foo3() { return null; } Class4 Foo4() { return null; } Class5 Foo5() { return null; } Class1 Bar1; Class2 Bar2; Class3 Bar3; Class4 Bar4; Class5 Bar5; } " }, new MetadataReference[] { Net451.mscorlib, varC_MTTestLib2.ToMetadataReference(), varC_MTTestLib1_V3.ToMetadataReference(), varC_MTTestLib3.ToMetadataReference() }); var asm_MTTestLib4 = varC_MTTestLib4.SourceAssembly().BoundReferences(); Assert.Same(asm_MTTestLib4[0], asm_MTTestLib1_V1[0]); Assert.NotSame(asm_MTTestLib4[1], varC_MTTestLib2.SourceAssembly()); Assert.Same(asm_MTTestLib4[2], varC_MTTestLib1_V3.SourceAssembly()); Assert.NotSame(asm_MTTestLib4[3], varC_MTTestLib3.SourceAssembly()); var c4 = CreateCompilation(new AssemblyIdentity("c4"), null, new MetadataReference[] { Net451.mscorlib, varC_MTTestLib2.ToMetadataReference(), varC_MTTestLib1_V3.ToMetadataReference(), varC_MTTestLib3.ToMetadataReference(), varC_MTTestLib4.ToMetadataReference() }); var asm4 = c4.SourceAssembly().BoundReferences(); Assert.Same(asm4[0], asm_MTTestLib1_V1[0]); Assert.Same(asm4[1], asm_MTTestLib4[1]); Assert.Same(asm4[2], asm_MTTestLib4[2]); Assert.Same(asm4[3], asm_MTTestLib4[3]); Assert.Same(asm4[4], varC_MTTestLib4.SourceAssembly()); Assert.Equal("MTTestLib2", asm4[1].Identity.Name); Assert.NotSame(asm4[1], varC_MTTestLib2.SourceAssembly()); Assert.NotSame(asm4[1], asm2[1]); Assert.NotSame(asm4[1], asm3[1]); Assert.Same(((RetargetingAssemblySymbol)asm4[1]).UnderlyingAssembly, varC_MTTestLib2.SourceAssembly()); Assert.Equal(2, (from a in asm4[1].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm4[1].BoundReferences() where object.ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal(1, (from a in asm4[1].BoundReferences() where object.ReferenceEquals(a, asm4[2]) select a).Count()); var retval6 = asm4[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Foo").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval6.Kind); Assert.Same(retval6, asm4[2].GlobalNamespace.GetMembers("Class1").Single()); Assert.Equal("MTTestLib1", asm4[2].Identity.Name); Assert.NotSame(asm4[2], asm2[2]); Assert.NotSame(asm4[2], asm3[2]); Assert.NotSame(asm4[2].DeclaringCompilation, asm2[2].DeclaringCompilation); Assert.NotSame(asm4[2].DeclaringCompilation, asm3[2].DeclaringCompilation); Assert.Equal(3, asm4[2].Identity.Version.Major); Assert.Equal(1, (from a in asm4[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm4[2].BoundReferences() where object.ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal("MTTestLib3", asm4[3].Identity.Name); Assert.NotSame(asm4[3], asm3[3]); Assert.Same(((RetargetingAssemblySymbol)asm4[3]).UnderlyingAssembly, asm3[3]); Assert.Equal(3, (from a in asm4[3].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm4[3].BoundReferences() where object.ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal(1, (from a in asm4[3].BoundReferences() where object.ReferenceEquals(a, asm4[1]) select a).Count()); Assert.Equal(1, (from a in asm4[3].BoundReferences() where object.ReferenceEquals(a, asm4[2]) select a).Count()); var type2 = asm4[3].GlobalNamespace.GetTypeMembers("Class5"). Single(); var retval7 = type2.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval7.Kind); Assert.Same(retval7, asm4[2].GlobalNamespace.GetMembers("Class1").Single()); var retval8 = type2.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval8.Kind); Assert.Same(retval8, asm4[2].GlobalNamespace.GetMembers("Class2").Single()); var retval9 = type2.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval9.Kind); Assert.Same(retval9, asm4[1].GlobalNamespace.GetMembers("Class4").Single()); Assert.Equal("MTTestLib4", asm4[4].Identity.Name); Assert.Equal(4, (from a in asm4[4].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm4[4].BoundReferences() where object.ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal(1, (from a in asm4[4].BoundReferences() where object.ReferenceEquals(a, asm4[1]) select a).Count()); Assert.Equal(1, (from a in asm4[4].BoundReferences() where object.ReferenceEquals(a, asm4[2]) select a).Count()); Assert.Equal(1, (from a in asm4[4].BoundReferences() where object.ReferenceEquals(a, asm4[3]) select a).Count()); var type3 = asm4[4].GlobalNamespace.GetTypeMembers("Class6"). Single(); var retval10 = type3.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval10.Kind); Assert.Same(retval10, asm4[2].GlobalNamespace.GetMembers("Class1").Single()); var retval11 = type3.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval11.Kind); Assert.Same(retval11, asm4[2].GlobalNamespace.GetMembers("Class2").Single()); var retval12 = type3.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval12.Kind); Assert.Same(retval12, asm4[2].GlobalNamespace.GetMembers("Class3").Single()); var retval13 = type3.GetMembers("Foo4").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval13.Kind); Assert.Same(retval13, asm4[1].GlobalNamespace.GetMembers("Class4").Single()); var retval14 = type3.GetMembers("Foo5").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval14.Kind); Assert.Same(retval14, asm4[3].GlobalNamespace.GetMembers("Class5").Single()); var c5 = CreateCompilation(new AssemblyIdentity("c5"), null, new MetadataReference[] { Net451.mscorlib, varC_MTTestLib3.ToMetadataReference() }); var asm5 = c5.SourceAssembly().BoundReferences(); Assert.Same(asm5[0], asm2[0]); Assert.True(asm5[1].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(asm3[3])); var c6 = CreateCompilation(new AssemblyIdentity("c6"), null, new MetadataReference[] { Net451.mscorlib, varC_MTTestLib2.ToMetadataReference() }); var asm6 = c6.SourceAssembly().BoundReferences(); Assert.Same(asm6[0], asm2[0]); Assert.True(asm6[1].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(varC_MTTestLib2.SourceAssembly())); var c7 = CreateCompilation(new AssemblyIdentity("c7"), null, new MetadataReference[] { Net451.mscorlib, varC_MTTestLib2.ToMetadataReference(), varC_MTTestLib3.ToMetadataReference(), varC_MTTestLib4.ToMetadataReference() }); var asm7 = c7.SourceAssembly().BoundReferences(); Assert.Same(asm7[0], asm2[0]); Assert.True(asm7[1].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(varC_MTTestLib2.SourceAssembly())); Assert.NotSame(asm7[2], asm3[3]); Assert.NotSame(asm7[2], asm4[3]); Assert.NotSame(asm7[3], asm4[4]); Assert.Equal("MTTestLib3", asm7[2].Identity.Name); Assert.Same(((RetargetingAssemblySymbol)asm7[2]).UnderlyingAssembly, asm3[3]); Assert.Equal(2, (from a in asm7[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm7[2].BoundReferences() where object.ReferenceEquals(a, asm7[0]) select a).Count()); Assert.Equal(1, (from a in asm7[2].BoundReferences() where object.ReferenceEquals(a, asm7[1]) select a).Count()); var type4 = asm7[2].GlobalNamespace.GetTypeMembers("Class5"). Single(); var retval15 = type4.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal("MTTestLib1", retval15.ContainingAssembly.Name); Assert.Equal(0, (from a in asm7 where a != null && a.Name == "MTTestLib1" select a).Count()); var retval16 = type4.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal("MTTestLib1", retval16.ContainingAssembly.Name); var retval17 = type4.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval17.Kind); Assert.Same(retval17, asm7[1].GlobalNamespace.GetMembers("Class4").Single()); Assert.Equal("MTTestLib4", asm7[3].Identity.Name); Assert.Same(((RetargetingAssemblySymbol)asm7[3]).UnderlyingAssembly, asm4[4]); Assert.Equal(3, (from a in asm7[3].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm7[3].BoundReferences() where object.ReferenceEquals(a, asm7[0]) select a).Count()); Assert.Equal(1, (from a in asm7[3].BoundReferences() where object.ReferenceEquals(a, asm7[1]) select a).Count()); Assert.Equal(1, (from a in asm7[3].BoundReferences() where object.ReferenceEquals(a, asm7[2]) select a).Count()); var type5 = asm7[3].GlobalNamespace.GetTypeMembers("Class6"). Single(); var retval18 = type5.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal("MTTestLib1", retval18.ContainingAssembly.Name); var retval19 = type5.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal("MTTestLib1", retval19.ContainingAssembly.Name); var retval20 = type5.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal("MTTestLib1", retval20.ContainingAssembly.Name); var retval21 = type5.GetMembers("Foo4").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval21.Kind); Assert.Same(retval21, asm7[1].GlobalNamespace.GetMembers("Class4").Single()); var retval22 = type5.GetMembers("Foo5").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval22.Kind); Assert.Same(retval22, asm7[2].GlobalNamespace.GetMembers("Class5").Single()); // This test shows that simple reordering of references doesn't pick different set of assemblies var c8 = CreateCompilation(new AssemblyIdentity("c8"), null, new MetadataReference[] { Net451.mscorlib, varC_MTTestLib4.ToMetadataReference(), varC_MTTestLib2.ToMetadataReference(), varC_MTTestLib3.ToMetadataReference() }); var asm8 = c8.SourceAssembly().BoundReferences(); Assert.Same(asm8[0], asm2[0]); Assert.True(asm8[2].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(asm4[1])); Assert.Same(asm8[2], asm7[1]); Assert.True(asm8[3].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(asm4[3])); Assert.Same(asm8[3], asm7[2]); Assert.True(asm8[1].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(asm4[4])); Assert.Same(asm8[1], asm7[3]); var c9 = CreateCompilation(new AssemblyIdentity("c9"), null, new MetadataReference[] { Net451.mscorlib, varC_MTTestLib4.ToMetadataReference() }); var asm9 = c9.SourceAssembly().BoundReferences(); Assert.Same(asm9[0], asm2[0]); Assert.True(asm9[1].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(asm4[4])); var c10 = CreateCompilation(new AssemblyIdentity("c10"), null, new MetadataReference[] { Net451.mscorlib, varC_MTTestLib2.ToMetadataReference(), varC_MTTestLib1_V3.ToMetadataReference(), varC_MTTestLib3.ToMetadataReference(), varC_MTTestLib4.ToMetadataReference() }); var asm10 = c10.SourceAssembly().BoundReferences(); Assert.Same(asm10[0], asm2[0]); Assert.Same(asm10[1], asm4[1]); Assert.Same(asm10[2], asm4[2]); Assert.Same(asm10[3], asm4[3]); Assert.Same(asm10[4], asm4[4]); // Run the same tests again to make sure we didn't corrupt prior state by loading additional assemblies Assert.Same(asm2[0], asm_MTTestLib1_V1[0]); Assert.Equal("MTTestLib2", asm2[1].Identity.Name); Assert.Equal(2, (from a in asm2[1].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm2[1].BoundReferences() where object.ReferenceEquals(a, asm2[0]) select a).Count()); Assert.Equal(1, (from a in asm2[1].BoundReferences() where object.ReferenceEquals(a, asm2[2]) select a).Count()); retval1 = asm2[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Foo").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval1.Kind); Assert.Same(retval1, asm2[2].GlobalNamespace.GetMembers("Class1").Single()); Assert.Equal("MTTestLib1", asm2[2].Identity.Name); Assert.Equal(1, asm2[2].Identity.Version.Major); Assert.Equal(1, (from a in asm2[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm2[2].BoundReferences() where object.ReferenceEquals(a, asm2[0]) select a).Count()); Assert.Same(asm_MTTestLib3[0], asm_MTTestLib1_V1[0]); Assert.NotSame(asm_MTTestLib3[1], varC_MTTestLib2.SourceAssembly()); Assert.NotSame(asm_MTTestLib3[2], varC_MTTestLib1_V1.SourceAssembly()); Assert.Same(asm3[0], asm_MTTestLib1_V1[0]); Assert.Same(asm3[1], asm_MTTestLib3[1]); Assert.Same(asm3[2], asm_MTTestLib3[2]); Assert.Same(asm3[3], varC_MTTestLib3.SourceAssembly()); Assert.Equal("MTTestLib2", asm3[1].Identity.Name); Assert.Same(((RetargetingAssemblySymbol)asm3[1]).UnderlyingAssembly, varC_MTTestLib2.SourceAssembly()); Assert.Equal(2, (from a in asm3[1].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm3[1].BoundReferences() where object.ReferenceEquals(a, asm3[0]) select a).Count()); Assert.Equal(1, (from a in asm3[1].BoundReferences() where object.ReferenceEquals(a, asm3[2]) select a).Count()); retval2 = asm3[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Foo").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval2.Kind); Assert.Same(retval2, asm3[2].GlobalNamespace.GetMembers("Class1").Single()); Assert.Equal("MTTestLib1", asm3[2].Identity.Name); Assert.NotSame(asm3[2], asm2[2]); Assert.NotSame(asm3[2].DeclaringCompilation, asm2[2].DeclaringCompilation); Assert.Equal(2, asm3[2].Identity.Version.Major); Assert.Equal(1, (from a in asm3[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm3[2].BoundReferences() where object.ReferenceEquals(a, asm3[0]) select a).Count()); Assert.Equal("MTTestLib3", asm3[3].Identity.Name); Assert.Equal(3, (from a in asm3[3].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm3[3].BoundReferences() where object.ReferenceEquals(a, asm3[0]) select a).Count()); Assert.Equal(1, (from a in asm3[3].BoundReferences() where object.ReferenceEquals(a, asm3[1]) select a).Count()); Assert.Equal(1, (from a in asm3[3].BoundReferences() where object.ReferenceEquals(a, asm3[2]) select a).Count()); type1 = asm3[3].GlobalNamespace.GetTypeMembers("Class5"). Single(); retval3 = type1.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval3.Kind); Assert.Same(retval3, asm3[2].GlobalNamespace.GetMembers("Class1").Single()); retval4 = type1.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval4.Kind); Assert.Same(retval4, asm3[2].GlobalNamespace.GetMembers("Class2").Single()); retval5 = type1.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval5.Kind); Assert.Same(retval5, asm3[1].GlobalNamespace.GetMembers("Class4").Single()); Assert.Same(asm4[0], asm_MTTestLib1_V1[0]); Assert.Same(asm4[1], asm_MTTestLib4[1]); Assert.Same(asm4[2], asm_MTTestLib4[2]); Assert.Same(asm4[3], asm_MTTestLib4[3]); Assert.Same(asm4[4], varC_MTTestLib4.SourceAssembly()); Assert.Equal("MTTestLib2", asm4[1].Identity.Name); Assert.NotSame(asm4[1], varC_MTTestLib2.SourceAssembly()); Assert.NotSame(asm4[1], asm2[1]); Assert.NotSame(asm4[1], asm3[1]); Assert.Same(((RetargetingAssemblySymbol)asm4[1]).UnderlyingAssembly, varC_MTTestLib2.SourceAssembly()); Assert.Equal(2, (from a in asm4[1].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm4[1].BoundReferences() where object.ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal(1, (from a in asm4[1].BoundReferences() where object.ReferenceEquals(a, asm4[2]) select a).Count()); retval6 = asm4[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Foo").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval6.Kind); Assert.Same(retval6, asm4[2].GlobalNamespace.GetMembers("Class1").Single()); Assert.Equal("MTTestLib1", asm4[2].Identity.Name); Assert.NotSame(asm4[2], asm2[2]); Assert.NotSame(asm4[2], asm3[2]); Assert.NotSame(asm4[2].DeclaringCompilation, asm2[2].DeclaringCompilation); Assert.NotSame(asm4[2].DeclaringCompilation, asm3[2].DeclaringCompilation); Assert.Equal(3, asm4[2].Identity.Version.Major); Assert.Equal(1, (from a in asm4[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm4[2].BoundReferences() where object.ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal("MTTestLib3", asm4[3].Identity.Name); Assert.NotSame(asm4[3], asm3[3]); Assert.Same(((RetargetingAssemblySymbol)asm4[3]).UnderlyingAssembly, asm3[3]); Assert.Equal(3, (from a in asm4[3].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm4[3].BoundReferences() where object.ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal(1, (from a in asm4[3].BoundReferences() where object.ReferenceEquals(a, asm4[1]) select a).Count()); Assert.Equal(1, (from a in asm4[3].BoundReferences() where object.ReferenceEquals(a, asm4[2]) select a).Count()); type2 = asm4[3].GlobalNamespace.GetTypeMembers("Class5"). Single(); retval7 = type2.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval7.Kind); Assert.Same(retval7, asm4[2].GlobalNamespace.GetMembers("Class1").Single()); retval8 = type2.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval8.Kind); Assert.Same(retval8, asm4[2].GlobalNamespace.GetMembers("Class2").Single()); retval9 = type2.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval9.Kind); Assert.Same(retval9, asm4[1].GlobalNamespace.GetMembers("Class4").Single()); Assert.Equal("MTTestLib4", asm4[4].Identity.Name); Assert.Equal(4, (from a in asm4[4].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm4[4].BoundReferences() where object.ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal(1, (from a in asm4[4].BoundReferences() where object.ReferenceEquals(a, asm4[1]) select a).Count()); Assert.Equal(1, (from a in asm4[4].BoundReferences() where object.ReferenceEquals(a, asm4[2]) select a).Count()); Assert.Equal(1, (from a in asm4[4].BoundReferences() where object.ReferenceEquals(a, asm4[3]) select a).Count()); type3 = asm4[4].GlobalNamespace.GetTypeMembers("Class6"). Single(); retval10 = type3.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval10.Kind); Assert.Same(retval10, asm4[2].GlobalNamespace.GetMembers("Class1").Single()); retval11 = type3.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval11.Kind); Assert.Same(retval11, asm4[2].GlobalNamespace.GetMembers("Class2").Single()); retval12 = type3.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval12.Kind); Assert.Same(retval12, asm4[2].GlobalNamespace.GetMembers("Class3").Single()); retval13 = type3.GetMembers("Foo4").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval13.Kind); Assert.Same(retval13, asm4[1].GlobalNamespace.GetMembers("Class4").Single()); retval14 = type3.GetMembers("Foo5").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval14.Kind); Assert.Same(retval14, asm4[3].GlobalNamespace.GetMembers("Class5").Single()); Assert.Same(asm5[0], asm2[0]); Assert.True(asm5[1].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(asm3[3])); Assert.Same(asm6[0], asm2[0]); Assert.True(asm6[1].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(varC_MTTestLib2.SourceAssembly())); Assert.Same(asm7[0], asm2[0]); Assert.True(asm7[1].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(varC_MTTestLib2.SourceAssembly())); Assert.NotSame(asm7[2], asm3[3]); Assert.NotSame(asm7[2], asm4[3]); Assert.NotSame(asm7[3], asm4[4]); Assert.Equal("MTTestLib3", asm7[2].Identity.Name); Assert.Same(((RetargetingAssemblySymbol)asm7[2]).UnderlyingAssembly, asm3[3]); Assert.Equal(2, (from a in asm7[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm7[2].BoundReferences() where object.ReferenceEquals(a, asm7[0]) select a).Count()); Assert.Equal(1, (from a in asm7[2].BoundReferences() where object.ReferenceEquals(a, asm7[1]) select a).Count()); type4 = asm7[2].GlobalNamespace.GetTypeMembers("Class5"). Single(); retval15 = type4.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal("MTTestLib1", retval15.ContainingAssembly.Name); Assert.Equal(0, (from a in asm7 where a != null && a.Name == "MTTestLib1" select a).Count()); retval16 = type4.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal("MTTestLib1", retval16.ContainingAssembly.Name); retval17 = type4.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval17.Kind); Assert.Same(retval17, asm7[1].GlobalNamespace.GetMembers("Class4").Single()); Assert.Equal("MTTestLib4", asm7[3].Identity.Name); Assert.Same(((RetargetingAssemblySymbol)asm7[3]).UnderlyingAssembly, asm4[4]); Assert.Equal(3, (from a in asm7[3].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm7[3].BoundReferences() where object.ReferenceEquals(a, asm7[0]) select a).Count()); Assert.Equal(1, (from a in asm7[3].BoundReferences() where object.ReferenceEquals(a, asm7[1]) select a).Count()); Assert.Equal(1, (from a in asm7[3].BoundReferences() where object.ReferenceEquals(a, asm7[2]) select a).Count()); type5 = asm7[3].GlobalNamespace.GetTypeMembers("Class6"). Single(); retval18 = type5.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal("MTTestLib1", retval18.ContainingAssembly.Name); retval19 = type5.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal("MTTestLib1", retval19.ContainingAssembly.Name); retval20 = type5.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal("MTTestLib1", retval20.ContainingAssembly.Name); retval21 = type5.GetMembers("Foo4").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval21.Kind); Assert.Same(retval21, asm7[1].GlobalNamespace.GetMembers("Class4").Single()); retval22 = type5.GetMembers("Foo5").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval22.Kind); Assert.Same(retval22, asm7[2].GlobalNamespace.GetMembers("Class5").Single()); } [Fact] public void MultiTargeting3() { var varMTTestLib2_Name = new AssemblyIdentity("MTTestLib2"); var varC_MTTestLib2 = CreateCompilation(varMTTestLib2_Name, (string[])null, new[] { Net451.mscorlib, TestReferences.SymbolsTests.V1.MTTestLib1.dll, TestReferences.SymbolsTests.V1.MTTestModule2.netmodule }); var asm_MTTestLib2 = varC_MTTestLib2.SourceAssembly().BoundReferences(); var c2 = CreateCompilation(new AssemblyIdentity("c2"), null, new MetadataReference[] { Net451.mscorlib, TestReferences.SymbolsTests.V1.MTTestLib1.dll, new CSharpCompilationReference(varC_MTTestLib2) }); var asm2Prime = c2.SourceAssembly().BoundReferences(); var asm2 = new AssemblySymbol[] { asm2Prime[0], asm2Prime[2], asm2Prime[1] }; Assert.Same(asm2[0], asm_MTTestLib2[0]); Assert.Same(asm2[1], varC_MTTestLib2.SourceAssembly()); Assert.Same(asm2[2], asm_MTTestLib2[1]); Assert.Equal("MTTestLib2", asm2[1].Identity.Name); Assert.Equal(4, (from a in asm2[1].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(2, (from a in asm2[1].BoundReferences() where object.ReferenceEquals(a, asm2[0]) select a).Count()); Assert.Equal(2, (from a in asm2[1].BoundReferences() where object.ReferenceEquals(a, asm2[2]) select a).Count()); var retval1 = asm2[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Foo").OfType<MethodSymbol>().Single().ReturnType; Assert.Same(retval1, asm2[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Bar").OfType<FieldSymbol>().Single().Type); Assert.NotEqual(SymbolKind.ErrorType, retval1.Kind); Assert.Same(retval1, asm2[2].GlobalNamespace.GetMembers("Class1").Single()); Assert.Equal("MTTestLib1", asm2[2].Identity.Name); Assert.Equal(1, asm2[2].Identity.Version.Major); Assert.Equal(1, (from a in asm2[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm2[2].BoundReferences() where object.ReferenceEquals(a, asm2[0]) select a).Count()); var varMTTestLib3_Name = new AssemblyIdentity("MTTestLib3"); var varC_MTTestLib3 = CreateCompilation(varMTTestLib3_Name, null, new MetadataReference[] { Net451.mscorlib, TestReferences.SymbolsTests.V2.MTTestLib1.dll, new CSharpCompilationReference(varC_MTTestLib2), TestReferences.SymbolsTests.V2.MTTestModule3.netmodule }); var asm_MTTestLib3Prime = varC_MTTestLib3.SourceAssembly().BoundReferences(); var asm_MTTestLib3 = new AssemblySymbol[] { asm_MTTestLib3Prime[0], asm_MTTestLib3Prime[2], asm_MTTestLib3Prime[1] }; Assert.Same(asm_MTTestLib3[0], asm_MTTestLib2[0]); Assert.NotSame(asm_MTTestLib3[1], varC_MTTestLib2.SourceAssembly()); Assert.NotSame(asm_MTTestLib3[2], asm_MTTestLib2[1]); var c3 = CreateCompilation(new AssemblyIdentity("c3"), null, new MetadataReference[] { Net451.mscorlib, TestReferences.SymbolsTests.V2.MTTestLib1.dll, new CSharpCompilationReference(varC_MTTestLib2), new CSharpCompilationReference(varC_MTTestLib3) }); var asm3Prime = c3.SourceAssembly().BoundReferences(); var asm3 = new AssemblySymbol[] { asm3Prime[0], asm3Prime[2], asm3Prime[1], asm3Prime[3] }; Assert.Same(asm3[0], asm_MTTestLib2[0]); Assert.Same(asm3[1], asm_MTTestLib3[1]); Assert.Same(asm3[2], asm_MTTestLib3[2]); Assert.Same(asm3[3], varC_MTTestLib3.SourceAssembly()); Assert.Equal("MTTestLib2", asm3[1].Identity.Name); Assert.Same(((RetargetingAssemblySymbol)asm3[1]).UnderlyingAssembly, varC_MTTestLib2.SourceAssembly()); Assert.Equal(4, (from a in asm3[1].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(2, (from a in asm3[1].BoundReferences() where object.ReferenceEquals(a, asm3[0]) select a).Count()); Assert.Equal(2, (from a in asm3[1].BoundReferences() where object.ReferenceEquals(a, asm3[2]) select a).Count()); var retval2 = asm3[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Foo").OfType<MethodSymbol>().Single().ReturnType; Assert.Same(retval2, asm3[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Bar").OfType<FieldSymbol>().Single().Type); Assert.NotEqual(SymbolKind.ErrorType, retval2.Kind); Assert.Same(retval2, asm3[2].GlobalNamespace.GetMembers("Class1").Single()); Assert.Equal("MTTestLib1", asm3[2].Identity.Name); Assert.NotSame(asm3[2], asm2[2]); Assert.NotSame(asm3[2], asm2[2]); Assert.NotSame(((PEAssemblySymbol)asm3[2]).Assembly, ((PEAssemblySymbol)asm2[2]).Assembly); Assert.Equal(2, asm3[2].Identity.Version.Major); Assert.Equal(1, (from a in asm3[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm3[2].BoundReferences() where object.ReferenceEquals(a, asm3[0]) select a).Count()); Assert.Equal("MTTestLib3", asm3[3].Identity.Name); Assert.Equal(6, (from a in asm3[3].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(2, (from a in asm3[3].BoundReferences() where object.ReferenceEquals(a, asm3[0]) select a).Count()); Assert.Equal(2, (from a in asm3[3].BoundReferences() where object.ReferenceEquals(a, asm3[1]) select a).Count()); Assert.Equal(2, (from a in asm3[3].BoundReferences() where object.ReferenceEquals(a, asm3[2]) select a).Count()); var type1 = asm3[3].GlobalNamespace.GetTypeMembers("Class5").Single(); var retval3 = type1.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval3.Kind); Assert.Same(retval3, asm3[2].GlobalNamespace.GetMembers("Class1").Single()); var retval4 = type1.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval4.Kind); Assert.Same(retval4, asm3[2].GlobalNamespace.GetMembers("Class2").Single()); var retval5 = type1.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval5.Kind); Assert.Same(retval5, asm3[1].GlobalNamespace.GetMembers("Class4").Single()); var varMTTestLib4_Name = new AssemblyIdentity("MTTestLib4"); var varC_MTTestLib4 = CreateCompilation(varMTTestLib4_Name, null, new MetadataReference[] { Net451.mscorlib, TestReferences.SymbolsTests.V3.MTTestLib1.dll, new CSharpCompilationReference(varC_MTTestLib2), new CSharpCompilationReference(varC_MTTestLib3), TestReferences.SymbolsTests.V3.MTTestModule4.netmodule }); var asm_MTTestLib4Prime = varC_MTTestLib4.SourceAssembly().BoundReferences(); var asm_MTTestLib4 = new AssemblySymbol[] { asm_MTTestLib4Prime[0], asm_MTTestLib4Prime[2], asm_MTTestLib4Prime[1], asm_MTTestLib4Prime[3] }; Assert.Same(asm_MTTestLib4[0], asm_MTTestLib2[0]); Assert.NotSame(asm_MTTestLib4[1], varC_MTTestLib2.SourceAssembly()); Assert.NotSame(asm_MTTestLib4[2], asm3[2]); Assert.NotSame(asm_MTTestLib4[2], asm2[2]); Assert.NotSame(asm_MTTestLib4[3], varC_MTTestLib3.SourceAssembly()); var c4 = CreateCompilation(new AssemblyIdentity("c4"), null, new MetadataReference[] { Net451.mscorlib, TestReferences.SymbolsTests.V3.MTTestLib1.dll, new CSharpCompilationReference(varC_MTTestLib2), new CSharpCompilationReference(varC_MTTestLib3), new CSharpCompilationReference(varC_MTTestLib4) }); var asm4Prime = c4.SourceAssembly().BoundReferences(); var asm4 = new AssemblySymbol[] { asm4Prime[0], asm4Prime[2], asm4Prime[1], asm4Prime[3], asm4Prime[4] }; Assert.Same(asm4[0], asm_MTTestLib2[0]); Assert.Same(asm4[1], asm_MTTestLib4[1]); Assert.Same(asm4[2], asm_MTTestLib4[2]); Assert.Same(asm4[3], asm_MTTestLib4[3]); Assert.Same(asm4[4], varC_MTTestLib4.SourceAssembly()); Assert.Equal("MTTestLib2", asm4[1].Identity.Name); Assert.NotSame(asm4[1], varC_MTTestLib2.SourceAssembly()); Assert.NotSame(asm4[1], asm2[1]); Assert.NotSame(asm4[1], asm3[1]); Assert.Same(((RetargetingAssemblySymbol)asm4[1]).UnderlyingAssembly, varC_MTTestLib2.SourceAssembly()); Assert.Equal(4, (from a in asm4[1].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(2, (from a in asm4[1].BoundReferences() where object.ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal(2, (from a in asm4[1].BoundReferences() where object.ReferenceEquals(a, asm4[2]) select a).Count()); var retval6 = asm4[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Foo").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval6.Kind); Assert.Same(retval6, asm4[2].GlobalNamespace.GetMembers("Class1").Single()); Assert.Equal("MTTestLib1", asm4[2].Identity.Name); Assert.NotSame(asm4[2], asm2[2]); Assert.NotSame(asm4[2], asm3[2]); Assert.NotSame(((PEAssemblySymbol)asm4[2]).Assembly, ((PEAssemblySymbol)asm2[2]).Assembly); Assert.NotSame(((PEAssemblySymbol)asm4[2]).Assembly, ((PEAssemblySymbol)asm3[2]).Assembly); Assert.Equal(3, asm4[2].Identity.Version.Major); Assert.Equal(1, (from a in asm4[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm4[2].BoundReferences() where object.ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal("MTTestLib3", asm4[3].Identity.Name); Assert.NotSame(asm4[3], asm3[3]); Assert.Same(((RetargetingAssemblySymbol)asm4[3]).UnderlyingAssembly, asm3[3]); Assert.Equal(6, (from a in asm4[3].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(2, (from a in asm4[3].BoundReferences() where object.ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal(2, (from a in asm4[3].BoundReferences() where object.ReferenceEquals(a, asm4[1]) select a).Count()); Assert.Equal(2, (from a in asm4[3].BoundReferences() where object.ReferenceEquals(a, asm4[2]) select a).Count()); var type2 = asm4[3].GlobalNamespace.GetTypeMembers("Class5"). Single(); var retval7 = type2.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval7.Kind); Assert.Same(retval7, asm4[2].GlobalNamespace.GetMembers("Class1").Single()); var retval8 = type2.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval8.Kind); Assert.Same(retval8, asm4[2].GlobalNamespace.GetMembers("Class2").Single()); var retval9 = type2.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval9.Kind); Assert.Same(retval9, asm4[1].GlobalNamespace.GetMembers("Class4").Single()); Assert.Equal("MTTestLib4", asm4[4].Identity.Name); Assert.Equal(8, (from a in asm4[4].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(2, (from a in asm4[4].BoundReferences() where object.ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal(2, (from a in asm4[4].BoundReferences() where object.ReferenceEquals(a, asm4[1]) select a).Count()); Assert.Equal(2, (from a in asm4[4].BoundReferences() where object.ReferenceEquals(a, asm4[2]) select a).Count()); Assert.Equal(2, (from a in asm4[4].BoundReferences() where object.ReferenceEquals(a, asm4[3]) select a).Count()); var type3 = asm4[4].GlobalNamespace.GetTypeMembers("Class6"). Single(); var retval10 = type3.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval10.Kind); Assert.Same(retval10, asm4[2].GlobalNamespace.GetMembers("Class1").Single()); var retval11 = type3.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval11.Kind); Assert.Same(retval11, asm4[2].GlobalNamespace.GetMembers("Class2").Single()); var retval12 = type3.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval12.Kind); Assert.Same(retval12, asm4[2].GlobalNamespace.GetMembers("Class3").Single()); var retval13 = type3.GetMembers("Foo4").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval13.Kind); Assert.Same(retval13, asm4[1].GlobalNamespace.GetMembers("Class4").Single()); var retval14 = type3.GetMembers("Foo5").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval14.Kind); Assert.Same(retval14, asm4[3].GlobalNamespace.GetMembers("Class5").Single()); var c5 = CreateCompilation(new AssemblyIdentity("c5"), null, new MetadataReference[] { Net451.mscorlib, new CSharpCompilationReference(varC_MTTestLib3) }); var asm5 = c5.SourceAssembly().BoundReferences(); Assert.Same(asm5[0], asm2[0]); Assert.True(asm5[1].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(asm3[3])); var c6 = CreateCompilation(new AssemblyIdentity("c6"), null, new MetadataReference[] { Net451.mscorlib, new CSharpCompilationReference(varC_MTTestLib2) }); var asm6 = c6.SourceAssembly().BoundReferences(); Assert.Same(asm6[0], asm2[0]); Assert.True(asm6[1].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(varC_MTTestLib2.SourceAssembly())); var c7 = CreateCompilation(new AssemblyIdentity("c7"), null, new MetadataReference[] { Net451.mscorlib, new CSharpCompilationReference(varC_MTTestLib2), new CSharpCompilationReference(varC_MTTestLib3), new CSharpCompilationReference(varC_MTTestLib4) }); var asm7 = c7.SourceAssembly().BoundReferences(); Assert.Same(asm7[0], asm2[0]); Assert.True(asm7[1].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(varC_MTTestLib2.SourceAssembly())); Assert.NotSame(asm7[2], asm3[3]); Assert.NotSame(asm7[2], asm4[3]); Assert.NotSame(asm7[3], asm4[4]); Assert.Equal("MTTestLib3", asm7[2].Identity.Name); Assert.Same(((RetargetingAssemblySymbol)asm7[2]).UnderlyingAssembly, asm3[3]); Assert.Equal(4, (from a in asm7[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(2, (from a in asm7[2].BoundReferences() where object.ReferenceEquals(a, asm7[0]) select a).Count()); Assert.Equal(2, (from a in asm7[2].BoundReferences() where object.ReferenceEquals(a, asm7[1]) select a).Count()); var type4 = asm7[2].GlobalNamespace.GetTypeMembers("Class5"). Single(); var retval15 = type4.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; AssemblySymbol missingAssembly; missingAssembly = retval15.ContainingAssembly; Assert.True(missingAssembly.IsMissing); Assert.Equal("MTTestLib1", missingAssembly.Identity.Name); var retval16 = type4.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.Same(missingAssembly, retval16.ContainingAssembly); var retval17 = type4.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval17.Kind); Assert.Same(retval17, asm7[1].GlobalNamespace.GetMembers("Class4").Single()); Assert.Equal("MTTestLib4", asm7[3].Identity.Name); Assert.Same(((RetargetingAssemblySymbol)asm7[3]).UnderlyingAssembly, asm4[4]); Assert.Equal(6, (from a in asm7[3].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(2, (from a in asm7[3].BoundReferences() where object.ReferenceEquals(a, asm7[0]) select a).Count()); Assert.Equal(2, (from a in asm7[3].BoundReferences() where object.ReferenceEquals(a, asm7[1]) select a).Count()); Assert.Equal(2, (from a in asm7[3].BoundReferences() where object.ReferenceEquals(a, asm7[2]) select a).Count()); var type5 = asm7[3].GlobalNamespace.GetTypeMembers("Class6"). Single(); var retval18 = type5.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal("MTTestLib1", ((MissingMetadataTypeSymbol)retval18).ContainingAssembly.Identity.Name); var retval19 = type5.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.Same(retval18.ContainingAssembly, retval19.ContainingAssembly); var retval20 = type5.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.Same(retval18.ContainingAssembly, retval20.ContainingAssembly); var retval21 = type5.GetMembers("Foo4").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval21.Kind); Assert.Same(retval21, asm7[1].GlobalNamespace.GetMembers("Class4").Single()); var retval22 = type5.GetMembers("Foo5").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval22.Kind); Assert.Same(retval22, asm7[2].GlobalNamespace.GetMembers("Class5").Single()); // This test shows that simple reordering of references doesn't pick different set of assemblies var c8 = CreateCompilation(new AssemblyIdentity("c8"), null, new MetadataReference[] { Net451.mscorlib, new CSharpCompilationReference(varC_MTTestLib4), new CSharpCompilationReference(varC_MTTestLib2), new CSharpCompilationReference(varC_MTTestLib3) }); var asm8 = c8.SourceAssembly().BoundReferences(); Assert.Same(asm8[0], asm2[0]); Assert.True(asm8[2].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(asm4[1])); Assert.Same(asm8[2], asm7[1]); Assert.True(asm8[3].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(asm4[3])); Assert.Same(asm8[3], asm7[2]); Assert.True(asm8[1].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(asm4[4])); Assert.Same(asm8[1], asm7[3]); var c9 = CreateCompilation(new AssemblyIdentity("c9"), null, new MetadataReference[] { Net451.mscorlib, new CSharpCompilationReference(varC_MTTestLib4) }); var asm9 = c9.SourceAssembly().BoundReferences(); Assert.Same(asm9[0], asm2[0]); Assert.True(asm9[1].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(asm4[4])); var c10 = CreateCompilation(new AssemblyIdentity("c10"), null, new MetadataReference[] { Net451.mscorlib, TestReferences.SymbolsTests.V3.MTTestLib1.dll, new CSharpCompilationReference(varC_MTTestLib2), new CSharpCompilationReference(varC_MTTestLib3), new CSharpCompilationReference(varC_MTTestLib4) }); var asm10Prime = c10.SourceAssembly().BoundReferences(); var asm10 = new AssemblySymbol[] { asm10Prime[0], asm10Prime[2], asm10Prime[1], asm10Prime[3], asm10Prime[4] }; Assert.Same(asm10[0], asm2[0]); Assert.Same(asm10[1], asm4[1]); Assert.Same(asm10[2], asm4[2]); Assert.Same(asm10[3], asm4[3]); Assert.Same(asm10[4], asm4[4]); // Run the same tests again to make sure we didn't corrupt prior state by loading additional assemblies Assert.Same(asm2[0], asm_MTTestLib2[0]); Assert.Equal("MTTestLib2", asm2[1].Identity.Name); Assert.Equal(4, (from a in asm2[1].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(2, (from a in asm2[1].BoundReferences() where object.ReferenceEquals(a, asm2[0]) select a).Count()); Assert.Equal(2, (from a in asm2[1].BoundReferences() where object.ReferenceEquals(a, asm2[2]) select a).Count()); retval1 = asm2[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Foo").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval1.Kind); Assert.Same(retval1, asm2[2].GlobalNamespace.GetMembers("Class1").Single()); Assert.Equal("MTTestLib1", asm2[2].Identity.Name); Assert.Equal(1, asm2[2].Identity.Version.Major); Assert.Equal(1, (from a in asm2[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm2[2].BoundReferences() where object.ReferenceEquals(a, asm2[0]) select a).Count()); Assert.Same(asm_MTTestLib3[0], asm_MTTestLib2[0]); Assert.NotSame(asm_MTTestLib3[1], varC_MTTestLib2.SourceAssembly()); Assert.NotSame(asm_MTTestLib3[2], asm_MTTestLib2[1]); Assert.Same(asm3[0], asm_MTTestLib2[0]); Assert.Same(asm3[1], asm_MTTestLib3[1]); Assert.Same(asm3[2], asm_MTTestLib3[2]); Assert.Same(asm3[3], varC_MTTestLib3.SourceAssembly()); Assert.Equal("MTTestLib2", asm3[1].Identity.Name); Assert.Same(((RetargetingAssemblySymbol)asm3[1]).UnderlyingAssembly, varC_MTTestLib2.SourceAssembly()); Assert.Equal(4, (from a in asm3[1].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(2, (from a in asm3[1].BoundReferences() where object.ReferenceEquals(a, asm3[0]) select a).Count()); Assert.Equal(2, (from a in asm3[1].BoundReferences() where object.ReferenceEquals(a, asm3[2]) select a).Count()); retval2 = asm3[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Foo").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval2.Kind); Assert.Same(retval2, asm3[2].GlobalNamespace.GetMembers("Class1").Single()); Assert.Equal("MTTestLib1", asm3[2].Identity.Name); Assert.NotSame(asm3[2], asm2[2]); Assert.NotSame(((PEAssemblySymbol)asm3[2]).Assembly, ((PEAssemblySymbol)asm2[2]).Assembly); Assert.Equal(2, asm3[2].Identity.Version.Major); Assert.Equal(1, (from a in asm3[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm3[2].BoundReferences() where object.ReferenceEquals(a, asm3[0]) select a).Count()); Assert.Equal("MTTestLib3", asm3[3].Identity.Name); Assert.Equal(6, (from a in asm3[3].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(2, (from a in asm3[3].BoundReferences() where object.ReferenceEquals(a, asm3[0]) select a).Count()); Assert.Equal(2, (from a in asm3[3].BoundReferences() where object.ReferenceEquals(a, asm3[1]) select a).Count()); Assert.Equal(2, (from a in asm3[3].BoundReferences() where object.ReferenceEquals(a, asm3[2]) select a).Count()); type1 = asm3[3].GlobalNamespace.GetTypeMembers("Class5"). Single(); retval3 = type1.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval3.Kind); Assert.Same(retval3, asm3[2].GlobalNamespace.GetMembers("Class1").Single()); retval4 = type1.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval4.Kind); Assert.Same(retval4, asm3[2].GlobalNamespace.GetMembers("Class2").Single()); retval5 = type1.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval5.Kind); Assert.Same(retval5, asm3[1].GlobalNamespace.GetMembers("Class4").Single()); Assert.Same(asm4[0], asm_MTTestLib2[0]); Assert.Same(asm4[1], asm_MTTestLib4[1]); Assert.Same(asm4[2], asm_MTTestLib4[2]); Assert.Same(asm4[3], asm_MTTestLib4[3]); Assert.Same(asm4[4], varC_MTTestLib4.SourceAssembly()); Assert.Equal("MTTestLib2", asm4[1].Identity.Name); Assert.NotSame(asm4[1], varC_MTTestLib2.SourceAssembly()); Assert.NotSame(asm4[1], asm2[1]); Assert.NotSame(asm4[1], asm3[1]); Assert.Same(((RetargetingAssemblySymbol)asm4[1]).UnderlyingAssembly, varC_MTTestLib2.SourceAssembly()); Assert.Equal(4, (from a in asm4[1].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(2, (from a in asm4[1].BoundReferences() where object.ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal(2, (from a in asm4[1].BoundReferences() where object.ReferenceEquals(a, asm4[2]) select a).Count()); retval6 = asm4[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Foo").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval6.Kind); Assert.Same(retval6, asm4[2].GlobalNamespace.GetMembers("Class1").Single()); Assert.Equal("MTTestLib1", asm4[2].Identity.Name); Assert.NotSame(asm4[2], asm2[2]); Assert.NotSame(asm4[2], asm3[2]); Assert.NotSame(((PEAssemblySymbol)asm4[2]).Assembly, ((PEAssemblySymbol)asm2[2]).Assembly); Assert.NotSame(((PEAssemblySymbol)asm4[2]).Assembly, ((PEAssemblySymbol)asm3[2]).Assembly); Assert.Equal(3, asm4[2].Identity.Version.Major); Assert.Equal(1, (from a in asm4[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm4[2].BoundReferences() where object.ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal("MTTestLib3", asm4[3].Identity.Name); Assert.NotSame(asm4[3], asm3[3]); Assert.Same(((RetargetingAssemblySymbol)asm4[3]).UnderlyingAssembly, asm3[3]); Assert.Equal(6, (from a in asm4[3].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(2, (from a in asm4[3].BoundReferences() where object.ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal(2, (from a in asm4[3].BoundReferences() where object.ReferenceEquals(a, asm4[1]) select a).Count()); Assert.Equal(2, (from a in asm4[3].BoundReferences() where object.ReferenceEquals(a, asm4[2]) select a).Count()); type2 = asm4[3].GlobalNamespace.GetTypeMembers("Class5"). Single(); retval7 = type2.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval7.Kind); Assert.Same(retval7, asm4[2].GlobalNamespace.GetMembers("Class1").Single()); retval8 = type2.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval8.Kind); Assert.Same(retval8, asm4[2].GlobalNamespace.GetMembers("Class2").Single()); retval9 = type2.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval9.Kind); Assert.Same(retval9, asm4[1].GlobalNamespace.GetMembers("Class4").Single()); Assert.Equal("MTTestLib4", asm4[4].Identity.Name); Assert.Equal(8, (from a in asm4[4].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(2, (from a in asm4[4].BoundReferences() where object.ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal(2, (from a in asm4[4].BoundReferences() where object.ReferenceEquals(a, asm4[1]) select a).Count()); Assert.Equal(2, (from a in asm4[4].BoundReferences() where object.ReferenceEquals(a, asm4[2]) select a).Count()); Assert.Equal(2, (from a in asm4[4].BoundReferences() where object.ReferenceEquals(a, asm4[3]) select a).Count()); type3 = asm4[4].GlobalNamespace.GetTypeMembers("Class6"). Single(); retval10 = type3.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval10.Kind); Assert.Same(retval10, asm4[2].GlobalNamespace.GetMembers("Class1").Single()); retval11 = type3.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval11.Kind); Assert.Same(retval11, asm4[2].GlobalNamespace.GetMembers("Class2").Single()); retval12 = type3.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval12.Kind); Assert.Same(retval12, asm4[2].GlobalNamespace.GetMembers("Class3").Single()); retval13 = type3.GetMembers("Foo4").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval13.Kind); Assert.Same(retval13, asm4[1].GlobalNamespace.GetMembers("Class4").Single()); retval14 = type3.GetMembers("Foo5").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval14.Kind); Assert.Same(retval14, asm4[3].GlobalNamespace.GetMembers("Class5").Single()); Assert.Same(asm5[0], asm2[0]); Assert.True(asm5[1].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(asm3[3])); Assert.Same(asm6[0], asm2[0]); Assert.True(asm6[1].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(varC_MTTestLib2.SourceAssembly())); Assert.Same(asm7[0], asm2[0]); Assert.True(asm7[1].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(varC_MTTestLib2.SourceAssembly())); Assert.NotSame(asm7[2], asm3[3]); Assert.NotSame(asm7[2], asm4[3]); Assert.NotSame(asm7[3], asm4[4]); Assert.Equal("MTTestLib3", asm7[2].Identity.Name); Assert.Same(((RetargetingAssemblySymbol)asm7[2]).UnderlyingAssembly, asm3[3]); Assert.Equal(4, (from a in asm7[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(2, (from a in asm7[2].BoundReferences() where object.ReferenceEquals(a, asm7[0]) select a).Count()); Assert.Equal(2, (from a in asm7[2].BoundReferences() where object.ReferenceEquals(a, asm7[1]) select a).Count()); type4 = asm7[2].GlobalNamespace.GetTypeMembers("Class5"). Single(); retval15 = type4.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; missingAssembly = retval15.ContainingAssembly; Assert.True(missingAssembly.IsMissing); Assert.Equal("MTTestLib1", missingAssembly.Identity.Name); retval16 = type4.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.Same(missingAssembly, retval16.ContainingAssembly); retval17 = type4.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval17.Kind); Assert.Same(retval17, asm7[1].GlobalNamespace.GetMembers("Class4").Single()); Assert.Equal("MTTestLib4", asm7[3].Identity.Name); Assert.Same(((RetargetingAssemblySymbol)asm7[3]).UnderlyingAssembly, asm4[4]); Assert.Equal(6, (from a in asm7[3].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(2, (from a in asm7[3].BoundReferences() where object.ReferenceEquals(a, asm7[0]) select a).Count()); Assert.Equal(2, (from a in asm7[3].BoundReferences() where object.ReferenceEquals(a, asm7[1]) select a).Count()); Assert.Equal(2, (from a in asm7[3].BoundReferences() where object.ReferenceEquals(a, asm7[2]) select a).Count()); type5 = asm7[3].GlobalNamespace.GetTypeMembers("Class6"). Single(); retval18 = type5.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal("MTTestLib1", ((MissingMetadataTypeSymbol)retval18).ContainingAssembly.Identity.Name); retval19 = type5.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.Same(retval18.ContainingAssembly, retval19.ContainingAssembly); retval20 = type5.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.Same(retval18.ContainingAssembly, retval20.ContainingAssembly); retval21 = type5.GetMembers("Foo4").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval21.Kind); Assert.Same(retval21, asm7[1].GlobalNamespace.GetMembers("Class4").Single()); retval22 = type5.GetMembers("Foo5").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval22.Kind); Assert.Same(retval22, asm7[2].GlobalNamespace.GetMembers("Class5").Single()); } [Fact] public void MultiTargeting4() { var localC1_V1_Name = new AssemblyIdentity("c1", new Version("1.0.0.0")); var localC1_V1 = CreateCompilation(localC1_V1_Name, new string[] { // AssemblyPaths.SymbolsTests.MultiTargeting.Source1Module.netmodule @" public class C1<T> { public class C2<S> { public C1<T>.C2<S> Foo() { return null; } } } " }, new[] { Net451.mscorlib }); var asm1_V1 = localC1_V1.SourceAssembly(); var localC1_V2_Name = new AssemblyIdentity("c1", new Version("2.0.0.0")); var localC1_V2 = CreateCompilation(localC1_V2_Name, new string[] { // AssemblyPaths.SymbolsTests.MultiTargeting.Source1Module.netmodule @" public class C1<T> { public class C2<S> { public C1<T>.C2<S> Foo() { return null; } } } " }, new MetadataReference[] { Net451.mscorlib }); var asm1_V2 = localC1_V2.SourceAssembly(); var localC4_V1_Name = new AssemblyIdentity("c4", new Version("1.0.0.0")); var localC4_V1 = CreateCompilation(localC4_V1_Name, new string[] { // AssemblyPaths.SymbolsTests.MultiTargeting.Source4Module.netmodule @" public class C4 { } " }, new MetadataReference[] { Net451.mscorlib }); var asm4_V1 = localC4_V1.SourceAssembly(); var localC4_V2_Name = new AssemblyIdentity("c4", new Version("2.0.0.0")); var localC4_V2 = CreateCompilation(localC4_V2_Name, new string[] { // AssemblyPaths.SymbolsTests.MultiTargeting.Source4Module.netmodule @" public class C4 { } " }, new MetadataReference[] { Net451.mscorlib }); var asm4_V2 = localC4_V2.SourceAssembly(); var c7 = CreateCompilation(new AssemblyIdentity("C7"), new string[] { // AssemblyPaths.SymbolsTests.MultiTargeting.Source7Module.netmodule @" public class C7 {} public class C8<T> { } " }, new MetadataReference[] { Net451.mscorlib }); var asm7 = c7.SourceAssembly(); var c3 = CreateCompilation(new AssemblyIdentity("C3"), new string[] { // AssemblyPaths.SymbolsTests.MultiTargeting.Source3Module.netmodule @" public class C3 { public C1<C3>.C2<C4> Foo() { return null; } public static C6<C4> Bar() { return null; } public C8<C7> Foo1() { return null; } public void Foo2(ref C300[,] x1, out C4 x2, ref C7[] x3, C4 x4 = null) { x2 = null; } internal virtual TFoo3 Foo3<TFoo3>() where TFoo3: C4 { return null; } public C8<C4> Foo4() { return null; } public abstract class C301 : I1 { } internal class C302 { } } public class C6<T> where T: new () {} public class C300 {} public interface I1 {} namespace ns1 { namespace ns2 { public class C303 {} } public class C304 { public class C305 {} } } " }, new MetadataReference[] { Net451.mscorlib, new CSharpCompilationReference(localC1_V1), new CSharpCompilationReference(localC4_V1), new CSharpCompilationReference(c7) }); var asm3 = c3.SourceAssembly(); var localC3Foo2 = asm3.GlobalNamespace.GetTypeMembers("C3"). Single().GetMembers("Foo2").OfType<MethodSymbol>().Single(); var c5 = CreateCompilation(new AssemblyIdentity("C5"), new string[] { // AssemblyPaths.SymbolsTests.MultiTargeting.Source5Module.netmodule @" public class C5 : ns1.C304.C305 {} " }, new MetadataReference[] { Net451.mscorlib, new CSharpCompilationReference(c3), new CSharpCompilationReference(localC1_V2), new CSharpCompilationReference(localC4_V2), new CSharpCompilationReference(c7) }); var asm5 = c5.SourceAssembly().BoundReferences(); Assert.NotSame(asm5[1], asm3); Assert.Same(((RetargetingAssemblySymbol)asm5[1]).UnderlyingAssembly, asm3); Assert.Same(asm5[2], asm1_V2); Assert.Same(asm5[3], asm4_V2); Assert.Same(asm5[4], asm7); var type3 = asm5[1].GlobalNamespace.GetTypeMembers("C3"). Single(); var type1 = asm1_V2.GlobalNamespace.GetTypeMembers("C1"). Single(); var type2 = type1.GetTypeMembers("C2"). Single(); var type4 = asm4_V2.GlobalNamespace.GetTypeMembers("C4"). Single(); var retval1 = (NamedTypeSymbol)type3.GetMembers("Foo").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal("C1<C3>.C2<C4>", retval1.ToTestDisplayString()); Assert.Same(retval1.OriginalDefinition, type2); var args1 = retval1.ContainingType.TypeArguments().Concat(retval1.TypeArguments()); var params1 = retval1.ContainingType.TypeParameters.Concat(retval1.TypeParameters); Assert.Same(params1[0], type1.TypeParameters[0]); Assert.Same(params1[1].OriginalDefinition, type2.TypeParameters[0].OriginalDefinition); Assert.Same(args1[0], type3); Assert.Same(args1[0].ContainingAssembly, asm5[1]); Assert.Same(args1[1], type4); var retval2 = retval1.ContainingType; Assert.Equal("C1<C3>", retval2.ToTestDisplayString()); Assert.Same(retval2.OriginalDefinition, type1); var bar = type3.GetMembers("Bar").OfType<MethodSymbol>().Single(); var retval3 = (NamedTypeSymbol)bar.ReturnType; var type6 = asm5[1].GlobalNamespace.GetTypeMembers("C6"). Single(); Assert.Equal("C6<C4>", retval3.ToTestDisplayString()); Assert.Same(retval3.OriginalDefinition, type6); Assert.Same(retval3.ContainingAssembly, asm5[1]); var args3 = retval3.TypeArguments(); var params3 = retval3.TypeParameters; Assert.Same(params3[0], type6.TypeParameters[0]); Assert.Same(params3[0].ContainingAssembly, asm5[1]); Assert.Same(args3[0], type4); var foo1 = type3.GetMembers("Foo1").OfType<MethodSymbol>().Single(); var retval4 = foo1.ReturnType; Assert.Equal("C8<C7>", retval4.ToTestDisplayString()); Assert.Same(retval4, asm3.GlobalNamespace.GetTypeMembers("C3"). Single(). GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType); var foo1Params = foo1.Parameters; Assert.Equal(0, foo1Params.Length); var foo2 = type3.GetMembers("Foo2").OfType<MethodSymbol>().Single(); Assert.NotEqual(localC3Foo2, foo2); Assert.Same(localC3Foo2, ((RetargetingMethodSymbol)foo2).UnderlyingMethod); Assert.Equal(1, ((RetargetingMethodSymbol)foo2).Locations.Length); var foo2Params = foo2.Parameters; Assert.Equal(4, foo2Params.Length); Assert.Same(localC3Foo2.Parameters[0], ((RetargetingParameterSymbol)foo2Params[0]).UnderlyingParameter); Assert.Same(localC3Foo2.Parameters[1], ((RetargetingParameterSymbol)foo2Params[1]).UnderlyingParameter); Assert.Same(localC3Foo2.Parameters[2], ((RetargetingParameterSymbol)foo2Params[2]).UnderlyingParameter); Assert.Same(localC3Foo2.Parameters[3], ((RetargetingParameterSymbol)foo2Params[3]).UnderlyingParameter); var x1 = foo2Params[0]; var x2 = foo2Params[1]; var x3 = foo2Params[2]; var x4 = foo2Params[3]; Assert.Equal("x1", x1.Name); Assert.NotEqual(localC3Foo2.Parameters[0].Type, x1.Type); Assert.Equal(localC3Foo2.Parameters[0].ToTestDisplayString(), x1.ToTestDisplayString()); Assert.Same(asm5[1], x1.ContainingAssembly); Assert.Same(foo2, x1.ContainingSymbol); Assert.False(x1.HasExplicitDefaultValue); Assert.False(x1.IsOptional); Assert.Equal(RefKind.Ref, x1.RefKind); Assert.Equal(2, ((ArrayTypeSymbol)x1.Type).Rank); Assert.Equal("x2", x2.Name); Assert.NotEqual(localC3Foo2.Parameters[1].Type, x2.Type); Assert.Equal(RefKind.Out, x2.RefKind); Assert.Equal("x3", x3.Name); Assert.Same(localC3Foo2.Parameters[2].Type, x3.Type); Assert.Equal("x4", x4.Name); Assert.True(x4.HasExplicitDefaultValue); Assert.True(x4.IsOptional); Assert.Equal("Foo2", foo2.Name); Assert.Equal(localC3Foo2.ToTestDisplayString(), foo2.ToTestDisplayString()); Assert.Same(asm5[1], foo2.ContainingAssembly); Assert.Same(type3, foo2.ContainingSymbol); Assert.Equal(Accessibility.Public, foo2.DeclaredAccessibility); Assert.False(foo2.HidesBaseMethodsByName); Assert.False(foo2.IsAbstract); Assert.False(foo2.IsExtern); Assert.False(foo2.IsGenericMethod); Assert.False(foo2.IsOverride); Assert.False(foo2.IsSealed); Assert.False(foo2.IsStatic); Assert.False(foo2.IsVararg); Assert.False(foo2.IsVirtual); Assert.True(foo2.ReturnsVoid); Assert.Equal(0, foo2.TypeParameters.Length); Assert.Equal(0, foo2.TypeArgumentsWithAnnotations.Length); Assert.True(bar.IsStatic); Assert.False(bar.ReturnsVoid); var foo3 = type3.GetMembers("Foo3").OfType<MethodSymbol>().Single(); Assert.Equal(Accessibility.Internal, foo3.DeclaredAccessibility); Assert.True(foo3.IsGenericMethod); Assert.True(foo3.IsVirtual); var foo3TypeParams = foo3.TypeParameters; Assert.Equal(1, foo3TypeParams.Length); Assert.Equal(1, foo3.TypeArgumentsWithAnnotations.Length); Assert.Same(foo3TypeParams[0], foo3.TypeArgumentsWithAnnotations[0].Type); var typeC301 = type3.GetTypeMembers("C301").Single(); var typeC302 = type3.GetTypeMembers("C302").Single(); var typeC6 = asm5[1].GlobalNamespace.GetTypeMembers("C6").Single(); Assert.Equal(typeC301.ToTestDisplayString(), asm3.GlobalNamespace.GetTypeMembers("C3").Single(). GetTypeMembers("C301").Single().ToTestDisplayString()); Assert.Equal(typeC6.ToTestDisplayString(), asm3.GlobalNamespace.GetTypeMembers("C6").Single().ToTestDisplayString()); Assert.Equal(typeC301.ToDisplayString(SymbolDisplayFormat.QualifiedNameArityFormat), asm3.GlobalNamespace.GetTypeMembers("C3").Single(). GetTypeMembers("C301").Single().ToDisplayString(SymbolDisplayFormat.QualifiedNameArityFormat)); Assert.Equal(typeC6.ToDisplayString(SymbolDisplayFormat.QualifiedNameArityFormat), asm3.GlobalNamespace.GetTypeMembers("C6").Single().ToDisplayString(SymbolDisplayFormat.QualifiedNameArityFormat)); Assert.Equal(type3.GetMembers().Length, asm3.GlobalNamespace.GetTypeMembers("C3").Single().GetMembers().Length); Assert.Equal(type3.GetTypeMembers().Length, asm3.GlobalNamespace.GetTypeMembers("C3").Single().GetTypeMembers().Length); Assert.Same(typeC301, type3.GetTypeMembers("C301", 0).Single()); Assert.Equal(0, type3.Arity); Assert.Equal(1, typeC6.Arity); Assert.NotNull(type3.BaseType()); Assert.Equal("System.Object", type3.BaseType().ToTestDisplayString()); Assert.Equal(Accessibility.Public, type3.DeclaredAccessibility); Assert.Equal(Accessibility.Internal, typeC302.DeclaredAccessibility); Assert.Equal(0, type3.Interfaces().Length); Assert.Equal(1, typeC301.Interfaces().Length); Assert.Equal("I1", typeC301.Interfaces().Single().Name); Assert.False(type3.IsAbstract); Assert.True(typeC301.IsAbstract); Assert.False(type3.IsSealed); Assert.False(type3.IsStatic); Assert.Equal(0, type3.TypeArguments().Length); Assert.Equal(0, type3.TypeParameters.Length); var localC6Params = typeC6.TypeParameters; Assert.Equal(1, localC6Params.Length); Assert.Equal(1, typeC6.TypeArguments().Length); Assert.Same(localC6Params[0], typeC6.TypeArguments()[0]); Assert.Same(((RetargetingNamedTypeSymbol)type3).UnderlyingNamedType, asm3.GlobalNamespace.GetTypeMembers("C3").Single()); Assert.Equal(1, ((RetargetingNamedTypeSymbol)type3).Locations.Length); Assert.Equal(TypeKind.Class, type3.TypeKind); Assert.Equal(TypeKind.Interface, asm5[1].GlobalNamespace.GetTypeMembers("I1").Single().TypeKind); var localC6_T = localC6Params[0]; var foo3TypeParam = foo3TypeParams[0]; Assert.Equal(0, localC6_T.ConstraintTypes().Length); Assert.Equal(1, foo3TypeParam.ConstraintTypes().Length); Assert.Same(type4, foo3TypeParam.ConstraintTypes().Single()); Assert.Same(typeC6, localC6_T.ContainingSymbol); Assert.False(foo3TypeParam.HasConstructorConstraint); Assert.True(localC6_T.HasConstructorConstraint); Assert.False(foo3TypeParam.HasReferenceTypeConstraint); Assert.False(foo3TypeParam.HasValueTypeConstraint); Assert.Equal("TFoo3", foo3TypeParam.Name); Assert.Equal("T", localC6_T.Name); Assert.Equal(0, foo3TypeParam.Ordinal); Assert.Equal(0, localC6_T.Ordinal); Assert.Equal(VarianceKind.None, foo3TypeParam.Variance); Assert.Same(((RetargetingTypeParameterSymbol)localC6_T).UnderlyingTypeParameter, asm3.GlobalNamespace.GetTypeMembers("C6").Single().TypeParameters[0]); var ns1 = asm5[1].GlobalNamespace.GetMembers("ns1").OfType<NamespaceSymbol>().Single(); var ns2 = ns1.GetMembers("ns2").OfType<NamespaceSymbol>().Single(); Assert.Equal("ns1.ns2", ns2.ToTestDisplayString()); Assert.Equal(2, ns1.GetMembers().Length); Assert.Equal(1, ns1.GetTypeMembers().Length); Assert.Same(ns1.GetTypeMembers("C304").Single(), ns1.GetTypeMembers("C304", 0).Single()); Assert.Same(asm5[1].Modules[0], asm5[1].Modules[0].GlobalNamespace.ContainingSymbol); Assert.Same(asm5[1].Modules[0].GlobalNamespace, ns1.ContainingSymbol); Assert.Same(asm5[1].Modules[0], ns1.Extent.Module); Assert.Equal(1, ns1.ConstituentNamespaces.Length); Assert.Same(ns1, ns1.ConstituentNamespaces[0]); Assert.False(ns1.IsGlobalNamespace); Assert.True(asm5[1].Modules[0].GlobalNamespace.IsGlobalNamespace); Assert.Same(asm3.Modules[0].GlobalNamespace, ((RetargetingNamespaceSymbol)asm5[1].Modules[0].GlobalNamespace).UnderlyingNamespace); Assert.Same(asm3.Modules[0].GlobalNamespace.GetMembers("ns1").Single(), ((RetargetingNamespaceSymbol)ns1).UnderlyingNamespace); var module3 = (RetargetingModuleSymbol)asm5[1].Modules[0]; Assert.Equal("C3.dll", module3.ToTestDisplayString()); Assert.Equal("C3.dll", module3.Name); Assert.Same(asm5[1], module3.ContainingSymbol); Assert.Same(asm5[1], module3.ContainingAssembly); Assert.Null(module3.ContainingType); var retval5 = type3.GetMembers("Foo4").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal("C8<C4>", retval5.ToTestDisplayString()); var typeC5 = c5.Assembly.GlobalNamespace.GetTypeMembers("C5").Single(); Assert.Same(asm5[1], typeC5.BaseType().ContainingAssembly); Assert.Equal("ns1.C304.C305", typeC5.BaseType().ToTestDisplayString()); Assert.NotEqual(SymbolKind.ErrorType, typeC5.Kind); } [Fact] public void MultiTargeting5() { var c1_Name = new AssemblyIdentity("c1"); var text = @" class Module1 { Class4 M1() {} Class4.Class4_1 M2() {} Class4 M3() {} } "; var c1 = CreateEmptyCompilation(text, new MetadataReference[] { MscorlibRef, TestReferences.SymbolsTests.V1.MTTestLib1.dll, TestReferences.SymbolsTests.V1.MTTestModule2.netmodule }); var c2_Name = new AssemblyIdentity("MTTestLib2"); var c2 = CreateCompilation(c2_Name, null, new MetadataReference[] { Net451.mscorlib, TestReferences.SymbolsTests.V2.MTTestLib1.dll, new CSharpCompilationReference(c1) }); SourceAssemblySymbol c1AsmSource = (SourceAssemblySymbol)c1.Assembly; PEAssemblySymbol Lib1_V1 = (PEAssemblySymbol)c1AsmSource.Modules[0].GetReferencedAssemblySymbols()[1]; PEModuleSymbol module1 = (PEModuleSymbol)c1AsmSource.Modules[1]; Assert.Equal(LocationKind.MetadataFile, ((MetadataLocation)Lib1_V1.Locations[0]).Kind); SourceAssemblySymbol c2AsmSource = (SourceAssemblySymbol)c2.Assembly; RetargetingAssemblySymbol c1AsmRef = (RetargetingAssemblySymbol)c2AsmSource.Modules[0].GetReferencedAssemblySymbols()[2]; PEAssemblySymbol Lib1_V2 = (PEAssemblySymbol)c2AsmSource.Modules[0].GetReferencedAssemblySymbols()[1]; PEModuleSymbol module2 = (PEModuleSymbol)c1AsmRef.Modules[1]; Assert.Equal(1, Lib1_V1.Identity.Version.Major); Assert.Equal(2, Lib1_V2.Identity.Version.Major); Assert.NotEqual(module1, module2); Assert.Same(module1.Module, module2.Module); NamedTypeSymbol classModule1 = c1AsmRef.Modules[0].GlobalNamespace.GetTypeMembers("Module1").Single(); MethodSymbol m1 = classModule1.GetMembers("M1").OfType<MethodSymbol>().Single(); MethodSymbol m2 = classModule1.GetMembers("M2").OfType<MethodSymbol>().Single(); MethodSymbol m3 = classModule1.GetMembers("M3").OfType<MethodSymbol>().Single(); Assert.Same(module2, m1.ReturnType.ContainingModule); Assert.Same(module2, m2.ReturnType.ContainingModule); Assert.Same(module2, m3.ReturnType.ContainingModule); } // Very simplistic test if a compilation has a single type with the given full name. Does NOT handle generics. private bool HasSingleTypeOfKind(CSharpCompilation c, TypeKind kind, string fullName) { string[] names = fullName.Split('.'); NamespaceOrTypeSymbol current = c.GlobalNamespace; foreach (string name in names) { var matchingSym = current.GetMembers(name); if (matchingSym.Length != 1) { return false; } current = (NamespaceOrTypeSymbol)matchingSym.First(); } return current is TypeSymbol && ((TypeSymbol)current).TypeKind == kind; } [Fact] public void AddRemoveReferences() { var mscorlibRef = Net451.mscorlib; var systemCoreRef = Net451.SystemCore; var systemRef = Net451.System; CSharpCompilation c = CSharpCompilation.Create("Test"); Assert.False(HasSingleTypeOfKind(c, TypeKind.Struct, "System.Int32")); c = c.AddReferences(mscorlibRef); Assert.True(HasSingleTypeOfKind(c, TypeKind.Struct, "System.Int32")); Assert.False(HasSingleTypeOfKind(c, TypeKind.Class, "System.Linq.Enumerable")); c = c.AddReferences(systemCoreRef); Assert.True(HasSingleTypeOfKind(c, TypeKind.Class, "System.Linq.Enumerable")); Assert.False(HasSingleTypeOfKind(c, TypeKind.Class, "System.Uri")); c = c.ReplaceReference(systemCoreRef, systemRef); Assert.False(HasSingleTypeOfKind(c, TypeKind.Class, "System.Linq.Enumerable")); Assert.True(HasSingleTypeOfKind(c, TypeKind.Class, "System.Uri")); c = c.RemoveReferences(systemRef); Assert.False(HasSingleTypeOfKind(c, TypeKind.Class, "System.Uri")); Assert.True(HasSingleTypeOfKind(c, TypeKind.Struct, "System.Int32")); c = c.RemoveReferences(mscorlibRef); Assert.False(HasSingleTypeOfKind(c, TypeKind.Struct, "System.Int32")); } private sealed class Resolver : MetadataReferenceResolver { private readonly string _data, _core, _system; public Resolver(string data, string core, string system) { _data = data; _core = core; _system = system; } public override ImmutableArray<PortableExecutableReference> ResolveReference(string reference, string baseFilePath, MetadataReferenceProperties properties) { switch (reference) { case "System.Data": return ImmutableArray.Create(MetadataReference.CreateFromFile(_data)); case "System.Core": return ImmutableArray.Create(MetadataReference.CreateFromFile(_core)); case "System": return ImmutableArray.Create(MetadataReference.CreateFromFile(_system)); default: if (File.Exists(reference)) { return ImmutableArray.Create(MetadataReference.CreateFromFile(reference)); } return ImmutableArray<PortableExecutableReference>.Empty; } } public override bool Equals(object other) => true; public override int GetHashCode() => 1; } [Fact] public void CompilationWithReferenceDirectives() { var data = Temp.CreateFile().WriteAllBytes(ResourcesNet451.SystemData).Path; var core = Temp.CreateFile().WriteAllBytes(ResourcesNet451.SystemCore).Path; var xml = Temp.CreateFile().WriteAllBytes(ResourcesNet451.SystemXml).Path; var system = Temp.CreateFile().WriteAllBytes(ResourcesNet451.System).Path; var trees = new[] { SyntaxFactory.ParseSyntaxTree($@" #r ""System.Data"" #r ""{xml}"" #r ""{core}"" ", options: TestOptions.Script), SyntaxFactory.ParseSyntaxTree(@" #r ""System"" ", options: TestOptions.Script), SyntaxFactory.ParseSyntaxTree(@" new System.Data.DataSet(); System.Linq.Expressions.Expression.Constant(123); System.Diagnostics.Process.GetCurrentProcess(); ", options: TestOptions.Script) }; var compilation = CreateCompilationWithMscorlib45( trees, options: TestOptions.ReleaseDll.WithMetadataReferenceResolver(new Resolver(data, core, system))); compilation.VerifyDiagnostics(); var boundRefs = compilation.Assembly.BoundReferences(); AssertEx.Equal(new[] { "System.Data", "System.Xml", "System.Core", "System", "mscorlib" }, boundRefs.Select(r => r.Name)); } [Fact] public void CompilationWithReferenceDirectives_Errors() { var data = Temp.CreateFile().WriteAllBytes(ResourcesNet451.SystemData).Path; var core = Temp.CreateFile().WriteAllBytes(ResourcesNet451.SystemCore).Path; var system = Temp.CreateFile().WriteAllBytes(ResourcesNet451.System).Path; var trees = new[] { SyntaxFactory.ParseSyntaxTree(@" #r System #r ""~!@#$%^&*():\?/"" #r ""non-existing-reference"" ", options: TestOptions.Script), SyntaxFactory.ParseSyntaxTree(@" #r ""System.Core"" ", TestOptions.Regular) }; var compilation = CreateCompilationWithMscorlib45( trees, options: TestOptions.ReleaseDll.WithMetadataReferenceResolver(new Resolver(data, core, system))); compilation.VerifyDiagnostics( // (3,1): error CS0006: Metadata file '~!@#$%^&*():\?/' could not be found Diagnostic(ErrorCode.ERR_NoMetadataFile, @"#r ""~!@#$%^&*():\?/""").WithArguments(@"~!@#$%^&*():\?/"), // (4,1): error CS0006: Metadata file 'non-existing-reference' could not be found Diagnostic(ErrorCode.ERR_NoMetadataFile, @"#r ""non-existing-reference""").WithArguments("non-existing-reference"), // (2,4): error CS7010: Quoted file name expected Diagnostic(ErrorCode.ERR_ExpectedPPFile, "System"), // (2,1): error CS7011: #r is only allowed in scripts Diagnostic(ErrorCode.ERR_ReferenceDirectiveOnlyAllowedInScripts, "r")); } private class DummyReferenceResolver : MetadataReferenceResolver { private readonly string _targetDll; public DummyReferenceResolver(string targetDll) { _targetDll = targetDll; } public override ImmutableArray<PortableExecutableReference> ResolveReference(string reference, string baseFilePath, MetadataReferenceProperties properties) { var path = reference.EndsWith("-resolve", StringComparison.Ordinal) ? _targetDll : reference; return ImmutableArray.Create(MetadataReference.CreateFromFile(path, properties)); } public override bool Equals(object other) => true; public override int GetHashCode() => 1; } [Fact] public void MetadataReferenceProvider() { var csClasses01 = Temp.CreateFile().WriteAllBytes(TestResources.MetadataTests.InterfaceAndClass.CSClasses01).Path; var csInterfaces01 = Temp.CreateFile().WriteAllBytes(TestResources.MetadataTests.InterfaceAndClass.CSInterfaces01).Path; var source = @" #r """ + "!@#$%^/&*-resolve" + @""" #r """ + csInterfaces01 + @""" class C : Metadata.ICSPropImpl { }"; var compilation = CreateCompilationWithMscorlib45( new[] { Parse(source, options: TestOptions.Script) }, options: TestOptions.ReleaseDll.WithMetadataReferenceResolver(new DummyReferenceResolver(csClasses01))); compilation.VerifyDiagnostics(); } [Fact] public void CompilationWithReferenceDirective_NoResolver() { var compilation = CreateCompilationWithMscorlib45( new[] { SyntaxFactory.ParseSyntaxTree(@"#r ""bar""", TestOptions.Script, "a.csx", Encoding.UTF8) }, options: TestOptions.ReleaseDll.WithMetadataReferenceResolver(null)); compilation.VerifyDiagnostics( // a.csx(1,1): error CS7099: Metadata references not supported. // #r "bar" Diagnostic(ErrorCode.ERR_MetadataReferencesNotSupported, @"#r ""bar""")); } [Fact] public void GlobalUsings1() { var trees = new[] { SyntaxFactory.ParseSyntaxTree(@" WriteLine(1); Console.WriteLine(2); ", options: TestOptions.Script), SyntaxFactory.ParseSyntaxTree(@" class C { void Foo() { Console.WriteLine(3); } } ", TestOptions.Regular) }; var compilation = CreateCompilationWithMscorlib45( trees, options: TestOptions.ReleaseDll.WithUsings(ImmutableArray.Create("System.Console", "System"))); var diagnostics = compilation.GetDiagnostics().ToArray(); // global usings are only visible in script code: DiagnosticsUtils.VerifyErrorCodes(diagnostics, // (4,18): error CS0103: The name 'Console' does not exist in the current context new ErrorDescription() { Code = (int)ErrorCode.ERR_NameNotInContext, Line = 4, Column = 18 }); } [Fact] public void GlobalUsings_Errors() { var trees = new[] { SyntaxFactory.ParseSyntaxTree(@" WriteLine(1); Console.WriteLine(2); ", options: TestOptions.Script) }; var compilation = CreateCompilationWithMscorlib45( trees, options: TestOptions.ReleaseDll.WithUsings("System.Console!", "Blah")); compilation.VerifyDiagnostics( // error CS0234: The type or namespace name 'Console!' does not exist in the namespace 'System' (are you missing an assembly reference?) Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS).WithArguments("Console!", "System"), // error CS0246: The type or namespace name 'Blah' could not be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound).WithArguments("Blah"), // (2,1): error CS0103: The name 'WriteLine' does not exist in the current context Diagnostic(ErrorCode.ERR_NameNotInContext, "WriteLine").WithArguments("WriteLine"), // (3,1): error CS0103: The name 'Console' does not exist in the current context Diagnostic(ErrorCode.ERR_NameNotInContext, "Console").WithArguments("Console")); } [Fact] public void ReferenceToAssemblyWithSpecialCharactersInName() { var r = TestReferences.SymbolsTests.Metadata.InvalidCharactersInAssemblyName; var st = SyntaxFactory.ParseSyntaxTree("class C { static void Main() { new lib.Class1(); } }"); var compilation = CSharpCompilation.Create("foo", references: new[] { MscorlibRef, r }, syntaxTrees: new[] { st }); var diags = compilation.GetDiagnostics().ToArray(); Assert.Equal(0, diags.Length); using (var stream = new MemoryStream()) { compilation.Emit(stream); } } [Fact] public void SyntaxTreeOrderConstruct() { var tree1 = CreateSyntaxTree("A"); var tree2 = CreateSyntaxTree("B"); SyntaxTree[] treeOrder1 = new[] { tree1, tree2 }; var compilation1 = CSharpCompilation.Create("Compilation1", syntaxTrees: treeOrder1); CheckCompilationSyntaxTrees(compilation1, treeOrder1); SyntaxTree[] treeOrder2 = new[] { tree2, tree1 }; var compilation2 = CSharpCompilation.Create("Compilation2", syntaxTrees: treeOrder2); CheckCompilationSyntaxTrees(compilation2, treeOrder2); } [Fact] public void SyntaxTreeOrderAdd() { var tree1 = CreateSyntaxTree("A"); var tree2 = CreateSyntaxTree("B"); var tree3 = CreateSyntaxTree("C"); var tree4 = CreateSyntaxTree("D"); SyntaxTree[] treeList1 = new[] { tree1, tree2 }; var compilation1 = CSharpCompilation.Create("Compilation1", syntaxTrees: treeList1); CheckCompilationSyntaxTrees(compilation1, treeList1); SyntaxTree[] treeList2 = new[] { tree3, tree4 }; var compilation2 = compilation1.AddSyntaxTrees(treeList2); CheckCompilationSyntaxTrees(compilation1, treeList1); //compilation1 untouched CheckCompilationSyntaxTrees(compilation2, treeList1.Concat(treeList2).ToArray()); SyntaxTree[] treeList3 = new[] { tree4, tree3 }; var compilation3 = CSharpCompilation.Create("Compilation3", syntaxTrees: treeList3); CheckCompilationSyntaxTrees(compilation3, treeList3); SyntaxTree[] treeList4 = new[] { tree2, tree1 }; var compilation4 = compilation3.AddSyntaxTrees(treeList4); CheckCompilationSyntaxTrees(compilation3, treeList3); //compilation3 untouched CheckCompilationSyntaxTrees(compilation4, treeList3.Concat(treeList4).ToArray()); } [Fact] public void SyntaxTreeOrderRemove() { var tree1 = CreateSyntaxTree("A"); var tree2 = CreateSyntaxTree("B"); var tree3 = CreateSyntaxTree("C"); var tree4 = CreateSyntaxTree("D"); SyntaxTree[] treeList1 = new[] { tree1, tree2, tree3, tree4 }; var compilation1 = CSharpCompilation.Create("Compilation1", syntaxTrees: treeList1); CheckCompilationSyntaxTrees(compilation1, treeList1); SyntaxTree[] treeList2 = new[] { tree3, tree1 }; var compilation2 = compilation1.RemoveSyntaxTrees(treeList2); CheckCompilationSyntaxTrees(compilation1, treeList1); //compilation1 untouched CheckCompilationSyntaxTrees(compilation2, tree2, tree4); SyntaxTree[] treeList3 = new[] { tree4, tree3, tree2, tree1 }; var compilation3 = CSharpCompilation.Create("Compilation3", syntaxTrees: treeList3); CheckCompilationSyntaxTrees(compilation3, treeList3); SyntaxTree[] treeList4 = new[] { tree3, tree1 }; var compilation4 = compilation3.RemoveSyntaxTrees(treeList4); CheckCompilationSyntaxTrees(compilation3, treeList3); //compilation3 untouched CheckCompilationSyntaxTrees(compilation4, tree4, tree2); } [Fact] public void SyntaxTreeOrderReplace() { var tree1 = CreateSyntaxTree("A"); var tree2 = CreateSyntaxTree("B"); var tree3 = CreateSyntaxTree("C"); SyntaxTree[] treeList1 = new[] { tree1, tree2 }; var compilation1 = CSharpCompilation.Create("Compilation1", syntaxTrees: treeList1); CheckCompilationSyntaxTrees(compilation1, treeList1); var compilation2 = compilation1.ReplaceSyntaxTree(tree1, tree3); CheckCompilationSyntaxTrees(compilation1, treeList1); //compilation1 untouched CheckCompilationSyntaxTrees(compilation2, tree3, tree2); SyntaxTree[] treeList3 = new[] { tree2, tree1 }; var compilation3 = CSharpCompilation.Create("Compilation3", syntaxTrees: treeList3); CheckCompilationSyntaxTrees(compilation3, treeList3); var compilation4 = compilation3.ReplaceSyntaxTree(tree1, tree3); CheckCompilationSyntaxTrees(compilation3, treeList3); //compilation3 untouched CheckCompilationSyntaxTrees(compilation4, tree2, tree3); } [WorkItem(578706, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578706")] [Fact] public void DeclaringCompilationOfAddedModule() { var source1 = "public class C1 { }"; var source2 = "public class C2 { }"; var lib1 = CreateCompilation(source1, assemblyName: "Lib1", options: TestOptions.ReleaseModule); var ref1 = lib1.EmitToImageReference(); // NOTE: can't use a compilation reference for a module. var lib2 = CreateCompilation(source2, new[] { ref1 }, assemblyName: "Lib2"); lib2.VerifyDiagnostics(); var sourceAssembly = lib2.Assembly; var sourceModule = sourceAssembly.Modules[0]; var sourceType = sourceModule.GlobalNamespace.GetMember<NamedTypeSymbol>("C2"); Assert.IsType<SourceAssemblySymbol>(sourceAssembly); Assert.Equal(lib2, sourceAssembly.DeclaringCompilation); Assert.IsType<SourceModuleSymbol>(sourceModule); Assert.Equal(lib2, sourceModule.DeclaringCompilation); Assert.IsType<SourceNamedTypeSymbol>(sourceType); Assert.Equal(lib2, sourceType.DeclaringCompilation); var addedModule = sourceAssembly.Modules[1]; var addedModuleAssembly = addedModule.ContainingAssembly; var addedModuleType = addedModule.GlobalNamespace.GetMember<NamedTypeSymbol>("C1"); Assert.IsType<SourceAssemblySymbol>(addedModuleAssembly); Assert.Equal(lib2, addedModuleAssembly.DeclaringCompilation); //NB: not lib1, not null Assert.IsType<PEModuleSymbol>(addedModule); Assert.Null(addedModule.DeclaringCompilation); Assert.IsAssignableFrom<PENamedTypeSymbol>(addedModuleType); Assert.Null(addedModuleType.DeclaringCompilation); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Text; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using static Roslyn.Test.Utilities.TestMetadata; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class CompilationCreationTests : CSharpTestBase { #region Helpers private static SyntaxTree CreateSyntaxTree(string className) { var text = string.Format("public partial class {0} {{ }}", className); var path = string.Format("{0}.cs", className); return SyntaxFactory.ParseSyntaxTree(text, path: path); } private static void CheckCompilationSyntaxTrees(CSharpCompilation compilation, params SyntaxTree[] expectedSyntaxTrees) { ImmutableArray<SyntaxTree> actualSyntaxTrees = compilation.SyntaxTrees; int numTrees = expectedSyntaxTrees.Length; Assert.Equal(numTrees, actualSyntaxTrees.Length); for (int i = 0; i < numTrees; i++) { Assert.Equal(expectedSyntaxTrees[i], actualSyntaxTrees[i]); } for (int i = 0; i < numTrees; i++) { for (int j = 0; j < numTrees; j++) { Assert.Equal(Math.Sign(compilation.CompareSyntaxTreeOrdering(expectedSyntaxTrees[i], expectedSyntaxTrees[j])), Math.Sign(i.CompareTo(j))); } } var types = expectedSyntaxTrees.Select(tree => compilation.GetSemanticModel(tree).GetDeclaredSymbol(tree.GetCompilationUnitRoot().Members.Single())).ToArray(); for (int i = 0; i < numTrees; i++) { for (int j = 0; j < numTrees; j++) { Assert.Equal(Math.Sign(compilation.CompareSourceLocations(types[i].Locations[0], types[j].Locations[0])), Math.Sign(i.CompareTo(j))); } } } #endregion [Fact] public void CorLibTypes() { var mdTestLib1 = TestReferences.SymbolsTests.MDTestLib1; var c1 = CSharpCompilation.Create("Test", references: new MetadataReference[] { MscorlibRef_v4_0_30316_17626, mdTestLib1 }); TypeSymbol c107 = c1.GlobalNamespace.GetTypeMembers("C107").Single(); Assert.Equal(SpecialType.None, c107.SpecialType); for (int i = 1; i <= (int)SpecialType.Count; i++) { NamedTypeSymbol type = c1.GetSpecialType((SpecialType)i); if (i == (int)SpecialType.System_Runtime_CompilerServices_RuntimeFeature || i == (int)SpecialType.System_Runtime_CompilerServices_PreserveBaseOverridesAttribute) { Assert.True(type.IsErrorType()); // Not available } else { Assert.False(type.IsErrorType()); } Assert.Equal((SpecialType)i, type.SpecialType); } Assert.Equal(SpecialType.None, c107.SpecialType); var arrayOfc107 = ArrayTypeSymbol.CreateCSharpArray(c1.Assembly, TypeWithAnnotations.Create(c107)); Assert.Equal(SpecialType.None, arrayOfc107.SpecialType); var c2 = CSharpCompilation.Create("Test", references: new[] { mdTestLib1 }); Assert.Equal(SpecialType.None, c2.GlobalNamespace.GetTypeMembers("C107").Single().SpecialType); } [Fact] public void CyclicReference() { var mscorlibRef = Net451.mscorlib; var cyclic2Ref = TestReferences.SymbolsTests.Cyclic.Cyclic2.dll; var tc1 = CSharpCompilation.Create("Cyclic1", references: new[] { mscorlibRef, cyclic2Ref }); Assert.NotNull(tc1.Assembly); // force creation of SourceAssemblySymbol var cyclic1Asm = (SourceAssemblySymbol)tc1.Assembly; var cyclic1Mod = (SourceModuleSymbol)cyclic1Asm.Modules[0]; var cyclic2Asm = (PEAssemblySymbol)tc1.GetReferencedAssemblySymbol(cyclic2Ref); var cyclic2Mod = (PEModuleSymbol)cyclic2Asm.Modules[0]; Assert.Same(cyclic2Mod.GetReferencedAssemblySymbols()[1], cyclic1Asm); Assert.Same(cyclic1Mod.GetReferencedAssemblySymbols()[1], cyclic2Asm); } [Fact] public void MultiTargeting1() { var varV1MTTestLib2Ref = TestReferences.SymbolsTests.V1.MTTestLib2.dll; var asm1 = MetadataTestHelpers.GetSymbolsForReferences(mrefs: new[] { Net451.mscorlib, varV1MTTestLib2Ref }); Assert.Equal("mscorlib", asm1[0].Identity.Name); Assert.Equal(0, asm1[0].BoundReferences().Length); Assert.Equal("MTTestLib2", asm1[1].Identity.Name); Assert.Equal(1, (from a in asm1[1].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm1[1].BoundReferences() where object.ReferenceEquals(a, asm1[0]) select a).Count()); Assert.Equal(SymbolKind.ErrorType, asm1[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Foo").OfType<MethodSymbol>().Single().ReturnType.Kind); var asm2 = MetadataTestHelpers.GetSymbolsForReferences(new[] { Net451.mscorlib, varV1MTTestLib2Ref, TestReferences.SymbolsTests.V1.MTTestLib1.dll }); Assert.Same(asm2[0], asm1[0]); Assert.Equal("MTTestLib2", asm2[1].Identity.Name); Assert.NotSame(asm2[1], asm1[1]); Assert.Same(((PEAssemblySymbol)asm2[1]).Assembly, ((PEAssemblySymbol)asm1[1]).Assembly); Assert.Equal(2, (from a in asm2[1].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm2[1].BoundReferences() where object.ReferenceEquals(a, asm2[0]) select a).Count()); Assert.Equal(1, (from a in asm2[1].BoundReferences() where object.ReferenceEquals(a, asm2[2]) select a).Count()); var retval1 = asm2[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Foo").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval1.Kind); Assert.Same(retval1, asm2[2].GlobalNamespace.GetMembers("Class1").Single()); Assert.Equal("MTTestLib1", asm2[2].Identity.Name); Assert.Equal(1, asm2[2].Identity.Version.Major); Assert.Equal(1, (from a in asm2[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm2[2].BoundReferences() where object.ReferenceEquals(a, asm2[0]) select a).Count()); var varV2MTTestLib3Ref = TestReferences.SymbolsTests.V2.MTTestLib3.dll; var asm3 = MetadataTestHelpers.GetSymbolsForReferences(new[] { Net451.mscorlib, varV1MTTestLib2Ref, TestReferences.SymbolsTests.V2.MTTestLib1.dll, varV2MTTestLib3Ref }); Assert.Same(asm3[0], asm1[0]); Assert.Equal("MTTestLib2", asm3[1].Identity.Name); Assert.NotSame(asm3[1], asm1[1]); Assert.NotSame(asm3[1], asm2[1]); Assert.Same(((PEAssemblySymbol)asm3[1]).Assembly, ((PEAssemblySymbol)asm1[1]).Assembly); Assert.Equal(2, (from a in asm3[1].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm3[1].BoundReferences() where object.ReferenceEquals(a, asm3[0]) select a).Count()); Assert.Equal(1, (from a in asm3[1].BoundReferences() where object.ReferenceEquals(a, asm3[2]) select a).Count()); var retval2 = asm3[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Foo").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval2.Kind); Assert.Same(retval2, asm3[2].GlobalNamespace.GetMembers("Class1").Single()); Assert.Equal("MTTestLib1", asm3[2].Identity.Name); Assert.NotSame(asm3[2], asm2[2]); Assert.NotSame(((PEAssemblySymbol)asm3[2]).Assembly, ((PEAssemblySymbol)asm2[2]).Assembly); Assert.Equal(2, asm3[2].Identity.Version.Major); Assert.Equal(1, (from a in asm3[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm3[2].BoundReferences() where object.ReferenceEquals(a, asm3[0]) select a).Count()); Assert.Equal("MTTestLib3", asm3[3].Identity.Name); Assert.Equal(3, (from a in asm3[3].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm3[3].BoundReferences() where object.ReferenceEquals(a, asm3[0]) select a).Count()); Assert.Equal(1, (from a in asm3[3].BoundReferences() where object.ReferenceEquals(a, asm3[1]) select a).Count()); Assert.Equal(1, (from a in asm3[3].BoundReferences() where object.ReferenceEquals(a, asm3[2]) select a).Count()); var type1 = asm3[3].GlobalNamespace.GetTypeMembers("Class5"). Single(); var retval3 = type1.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval3.Kind); Assert.Same(retval3, asm3[2].GlobalNamespace.GetMembers("Class1").Single()); var retval4 = type1.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval4.Kind); Assert.Same(retval4, asm3[2].GlobalNamespace.GetMembers("Class2").Single()); var retval5 = type1.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval5.Kind); Assert.Same(retval5, asm3[1].GlobalNamespace.GetMembers("Class4").Single()); var varV3MTTestLib4Ref = TestReferences.SymbolsTests.V3.MTTestLib4.dll; var asm4 = MetadataTestHelpers.GetSymbolsForReferences(new MetadataReference[] { Net451.mscorlib, varV1MTTestLib2Ref, TestReferences.SymbolsTests.V3.MTTestLib1.dll, varV2MTTestLib3Ref, varV3MTTestLib4Ref }); Assert.Same(asm3[0], asm1[0]); Assert.Equal("MTTestLib2", asm4[1].Identity.Name); Assert.NotSame(asm4[1], asm1[1]); Assert.NotSame(asm4[1], asm2[1]); Assert.NotSame(asm4[1], asm3[1]); Assert.Same(((PEAssemblySymbol)asm4[1]).Assembly, ((PEAssemblySymbol)asm1[1]).Assembly); Assert.Equal(2, (from a in asm4[1].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm4[1].BoundReferences() where object.ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal(1, (from a in asm4[1].BoundReferences() where object.ReferenceEquals(a, asm4[2]) select a).Count()); var retval6 = asm4[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Foo").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval6.Kind); Assert.Same(retval6, asm4[2].GlobalNamespace.GetMembers("Class1").Single()); Assert.Equal("MTTestLib1", asm4[2].Identity.Name); Assert.NotSame(asm4[2], asm2[2]); Assert.NotSame(asm4[2], asm3[2]); Assert.NotSame(((PEAssemblySymbol)asm4[2]).Assembly, ((PEAssemblySymbol)asm2[2]).Assembly); Assert.NotSame(((PEAssemblySymbol)asm4[2]).Assembly, ((PEAssemblySymbol)asm3[2]).Assembly); Assert.Equal(3, asm4[2].Identity.Version.Major); Assert.Equal(1, (from a in asm4[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm4[2].BoundReferences() where object.ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal("MTTestLib3", asm4[3].Identity.Name); Assert.NotSame(asm4[3], asm3[3]); Assert.Same(((PEAssemblySymbol)asm4[3]).Assembly, ((PEAssemblySymbol)asm3[3]).Assembly); Assert.Equal(3, (from a in asm4[3].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm4[3].BoundReferences() where object.ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal(1, (from a in asm4[3].BoundReferences() where object.ReferenceEquals(a, asm4[1]) select a).Count()); Assert.Equal(1, (from a in asm4[3].BoundReferences() where object.ReferenceEquals(a, asm4[2]) select a).Count()); var type2 = asm4[3].GlobalNamespace.GetTypeMembers("Class5"). Single(); var retval7 = type2.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval7.Kind); Assert.Same(retval7, asm4[2].GlobalNamespace.GetMembers("Class1").Single()); var retval8 = type2.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval8.Kind); Assert.Same(retval8, asm4[2].GlobalNamespace.GetMembers("Class2").Single()); var retval9 = type2.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval9.Kind); Assert.Same(retval9, asm4[1].GlobalNamespace.GetMembers("Class4").Single()); Assert.Equal("MTTestLib4", asm4[4].Identity.Name); Assert.Equal(4, (from a in asm4[4].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm4[4].BoundReferences() where object.ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal(1, (from a in asm4[4].BoundReferences() where object.ReferenceEquals(a, asm4[1]) select a).Count()); Assert.Equal(1, (from a in asm4[4].BoundReferences() where object.ReferenceEquals(a, asm4[2]) select a).Count()); Assert.Equal(1, (from a in asm4[4].BoundReferences() where object.ReferenceEquals(a, asm4[3]) select a).Count()); var type3 = asm4[4].GlobalNamespace.GetTypeMembers("Class6"). Single(); var retval10 = type3.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval10.Kind); Assert.Same(retval10, asm4[2].GlobalNamespace.GetMembers("Class1").Single()); var retval11 = type3.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval11.Kind); Assert.Same(retval11, asm4[2].GlobalNamespace.GetMembers("Class2").Single()); var retval12 = type3.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval12.Kind); Assert.Same(retval12, asm4[2].GlobalNamespace.GetMembers("Class3").Single()); var retval13 = type3.GetMembers("Foo4").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval13.Kind); Assert.Same(retval13, asm4[1].GlobalNamespace.GetMembers("Class4").Single()); var retval14 = type3.GetMembers("Foo5").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval14.Kind); Assert.Same(retval14, asm4[3].GlobalNamespace.GetMembers("Class5").Single()); var asm5 = MetadataTestHelpers.GetSymbolsForReferences(new[] { Net451.mscorlib, varV2MTTestLib3Ref }); Assert.Same(asm5[0], asm1[0]); Assert.True(asm5[1].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(asm3[3])); var asm6 = MetadataTestHelpers.GetSymbolsForReferences(new[] { Net451.mscorlib, varV1MTTestLib2Ref }); Assert.Same(asm6[0], asm1[0]); Assert.Same(asm6[1], asm1[1]); var asm7 = MetadataTestHelpers.GetSymbolsForReferences(new[] { Net451.mscorlib, varV1MTTestLib2Ref, varV2MTTestLib3Ref, varV3MTTestLib4Ref }); Assert.Same(asm7[0], asm1[0]); Assert.Same(asm7[1], asm1[1]); Assert.NotSame(asm7[2], asm3[3]); Assert.NotSame(asm7[2], asm4[3]); Assert.NotSame(asm7[3], asm4[4]); Assert.Equal("MTTestLib3", asm7[2].Identity.Name); Assert.Same(((PEAssemblySymbol)asm7[2]).Assembly, ((PEAssemblySymbol)asm3[3]).Assembly); Assert.Equal(2, (from a in asm7[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm7[2].BoundReferences() where object.ReferenceEquals(a, asm7[0]) select a).Count()); Assert.Equal(1, (from a in asm7[2].BoundReferences() where object.ReferenceEquals(a, asm7[1]) select a).Count()); var type4 = asm7[2].GlobalNamespace.GetTypeMembers("Class5"). Single(); var retval15 = type4.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal(SymbolKind.ErrorType, retval15.Kind); var retval16 = type4.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal(SymbolKind.ErrorType, retval16.Kind); var retval17 = type4.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval17.Kind); Assert.Same(retval17, asm7[1].GlobalNamespace.GetMembers("Class4").Single()); Assert.Equal("MTTestLib4", asm7[3].Identity.Name); Assert.Same(((PEAssemblySymbol)asm7[3]).Assembly, ((PEAssemblySymbol)asm4[4]).Assembly); Assert.Equal(3, (from a in asm7[3].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm7[3].BoundReferences() where object.ReferenceEquals(a, asm7[0]) select a).Count()); Assert.Equal(1, (from a in asm7[3].BoundReferences() where object.ReferenceEquals(a, asm7[1]) select a).Count()); Assert.Equal(1, (from a in asm7[3].BoundReferences() where object.ReferenceEquals(a, asm7[2]) select a).Count()); var type5 = asm7[3].GlobalNamespace.GetTypeMembers("Class6"). Single(); var retval18 = type5.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal(SymbolKind.ErrorType, retval18.Kind); var retval19 = type5.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal(SymbolKind.ErrorType, retval19.Kind); var retval20 = type5.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal(SymbolKind.ErrorType, retval20.Kind); var retval21 = type5.GetMembers("Foo4").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval21.Kind); Assert.Same(retval21, asm7[1].GlobalNamespace.GetMembers("Class4").Single()); var retval22 = type5.GetMembers("Foo5").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval22.Kind); Assert.Same(retval22, asm7[2].GlobalNamespace.GetMembers("Class5").Single()); // This test shows that simple reordering of references doesn't pick different set of assemblies var asm8 = MetadataTestHelpers.GetSymbolsForReferences(new[] { Net451.mscorlib, varV3MTTestLib4Ref, varV1MTTestLib2Ref, varV2MTTestLib3Ref }); Assert.Same(asm8[0], asm1[0]); Assert.Same(asm8[0], asm1[0]); Assert.Same(asm8[2], asm7[1]); Assert.True(asm8[3].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(asm4[3])); Assert.Same(asm8[3], asm7[2]); Assert.True(asm8[1].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(asm4[4])); Assert.Same(asm8[1], asm7[3]); var asm9 = MetadataTestHelpers.GetSymbolsForReferences(new[] { Net451.mscorlib, varV3MTTestLib4Ref }); Assert.Same(asm9[0], asm1[0]); Assert.True(asm9[1].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(asm4[4])); var asm10 = MetadataTestHelpers.GetSymbolsForReferences(new[] { Net451.mscorlib, varV1MTTestLib2Ref, TestReferences.SymbolsTests.V3.MTTestLib1.dll, varV2MTTestLib3Ref, varV3MTTestLib4Ref }); Assert.Same(asm10[0], asm1[0]); Assert.Same(asm10[1], asm4[1]); Assert.Same(asm10[2], asm4[2]); Assert.Same(asm10[3], asm4[3]); Assert.Same(asm10[4], asm4[4]); // Run the same tests again to make sure we didn't corrupt prior state by loading additional assemblies Assert.Equal("MTTestLib2", asm1[1].Identity.Name); Assert.Equal(1, (from a in asm1[1].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm1[1].BoundReferences() where ReferenceEquals(a, asm1[0]) select a).Count()); Assert.Equal(SymbolKind.ErrorType, asm1[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Foo").OfType<MethodSymbol>().Single().ReturnType.Kind); Assert.Same(asm2[0], asm1[0]); Assert.Equal("MTTestLib2", asm2[1].Identity.Name); Assert.NotSame(asm2[1], asm1[1]); Assert.Same(((PEAssemblySymbol)asm2[1]).Assembly, ((PEAssemblySymbol)asm1[1]).Assembly); Assert.Equal(2, (from a in asm2[1].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm2[1].BoundReferences() where ReferenceEquals(a, asm2[0]) select a).Count()); Assert.Equal(1, (from a in asm2[1].BoundReferences() where ReferenceEquals(a, asm2[2]) select a).Count()); retval1 = asm2[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Foo").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval1.Kind); Assert.Same(retval1, asm2[2].GlobalNamespace.GetMembers("Class1").Single()); Assert.Equal("MTTestLib1", asm2[2].Identity.Name); Assert.Equal(1, asm2[2].Identity.Version.Major); Assert.Equal(1, (from a in asm2[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm2[2].BoundReferences() where ReferenceEquals(a, asm2[0]) select a).Count()); Assert.Same(asm3[0], asm1[0]); Assert.Equal("MTTestLib2", asm3[1].Identity.Name); Assert.NotSame(asm3[1], asm1[1]); Assert.NotSame(asm3[1], asm2[1]); Assert.Same(((PEAssemblySymbol)asm3[1]).Assembly, ((PEAssemblySymbol)asm1[1]).Assembly); Assert.Equal(2, (from a in asm3[1].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm3[1].BoundReferences() where ReferenceEquals(a, asm3[0]) select a).Count()); Assert.Equal(1, (from a in asm3[1].BoundReferences() where ReferenceEquals(a, asm3[2]) select a).Count()); retval2 = asm3[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Foo").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval2.Kind); Assert.Same(retval2, asm3[2].GlobalNamespace.GetMembers("Class1").Single()); Assert.Equal("MTTestLib1", asm3[2].Identity.Name); Assert.NotSame(asm3[2], asm2[2]); Assert.NotSame(((PEAssemblySymbol)asm3[2]).Assembly, ((PEAssemblySymbol)asm2[2]).Assembly); Assert.Equal(2, asm3[2].Identity.Version.Major); Assert.Equal(1, (from a in asm3[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm3[2].BoundReferences() where ReferenceEquals(a, asm3[0]) select a).Count()); Assert.Equal("MTTestLib3", asm3[3].Identity.Name); Assert.Equal(3, (from a in asm3[3].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm3[3].BoundReferences() where ReferenceEquals(a, asm3[0]) select a).Count()); Assert.Equal(1, (from a in asm3[3].BoundReferences() where ReferenceEquals(a, asm3[1]) select a).Count()); Assert.Equal(1, (from a in asm3[3].BoundReferences() where ReferenceEquals(a, asm3[2]) select a).Count()); type1 = asm3[3].GlobalNamespace.GetTypeMembers("Class5"). Single(); retval3 = type1.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval3.Kind); Assert.Same(retval3, asm3[2].GlobalNamespace.GetMembers("Class1").Single()); retval4 = type1.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval4.Kind); Assert.Same(retval4, asm3[2].GlobalNamespace.GetMembers("Class2").Single()); retval5 = type1.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval5.Kind); Assert.Same(retval5, asm3[1].GlobalNamespace.GetMembers("Class4").Single()); Assert.Same(asm3[0], asm1[0]); Assert.Equal("MTTestLib2", asm4[1].Identity.Name); Assert.NotSame(asm4[1], asm1[1]); Assert.NotSame(asm4[1], asm2[1]); Assert.NotSame(asm4[1], asm3[1]); Assert.Same(((PEAssemblySymbol)asm4[1]).Assembly, ((PEAssemblySymbol)asm1[1]).Assembly); Assert.Equal(2, (from a in asm4[1].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm4[1].BoundReferences() where ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal(1, (from a in asm4[1].BoundReferences() where ReferenceEquals(a, asm4[2]) select a).Count()); retval6 = asm4[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Foo").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval6.Kind); Assert.Same(retval6, asm4[2].GlobalNamespace.GetMembers("Class1").Single()); Assert.Equal("MTTestLib1", asm4[2].Identity.Name); Assert.NotSame(asm4[2], asm2[2]); Assert.NotSame(asm4[2], asm3[2]); Assert.NotSame(((PEAssemblySymbol)asm4[2]).Assembly, ((PEAssemblySymbol)asm2[2]).Assembly); Assert.NotSame(((PEAssemblySymbol)asm4[2]).Assembly, ((PEAssemblySymbol)asm3[2]).Assembly); Assert.Equal(3, asm4[2].Identity.Version.Major); Assert.Equal(1, (from a in asm4[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm4[2].BoundReferences() where ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal("MTTestLib3", asm4[3].Identity.Name); Assert.NotSame(asm4[3], asm3[3]); Assert.Same(((PEAssemblySymbol)asm4[3]).Assembly, ((PEAssemblySymbol)asm3[3]).Assembly); Assert.Equal(3, (from a in asm4[3].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm4[3].BoundReferences() where ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal(1, (from a in asm4[3].BoundReferences() where ReferenceEquals(a, asm4[1]) select a).Count()); Assert.Equal(1, (from a in asm4[3].BoundReferences() where ReferenceEquals(a, asm4[2]) select a).Count()); type2 = asm4[3].GlobalNamespace.GetTypeMembers("Class5"). Single(); retval7 = type2.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval7.Kind); Assert.Same(retval7, asm4[2].GlobalNamespace.GetMembers("Class1").Single()); retval8 = type2.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval8.Kind); Assert.Same(retval8, asm4[2].GlobalNamespace.GetMembers("Class2").Single()); retval9 = type2.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval9.Kind); Assert.Same(retval9, asm4[1].GlobalNamespace.GetMembers("Class4").Single()); Assert.Equal("MTTestLib4", asm4[4].Identity.Name); Assert.Equal(4, (from a in asm4[4].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm4[4].BoundReferences() where ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal(1, (from a in asm4[4].BoundReferences() where ReferenceEquals(a, asm4[1]) select a).Count()); Assert.Equal(1, (from a in asm4[4].BoundReferences() where ReferenceEquals(a, asm4[2]) select a).Count()); Assert.Equal(1, (from a in asm4[4].BoundReferences() where ReferenceEquals(a, asm4[3]) select a).Count()); type3 = asm4[4].GlobalNamespace.GetTypeMembers("Class6"). Single(); retval10 = type3.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval10.Kind); Assert.Same(retval10, asm4[2].GlobalNamespace.GetMembers("Class1").Single()); retval11 = type3.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval11.Kind); Assert.Same(retval11, asm4[2].GlobalNamespace.GetMembers("Class2").Single()); retval12 = type3.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval12.Kind); Assert.Same(retval12, asm4[2].GlobalNamespace.GetMembers("Class3").Single()); retval13 = type3.GetMembers("Foo4").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval13.Kind); Assert.Same(retval13, asm4[1].GlobalNamespace.GetMembers("Class4").Single()); retval14 = type3.GetMembers("Foo5").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval14.Kind); Assert.Same(retval14, asm4[3].GlobalNamespace.GetMembers("Class5").Single()); Assert.Same(asm7[0], asm1[0]); Assert.Same(asm7[1], asm1[1]); Assert.NotSame(asm7[2], asm3[3]); Assert.NotSame(asm7[2], asm4[3]); Assert.NotSame(asm7[3], asm4[4]); Assert.Equal("MTTestLib3", asm7[2].Identity.Name); Assert.Same(((PEAssemblySymbol)asm7[2]).Assembly, ((PEAssemblySymbol)asm3[3]).Assembly); Assert.Equal(2, (from a in asm7[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm7[2].BoundReferences() where ReferenceEquals(a, asm7[0]) select a).Count()); Assert.Equal(1, (from a in asm7[2].BoundReferences() where ReferenceEquals(a, asm7[1]) select a).Count()); type4 = asm7[2].GlobalNamespace.GetTypeMembers("Class5"). Single(); retval15 = type4.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal(SymbolKind.ErrorType, retval15.Kind); retval16 = type4.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal(SymbolKind.ErrorType, retval16.Kind); retval17 = type4.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval17.Kind); Assert.Same(retval17, asm7[1].GlobalNamespace.GetMembers("Class4").Single()); Assert.Equal("MTTestLib4", asm7[3].Identity.Name); Assert.Same(((PEAssemblySymbol)asm7[3]).Assembly, ((PEAssemblySymbol)asm4[4]).Assembly); Assert.Equal(3, (from a in asm7[3].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm7[3].BoundReferences() where ReferenceEquals(a, asm7[0]) select a).Count()); Assert.Equal(1, (from a in asm7[3].BoundReferences() where ReferenceEquals(a, asm7[1]) select a).Count()); Assert.Equal(1, (from a in asm7[3].BoundReferences() where ReferenceEquals(a, asm7[2]) select a).Count()); type5 = asm7[3].GlobalNamespace.GetTypeMembers("Class6"). Single(); retval18 = type5.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal(SymbolKind.ErrorType, retval18.Kind); retval19 = type5.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal(SymbolKind.ErrorType, retval19.Kind); retval20 = type5.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal(SymbolKind.ErrorType, retval20.Kind); retval21 = type5.GetMembers("Foo4").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval21.Kind); Assert.Same(retval21, asm7[1].GlobalNamespace.GetMembers("Class4").Single()); retval22 = type5.GetMembers("Foo5").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval22.Kind); Assert.Same(retval22, asm7[2].GlobalNamespace.GetMembers("Class5").Single()); } [Fact] public void MultiTargeting2() { var varMTTestLib1_V1_Name = new AssemblyIdentity("MTTestLib1", new Version("1.0.0.0")); var varC_MTTestLib1_V1 = CreateCompilation(varMTTestLib1_V1_Name, new string[] { // AssemblyPaths.SymbolsTests.V1.MTTestModule1.netmodule @" public class Class1 { } " }, new[] { Net451.mscorlib }); var asm_MTTestLib1_V1 = varC_MTTestLib1_V1.SourceAssembly().BoundReferences(); var varMTTestLib2_Name = new AssemblyIdentity("MTTestLib2"); var varC_MTTestLib2 = CreateCompilation(varMTTestLib2_Name, new string[] { // AssemblyPaths.SymbolsTests.V1.MTTestModule2.netmodule @" public class Class4 { Class1 Foo() { return null; } public Class1 Bar; } " }, new MetadataReference[] { Net451.mscorlib, varC_MTTestLib1_V1.ToMetadataReference() }); var asm_MTTestLib2 = varC_MTTestLib2.SourceAssembly().BoundReferences(); Assert.Same(asm_MTTestLib2[0], asm_MTTestLib1_V1[0]); Assert.Same(asm_MTTestLib2[1], varC_MTTestLib1_V1.SourceAssembly()); var c2 = CreateCompilation(new AssemblyIdentity("c2"), null, new MetadataReference[] { Net451.mscorlib, varC_MTTestLib2.ToMetadataReference(), varC_MTTestLib1_V1.ToMetadataReference() }); var asm2 = c2.SourceAssembly().BoundReferences(); Assert.Same(asm2[0], asm_MTTestLib1_V1[0]); Assert.Same(asm2[1], varC_MTTestLib2.SourceAssembly()); Assert.Same(asm2[2], varC_MTTestLib1_V1.SourceAssembly()); Assert.Equal("MTTestLib2", asm2[1].Identity.Name); Assert.Equal(2, (from a in asm2[1].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm2[1].BoundReferences() where object.ReferenceEquals(a, asm2[0]) select a).Count()); Assert.Equal(1, (from a in asm2[1].BoundReferences() where object.ReferenceEquals(a, asm2[2]) select a).Count()); var retval1 = asm2[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Foo").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval1.Kind); Assert.Same(retval1, asm2[2].GlobalNamespace.GetMembers("Class1").Single()); Assert.Equal("MTTestLib1", asm2[2].Identity.Name); Assert.Equal(1, asm2[2].Identity.Version.Major); Assert.Equal(1, (from a in asm2[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm2[2].BoundReferences() where object.ReferenceEquals(a, asm2[0]) select a).Count()); var varMTTestLib1_V2_Name = new AssemblyIdentity("MTTestLib1", new Version("2.0.0.0")); var varC_MTTestLib1_V2 = CreateCompilation(varMTTestLib1_V2_Name, new string[] { // AssemblyPaths.SymbolsTests.V2.MTTestModule1.netmodule @" public class Class1 { } public class Class2 { } " }, new MetadataReference[] { Net451.mscorlib }); var asm_MTTestLib1_V2 = varC_MTTestLib1_V2.SourceAssembly().BoundReferences(); var varMTTestLib3_Name = new AssemblyIdentity("MTTestLib3"); var varC_MTTestLib3 = CreateCompilation(varMTTestLib3_Name, new string[] { // AssemblyPaths.SymbolsTests.V2.MTTestModule3.netmodule @" public class Class5 { Class1 Foo1() { return null; } Class2 Foo2() { return null; } Class4 Foo3() { return null; } Class1 Bar1; Class2 Bar2; Class4 Bar3; } " }, new MetadataReference[] { Net451.mscorlib, varC_MTTestLib2.ToMetadataReference(), varC_MTTestLib1_V2.ToMetadataReference() }); var asm_MTTestLib3 = varC_MTTestLib3.SourceAssembly().BoundReferences(); Assert.Same(asm_MTTestLib3[0], asm_MTTestLib1_V1[0]); Assert.NotSame(asm_MTTestLib3[1], varC_MTTestLib2.SourceAssembly()); Assert.NotSame(asm_MTTestLib3[2], varC_MTTestLib1_V1.SourceAssembly()); var c3 = CreateCompilation(new AssemblyIdentity("c3"), null, new MetadataReference[] { Net451.mscorlib, varC_MTTestLib2.ToMetadataReference(), varC_MTTestLib1_V2.ToMetadataReference(), varC_MTTestLib3.ToMetadataReference() }); var asm3 = c3.SourceAssembly().BoundReferences(); Assert.Same(asm3[0], asm_MTTestLib1_V1[0]); Assert.Same(asm3[1], asm_MTTestLib3[1]); Assert.Same(asm3[2], asm_MTTestLib3[2]); Assert.Same(asm3[3], varC_MTTestLib3.SourceAssembly()); Assert.Equal("MTTestLib2", asm3[1].Identity.Name); Assert.Same(((RetargetingAssemblySymbol)asm3[1]).UnderlyingAssembly, varC_MTTestLib2.SourceAssembly()); Assert.Equal(2, (from a in asm3[1].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm3[1].BoundReferences() where object.ReferenceEquals(a, asm3[0]) select a).Count()); Assert.Equal(1, (from a in asm3[1].BoundReferences() where object.ReferenceEquals(a, asm3[2]) select a).Count()); var retval2 = asm3[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Foo").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval2.Kind); Assert.Same(retval2, asm3[2].GlobalNamespace.GetMembers("Class1").Single()); Assert.Equal("MTTestLib1", asm3[2].Identity.Name); Assert.NotSame(asm3[2], asm2[2]); Assert.NotSame(asm3[2].DeclaringCompilation, asm2[2].DeclaringCompilation); Assert.Equal(2, asm3[2].Identity.Version.Major); Assert.Equal(1, (from a in asm3[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm3[2].BoundReferences() where object.ReferenceEquals(a, asm3[0]) select a).Count()); Assert.Equal("MTTestLib3", asm3[3].Identity.Name); Assert.Equal(3, (from a in asm3[3].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm3[3].BoundReferences() where object.ReferenceEquals(a, asm3[0]) select a).Count()); Assert.Equal(1, (from a in asm3[3].BoundReferences() where object.ReferenceEquals(a, asm3[1]) select a).Count()); Assert.Equal(1, (from a in asm3[3].BoundReferences() where object.ReferenceEquals(a, asm3[2]) select a).Count()); var type1 = asm3[3].GlobalNamespace.GetTypeMembers("Class5"). Single(); var retval3 = type1.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval3.Kind); Assert.Same(retval3, asm3[2].GlobalNamespace.GetMembers("Class1").Single()); var retval4 = type1.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval4.Kind); Assert.Same(retval4, asm3[2].GlobalNamespace.GetMembers("Class2").Single()); var retval5 = type1.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval5.Kind); Assert.Same(retval5, asm3[1].GlobalNamespace.GetMembers("Class4").Single()); var varMTTestLib1_V3_Name = new AssemblyIdentity("MTTestLib1", new Version("3.0.0.0")); var varC_MTTestLib1_V3 = CreateCompilation(varMTTestLib1_V3_Name, new string[] { // AssemblyPaths.SymbolsTests.V3.MTTestModule1.netmodule @" public class Class1 { } public class Class2 { } public class Class3 { } " }, new MetadataReference[] { Net451.mscorlib }); var asm_MTTestLib1_V3 = varC_MTTestLib1_V3.SourceAssembly().BoundReferences(); var varMTTestLib4_Name = new AssemblyIdentity("MTTestLib4"); var varC_MTTestLib4 = CreateCompilation(varMTTestLib4_Name, new string[] { // AssemblyPaths.SymbolsTests.V3.MTTestModule4.netmodule @" public class Class6 { Class1 Foo1() { return null; } Class2 Foo2() { return null; } Class3 Foo3() { return null; } Class4 Foo4() { return null; } Class5 Foo5() { return null; } Class1 Bar1; Class2 Bar2; Class3 Bar3; Class4 Bar4; Class5 Bar5; } " }, new MetadataReference[] { Net451.mscorlib, varC_MTTestLib2.ToMetadataReference(), varC_MTTestLib1_V3.ToMetadataReference(), varC_MTTestLib3.ToMetadataReference() }); var asm_MTTestLib4 = varC_MTTestLib4.SourceAssembly().BoundReferences(); Assert.Same(asm_MTTestLib4[0], asm_MTTestLib1_V1[0]); Assert.NotSame(asm_MTTestLib4[1], varC_MTTestLib2.SourceAssembly()); Assert.Same(asm_MTTestLib4[2], varC_MTTestLib1_V3.SourceAssembly()); Assert.NotSame(asm_MTTestLib4[3], varC_MTTestLib3.SourceAssembly()); var c4 = CreateCompilation(new AssemblyIdentity("c4"), null, new MetadataReference[] { Net451.mscorlib, varC_MTTestLib2.ToMetadataReference(), varC_MTTestLib1_V3.ToMetadataReference(), varC_MTTestLib3.ToMetadataReference(), varC_MTTestLib4.ToMetadataReference() }); var asm4 = c4.SourceAssembly().BoundReferences(); Assert.Same(asm4[0], asm_MTTestLib1_V1[0]); Assert.Same(asm4[1], asm_MTTestLib4[1]); Assert.Same(asm4[2], asm_MTTestLib4[2]); Assert.Same(asm4[3], asm_MTTestLib4[3]); Assert.Same(asm4[4], varC_MTTestLib4.SourceAssembly()); Assert.Equal("MTTestLib2", asm4[1].Identity.Name); Assert.NotSame(asm4[1], varC_MTTestLib2.SourceAssembly()); Assert.NotSame(asm4[1], asm2[1]); Assert.NotSame(asm4[1], asm3[1]); Assert.Same(((RetargetingAssemblySymbol)asm4[1]).UnderlyingAssembly, varC_MTTestLib2.SourceAssembly()); Assert.Equal(2, (from a in asm4[1].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm4[1].BoundReferences() where object.ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal(1, (from a in asm4[1].BoundReferences() where object.ReferenceEquals(a, asm4[2]) select a).Count()); var retval6 = asm4[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Foo").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval6.Kind); Assert.Same(retval6, asm4[2].GlobalNamespace.GetMembers("Class1").Single()); Assert.Equal("MTTestLib1", asm4[2].Identity.Name); Assert.NotSame(asm4[2], asm2[2]); Assert.NotSame(asm4[2], asm3[2]); Assert.NotSame(asm4[2].DeclaringCompilation, asm2[2].DeclaringCompilation); Assert.NotSame(asm4[2].DeclaringCompilation, asm3[2].DeclaringCompilation); Assert.Equal(3, asm4[2].Identity.Version.Major); Assert.Equal(1, (from a in asm4[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm4[2].BoundReferences() where object.ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal("MTTestLib3", asm4[3].Identity.Name); Assert.NotSame(asm4[3], asm3[3]); Assert.Same(((RetargetingAssemblySymbol)asm4[3]).UnderlyingAssembly, asm3[3]); Assert.Equal(3, (from a in asm4[3].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm4[3].BoundReferences() where object.ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal(1, (from a in asm4[3].BoundReferences() where object.ReferenceEquals(a, asm4[1]) select a).Count()); Assert.Equal(1, (from a in asm4[3].BoundReferences() where object.ReferenceEquals(a, asm4[2]) select a).Count()); var type2 = asm4[3].GlobalNamespace.GetTypeMembers("Class5"). Single(); var retval7 = type2.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval7.Kind); Assert.Same(retval7, asm4[2].GlobalNamespace.GetMembers("Class1").Single()); var retval8 = type2.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval8.Kind); Assert.Same(retval8, asm4[2].GlobalNamespace.GetMembers("Class2").Single()); var retval9 = type2.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval9.Kind); Assert.Same(retval9, asm4[1].GlobalNamespace.GetMembers("Class4").Single()); Assert.Equal("MTTestLib4", asm4[4].Identity.Name); Assert.Equal(4, (from a in asm4[4].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm4[4].BoundReferences() where object.ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal(1, (from a in asm4[4].BoundReferences() where object.ReferenceEquals(a, asm4[1]) select a).Count()); Assert.Equal(1, (from a in asm4[4].BoundReferences() where object.ReferenceEquals(a, asm4[2]) select a).Count()); Assert.Equal(1, (from a in asm4[4].BoundReferences() where object.ReferenceEquals(a, asm4[3]) select a).Count()); var type3 = asm4[4].GlobalNamespace.GetTypeMembers("Class6"). Single(); var retval10 = type3.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval10.Kind); Assert.Same(retval10, asm4[2].GlobalNamespace.GetMembers("Class1").Single()); var retval11 = type3.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval11.Kind); Assert.Same(retval11, asm4[2].GlobalNamespace.GetMembers("Class2").Single()); var retval12 = type3.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval12.Kind); Assert.Same(retval12, asm4[2].GlobalNamespace.GetMembers("Class3").Single()); var retval13 = type3.GetMembers("Foo4").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval13.Kind); Assert.Same(retval13, asm4[1].GlobalNamespace.GetMembers("Class4").Single()); var retval14 = type3.GetMembers("Foo5").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval14.Kind); Assert.Same(retval14, asm4[3].GlobalNamespace.GetMembers("Class5").Single()); var c5 = CreateCompilation(new AssemblyIdentity("c5"), null, new MetadataReference[] { Net451.mscorlib, varC_MTTestLib3.ToMetadataReference() }); var asm5 = c5.SourceAssembly().BoundReferences(); Assert.Same(asm5[0], asm2[0]); Assert.True(asm5[1].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(asm3[3])); var c6 = CreateCompilation(new AssemblyIdentity("c6"), null, new MetadataReference[] { Net451.mscorlib, varC_MTTestLib2.ToMetadataReference() }); var asm6 = c6.SourceAssembly().BoundReferences(); Assert.Same(asm6[0], asm2[0]); Assert.True(asm6[1].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(varC_MTTestLib2.SourceAssembly())); var c7 = CreateCompilation(new AssemblyIdentity("c7"), null, new MetadataReference[] { Net451.mscorlib, varC_MTTestLib2.ToMetadataReference(), varC_MTTestLib3.ToMetadataReference(), varC_MTTestLib4.ToMetadataReference() }); var asm7 = c7.SourceAssembly().BoundReferences(); Assert.Same(asm7[0], asm2[0]); Assert.True(asm7[1].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(varC_MTTestLib2.SourceAssembly())); Assert.NotSame(asm7[2], asm3[3]); Assert.NotSame(asm7[2], asm4[3]); Assert.NotSame(asm7[3], asm4[4]); Assert.Equal("MTTestLib3", asm7[2].Identity.Name); Assert.Same(((RetargetingAssemblySymbol)asm7[2]).UnderlyingAssembly, asm3[3]); Assert.Equal(2, (from a in asm7[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm7[2].BoundReferences() where object.ReferenceEquals(a, asm7[0]) select a).Count()); Assert.Equal(1, (from a in asm7[2].BoundReferences() where object.ReferenceEquals(a, asm7[1]) select a).Count()); var type4 = asm7[2].GlobalNamespace.GetTypeMembers("Class5"). Single(); var retval15 = type4.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal("MTTestLib1", retval15.ContainingAssembly.Name); Assert.Equal(0, (from a in asm7 where a != null && a.Name == "MTTestLib1" select a).Count()); var retval16 = type4.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal("MTTestLib1", retval16.ContainingAssembly.Name); var retval17 = type4.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval17.Kind); Assert.Same(retval17, asm7[1].GlobalNamespace.GetMembers("Class4").Single()); Assert.Equal("MTTestLib4", asm7[3].Identity.Name); Assert.Same(((RetargetingAssemblySymbol)asm7[3]).UnderlyingAssembly, asm4[4]); Assert.Equal(3, (from a in asm7[3].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm7[3].BoundReferences() where object.ReferenceEquals(a, asm7[0]) select a).Count()); Assert.Equal(1, (from a in asm7[3].BoundReferences() where object.ReferenceEquals(a, asm7[1]) select a).Count()); Assert.Equal(1, (from a in asm7[3].BoundReferences() where object.ReferenceEquals(a, asm7[2]) select a).Count()); var type5 = asm7[3].GlobalNamespace.GetTypeMembers("Class6"). Single(); var retval18 = type5.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal("MTTestLib1", retval18.ContainingAssembly.Name); var retval19 = type5.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal("MTTestLib1", retval19.ContainingAssembly.Name); var retval20 = type5.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal("MTTestLib1", retval20.ContainingAssembly.Name); var retval21 = type5.GetMembers("Foo4").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval21.Kind); Assert.Same(retval21, asm7[1].GlobalNamespace.GetMembers("Class4").Single()); var retval22 = type5.GetMembers("Foo5").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval22.Kind); Assert.Same(retval22, asm7[2].GlobalNamespace.GetMembers("Class5").Single()); // This test shows that simple reordering of references doesn't pick different set of assemblies var c8 = CreateCompilation(new AssemblyIdentity("c8"), null, new MetadataReference[] { Net451.mscorlib, varC_MTTestLib4.ToMetadataReference(), varC_MTTestLib2.ToMetadataReference(), varC_MTTestLib3.ToMetadataReference() }); var asm8 = c8.SourceAssembly().BoundReferences(); Assert.Same(asm8[0], asm2[0]); Assert.True(asm8[2].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(asm4[1])); Assert.Same(asm8[2], asm7[1]); Assert.True(asm8[3].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(asm4[3])); Assert.Same(asm8[3], asm7[2]); Assert.True(asm8[1].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(asm4[4])); Assert.Same(asm8[1], asm7[3]); var c9 = CreateCompilation(new AssemblyIdentity("c9"), null, new MetadataReference[] { Net451.mscorlib, varC_MTTestLib4.ToMetadataReference() }); var asm9 = c9.SourceAssembly().BoundReferences(); Assert.Same(asm9[0], asm2[0]); Assert.True(asm9[1].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(asm4[4])); var c10 = CreateCompilation(new AssemblyIdentity("c10"), null, new MetadataReference[] { Net451.mscorlib, varC_MTTestLib2.ToMetadataReference(), varC_MTTestLib1_V3.ToMetadataReference(), varC_MTTestLib3.ToMetadataReference(), varC_MTTestLib4.ToMetadataReference() }); var asm10 = c10.SourceAssembly().BoundReferences(); Assert.Same(asm10[0], asm2[0]); Assert.Same(asm10[1], asm4[1]); Assert.Same(asm10[2], asm4[2]); Assert.Same(asm10[3], asm4[3]); Assert.Same(asm10[4], asm4[4]); // Run the same tests again to make sure we didn't corrupt prior state by loading additional assemblies Assert.Same(asm2[0], asm_MTTestLib1_V1[0]); Assert.Equal("MTTestLib2", asm2[1].Identity.Name); Assert.Equal(2, (from a in asm2[1].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm2[1].BoundReferences() where object.ReferenceEquals(a, asm2[0]) select a).Count()); Assert.Equal(1, (from a in asm2[1].BoundReferences() where object.ReferenceEquals(a, asm2[2]) select a).Count()); retval1 = asm2[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Foo").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval1.Kind); Assert.Same(retval1, asm2[2].GlobalNamespace.GetMembers("Class1").Single()); Assert.Equal("MTTestLib1", asm2[2].Identity.Name); Assert.Equal(1, asm2[2].Identity.Version.Major); Assert.Equal(1, (from a in asm2[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm2[2].BoundReferences() where object.ReferenceEquals(a, asm2[0]) select a).Count()); Assert.Same(asm_MTTestLib3[0], asm_MTTestLib1_V1[0]); Assert.NotSame(asm_MTTestLib3[1], varC_MTTestLib2.SourceAssembly()); Assert.NotSame(asm_MTTestLib3[2], varC_MTTestLib1_V1.SourceAssembly()); Assert.Same(asm3[0], asm_MTTestLib1_V1[0]); Assert.Same(asm3[1], asm_MTTestLib3[1]); Assert.Same(asm3[2], asm_MTTestLib3[2]); Assert.Same(asm3[3], varC_MTTestLib3.SourceAssembly()); Assert.Equal("MTTestLib2", asm3[1].Identity.Name); Assert.Same(((RetargetingAssemblySymbol)asm3[1]).UnderlyingAssembly, varC_MTTestLib2.SourceAssembly()); Assert.Equal(2, (from a in asm3[1].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm3[1].BoundReferences() where object.ReferenceEquals(a, asm3[0]) select a).Count()); Assert.Equal(1, (from a in asm3[1].BoundReferences() where object.ReferenceEquals(a, asm3[2]) select a).Count()); retval2 = asm3[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Foo").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval2.Kind); Assert.Same(retval2, asm3[2].GlobalNamespace.GetMembers("Class1").Single()); Assert.Equal("MTTestLib1", asm3[2].Identity.Name); Assert.NotSame(asm3[2], asm2[2]); Assert.NotSame(asm3[2].DeclaringCompilation, asm2[2].DeclaringCompilation); Assert.Equal(2, asm3[2].Identity.Version.Major); Assert.Equal(1, (from a in asm3[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm3[2].BoundReferences() where object.ReferenceEquals(a, asm3[0]) select a).Count()); Assert.Equal("MTTestLib3", asm3[3].Identity.Name); Assert.Equal(3, (from a in asm3[3].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm3[3].BoundReferences() where object.ReferenceEquals(a, asm3[0]) select a).Count()); Assert.Equal(1, (from a in asm3[3].BoundReferences() where object.ReferenceEquals(a, asm3[1]) select a).Count()); Assert.Equal(1, (from a in asm3[3].BoundReferences() where object.ReferenceEquals(a, asm3[2]) select a).Count()); type1 = asm3[3].GlobalNamespace.GetTypeMembers("Class5"). Single(); retval3 = type1.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval3.Kind); Assert.Same(retval3, asm3[2].GlobalNamespace.GetMembers("Class1").Single()); retval4 = type1.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval4.Kind); Assert.Same(retval4, asm3[2].GlobalNamespace.GetMembers("Class2").Single()); retval5 = type1.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval5.Kind); Assert.Same(retval5, asm3[1].GlobalNamespace.GetMembers("Class4").Single()); Assert.Same(asm4[0], asm_MTTestLib1_V1[0]); Assert.Same(asm4[1], asm_MTTestLib4[1]); Assert.Same(asm4[2], asm_MTTestLib4[2]); Assert.Same(asm4[3], asm_MTTestLib4[3]); Assert.Same(asm4[4], varC_MTTestLib4.SourceAssembly()); Assert.Equal("MTTestLib2", asm4[1].Identity.Name); Assert.NotSame(asm4[1], varC_MTTestLib2.SourceAssembly()); Assert.NotSame(asm4[1], asm2[1]); Assert.NotSame(asm4[1], asm3[1]); Assert.Same(((RetargetingAssemblySymbol)asm4[1]).UnderlyingAssembly, varC_MTTestLib2.SourceAssembly()); Assert.Equal(2, (from a in asm4[1].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm4[1].BoundReferences() where object.ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal(1, (from a in asm4[1].BoundReferences() where object.ReferenceEquals(a, asm4[2]) select a).Count()); retval6 = asm4[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Foo").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval6.Kind); Assert.Same(retval6, asm4[2].GlobalNamespace.GetMembers("Class1").Single()); Assert.Equal("MTTestLib1", asm4[2].Identity.Name); Assert.NotSame(asm4[2], asm2[2]); Assert.NotSame(asm4[2], asm3[2]); Assert.NotSame(asm4[2].DeclaringCompilation, asm2[2].DeclaringCompilation); Assert.NotSame(asm4[2].DeclaringCompilation, asm3[2].DeclaringCompilation); Assert.Equal(3, asm4[2].Identity.Version.Major); Assert.Equal(1, (from a in asm4[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm4[2].BoundReferences() where object.ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal("MTTestLib3", asm4[3].Identity.Name); Assert.NotSame(asm4[3], asm3[3]); Assert.Same(((RetargetingAssemblySymbol)asm4[3]).UnderlyingAssembly, asm3[3]); Assert.Equal(3, (from a in asm4[3].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm4[3].BoundReferences() where object.ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal(1, (from a in asm4[3].BoundReferences() where object.ReferenceEquals(a, asm4[1]) select a).Count()); Assert.Equal(1, (from a in asm4[3].BoundReferences() where object.ReferenceEquals(a, asm4[2]) select a).Count()); type2 = asm4[3].GlobalNamespace.GetTypeMembers("Class5"). Single(); retval7 = type2.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval7.Kind); Assert.Same(retval7, asm4[2].GlobalNamespace.GetMembers("Class1").Single()); retval8 = type2.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval8.Kind); Assert.Same(retval8, asm4[2].GlobalNamespace.GetMembers("Class2").Single()); retval9 = type2.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval9.Kind); Assert.Same(retval9, asm4[1].GlobalNamespace.GetMembers("Class4").Single()); Assert.Equal("MTTestLib4", asm4[4].Identity.Name); Assert.Equal(4, (from a in asm4[4].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm4[4].BoundReferences() where object.ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal(1, (from a in asm4[4].BoundReferences() where object.ReferenceEquals(a, asm4[1]) select a).Count()); Assert.Equal(1, (from a in asm4[4].BoundReferences() where object.ReferenceEquals(a, asm4[2]) select a).Count()); Assert.Equal(1, (from a in asm4[4].BoundReferences() where object.ReferenceEquals(a, asm4[3]) select a).Count()); type3 = asm4[4].GlobalNamespace.GetTypeMembers("Class6"). Single(); retval10 = type3.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval10.Kind); Assert.Same(retval10, asm4[2].GlobalNamespace.GetMembers("Class1").Single()); retval11 = type3.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval11.Kind); Assert.Same(retval11, asm4[2].GlobalNamespace.GetMembers("Class2").Single()); retval12 = type3.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval12.Kind); Assert.Same(retval12, asm4[2].GlobalNamespace.GetMembers("Class3").Single()); retval13 = type3.GetMembers("Foo4").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval13.Kind); Assert.Same(retval13, asm4[1].GlobalNamespace.GetMembers("Class4").Single()); retval14 = type3.GetMembers("Foo5").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval14.Kind); Assert.Same(retval14, asm4[3].GlobalNamespace.GetMembers("Class5").Single()); Assert.Same(asm5[0], asm2[0]); Assert.True(asm5[1].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(asm3[3])); Assert.Same(asm6[0], asm2[0]); Assert.True(asm6[1].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(varC_MTTestLib2.SourceAssembly())); Assert.Same(asm7[0], asm2[0]); Assert.True(asm7[1].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(varC_MTTestLib2.SourceAssembly())); Assert.NotSame(asm7[2], asm3[3]); Assert.NotSame(asm7[2], asm4[3]); Assert.NotSame(asm7[3], asm4[4]); Assert.Equal("MTTestLib3", asm7[2].Identity.Name); Assert.Same(((RetargetingAssemblySymbol)asm7[2]).UnderlyingAssembly, asm3[3]); Assert.Equal(2, (from a in asm7[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm7[2].BoundReferences() where object.ReferenceEquals(a, asm7[0]) select a).Count()); Assert.Equal(1, (from a in asm7[2].BoundReferences() where object.ReferenceEquals(a, asm7[1]) select a).Count()); type4 = asm7[2].GlobalNamespace.GetTypeMembers("Class5"). Single(); retval15 = type4.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal("MTTestLib1", retval15.ContainingAssembly.Name); Assert.Equal(0, (from a in asm7 where a != null && a.Name == "MTTestLib1" select a).Count()); retval16 = type4.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal("MTTestLib1", retval16.ContainingAssembly.Name); retval17 = type4.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval17.Kind); Assert.Same(retval17, asm7[1].GlobalNamespace.GetMembers("Class4").Single()); Assert.Equal("MTTestLib4", asm7[3].Identity.Name); Assert.Same(((RetargetingAssemblySymbol)asm7[3]).UnderlyingAssembly, asm4[4]); Assert.Equal(3, (from a in asm7[3].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm7[3].BoundReferences() where object.ReferenceEquals(a, asm7[0]) select a).Count()); Assert.Equal(1, (from a in asm7[3].BoundReferences() where object.ReferenceEquals(a, asm7[1]) select a).Count()); Assert.Equal(1, (from a in asm7[3].BoundReferences() where object.ReferenceEquals(a, asm7[2]) select a).Count()); type5 = asm7[3].GlobalNamespace.GetTypeMembers("Class6"). Single(); retval18 = type5.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal("MTTestLib1", retval18.ContainingAssembly.Name); retval19 = type5.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal("MTTestLib1", retval19.ContainingAssembly.Name); retval20 = type5.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal("MTTestLib1", retval20.ContainingAssembly.Name); retval21 = type5.GetMembers("Foo4").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval21.Kind); Assert.Same(retval21, asm7[1].GlobalNamespace.GetMembers("Class4").Single()); retval22 = type5.GetMembers("Foo5").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval22.Kind); Assert.Same(retval22, asm7[2].GlobalNamespace.GetMembers("Class5").Single()); } [Fact] public void MultiTargeting3() { var varMTTestLib2_Name = new AssemblyIdentity("MTTestLib2"); var varC_MTTestLib2 = CreateCompilation(varMTTestLib2_Name, (string[])null, new[] { Net451.mscorlib, TestReferences.SymbolsTests.V1.MTTestLib1.dll, TestReferences.SymbolsTests.V1.MTTestModule2.netmodule }); var asm_MTTestLib2 = varC_MTTestLib2.SourceAssembly().BoundReferences(); var c2 = CreateCompilation(new AssemblyIdentity("c2"), null, new MetadataReference[] { Net451.mscorlib, TestReferences.SymbolsTests.V1.MTTestLib1.dll, new CSharpCompilationReference(varC_MTTestLib2) }); var asm2Prime = c2.SourceAssembly().BoundReferences(); var asm2 = new AssemblySymbol[] { asm2Prime[0], asm2Prime[2], asm2Prime[1] }; Assert.Same(asm2[0], asm_MTTestLib2[0]); Assert.Same(asm2[1], varC_MTTestLib2.SourceAssembly()); Assert.Same(asm2[2], asm_MTTestLib2[1]); Assert.Equal("MTTestLib2", asm2[1].Identity.Name); Assert.Equal(4, (from a in asm2[1].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(2, (from a in asm2[1].BoundReferences() where object.ReferenceEquals(a, asm2[0]) select a).Count()); Assert.Equal(2, (from a in asm2[1].BoundReferences() where object.ReferenceEquals(a, asm2[2]) select a).Count()); var retval1 = asm2[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Foo").OfType<MethodSymbol>().Single().ReturnType; Assert.Same(retval1, asm2[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Bar").OfType<FieldSymbol>().Single().Type); Assert.NotEqual(SymbolKind.ErrorType, retval1.Kind); Assert.Same(retval1, asm2[2].GlobalNamespace.GetMembers("Class1").Single()); Assert.Equal("MTTestLib1", asm2[2].Identity.Name); Assert.Equal(1, asm2[2].Identity.Version.Major); Assert.Equal(1, (from a in asm2[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm2[2].BoundReferences() where object.ReferenceEquals(a, asm2[0]) select a).Count()); var varMTTestLib3_Name = new AssemblyIdentity("MTTestLib3"); var varC_MTTestLib3 = CreateCompilation(varMTTestLib3_Name, null, new MetadataReference[] { Net451.mscorlib, TestReferences.SymbolsTests.V2.MTTestLib1.dll, new CSharpCompilationReference(varC_MTTestLib2), TestReferences.SymbolsTests.V2.MTTestModule3.netmodule }); var asm_MTTestLib3Prime = varC_MTTestLib3.SourceAssembly().BoundReferences(); var asm_MTTestLib3 = new AssemblySymbol[] { asm_MTTestLib3Prime[0], asm_MTTestLib3Prime[2], asm_MTTestLib3Prime[1] }; Assert.Same(asm_MTTestLib3[0], asm_MTTestLib2[0]); Assert.NotSame(asm_MTTestLib3[1], varC_MTTestLib2.SourceAssembly()); Assert.NotSame(asm_MTTestLib3[2], asm_MTTestLib2[1]); var c3 = CreateCompilation(new AssemblyIdentity("c3"), null, new MetadataReference[] { Net451.mscorlib, TestReferences.SymbolsTests.V2.MTTestLib1.dll, new CSharpCompilationReference(varC_MTTestLib2), new CSharpCompilationReference(varC_MTTestLib3) }); var asm3Prime = c3.SourceAssembly().BoundReferences(); var asm3 = new AssemblySymbol[] { asm3Prime[0], asm3Prime[2], asm3Prime[1], asm3Prime[3] }; Assert.Same(asm3[0], asm_MTTestLib2[0]); Assert.Same(asm3[1], asm_MTTestLib3[1]); Assert.Same(asm3[2], asm_MTTestLib3[2]); Assert.Same(asm3[3], varC_MTTestLib3.SourceAssembly()); Assert.Equal("MTTestLib2", asm3[1].Identity.Name); Assert.Same(((RetargetingAssemblySymbol)asm3[1]).UnderlyingAssembly, varC_MTTestLib2.SourceAssembly()); Assert.Equal(4, (from a in asm3[1].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(2, (from a in asm3[1].BoundReferences() where object.ReferenceEquals(a, asm3[0]) select a).Count()); Assert.Equal(2, (from a in asm3[1].BoundReferences() where object.ReferenceEquals(a, asm3[2]) select a).Count()); var retval2 = asm3[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Foo").OfType<MethodSymbol>().Single().ReturnType; Assert.Same(retval2, asm3[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Bar").OfType<FieldSymbol>().Single().Type); Assert.NotEqual(SymbolKind.ErrorType, retval2.Kind); Assert.Same(retval2, asm3[2].GlobalNamespace.GetMembers("Class1").Single()); Assert.Equal("MTTestLib1", asm3[2].Identity.Name); Assert.NotSame(asm3[2], asm2[2]); Assert.NotSame(asm3[2], asm2[2]); Assert.NotSame(((PEAssemblySymbol)asm3[2]).Assembly, ((PEAssemblySymbol)asm2[2]).Assembly); Assert.Equal(2, asm3[2].Identity.Version.Major); Assert.Equal(1, (from a in asm3[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm3[2].BoundReferences() where object.ReferenceEquals(a, asm3[0]) select a).Count()); Assert.Equal("MTTestLib3", asm3[3].Identity.Name); Assert.Equal(6, (from a in asm3[3].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(2, (from a in asm3[3].BoundReferences() where object.ReferenceEquals(a, asm3[0]) select a).Count()); Assert.Equal(2, (from a in asm3[3].BoundReferences() where object.ReferenceEquals(a, asm3[1]) select a).Count()); Assert.Equal(2, (from a in asm3[3].BoundReferences() where object.ReferenceEquals(a, asm3[2]) select a).Count()); var type1 = asm3[3].GlobalNamespace.GetTypeMembers("Class5").Single(); var retval3 = type1.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval3.Kind); Assert.Same(retval3, asm3[2].GlobalNamespace.GetMembers("Class1").Single()); var retval4 = type1.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval4.Kind); Assert.Same(retval4, asm3[2].GlobalNamespace.GetMembers("Class2").Single()); var retval5 = type1.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval5.Kind); Assert.Same(retval5, asm3[1].GlobalNamespace.GetMembers("Class4").Single()); var varMTTestLib4_Name = new AssemblyIdentity("MTTestLib4"); var varC_MTTestLib4 = CreateCompilation(varMTTestLib4_Name, null, new MetadataReference[] { Net451.mscorlib, TestReferences.SymbolsTests.V3.MTTestLib1.dll, new CSharpCompilationReference(varC_MTTestLib2), new CSharpCompilationReference(varC_MTTestLib3), TestReferences.SymbolsTests.V3.MTTestModule4.netmodule }); var asm_MTTestLib4Prime = varC_MTTestLib4.SourceAssembly().BoundReferences(); var asm_MTTestLib4 = new AssemblySymbol[] { asm_MTTestLib4Prime[0], asm_MTTestLib4Prime[2], asm_MTTestLib4Prime[1], asm_MTTestLib4Prime[3] }; Assert.Same(asm_MTTestLib4[0], asm_MTTestLib2[0]); Assert.NotSame(asm_MTTestLib4[1], varC_MTTestLib2.SourceAssembly()); Assert.NotSame(asm_MTTestLib4[2], asm3[2]); Assert.NotSame(asm_MTTestLib4[2], asm2[2]); Assert.NotSame(asm_MTTestLib4[3], varC_MTTestLib3.SourceAssembly()); var c4 = CreateCompilation(new AssemblyIdentity("c4"), null, new MetadataReference[] { Net451.mscorlib, TestReferences.SymbolsTests.V3.MTTestLib1.dll, new CSharpCompilationReference(varC_MTTestLib2), new CSharpCompilationReference(varC_MTTestLib3), new CSharpCompilationReference(varC_MTTestLib4) }); var asm4Prime = c4.SourceAssembly().BoundReferences(); var asm4 = new AssemblySymbol[] { asm4Prime[0], asm4Prime[2], asm4Prime[1], asm4Prime[3], asm4Prime[4] }; Assert.Same(asm4[0], asm_MTTestLib2[0]); Assert.Same(asm4[1], asm_MTTestLib4[1]); Assert.Same(asm4[2], asm_MTTestLib4[2]); Assert.Same(asm4[3], asm_MTTestLib4[3]); Assert.Same(asm4[4], varC_MTTestLib4.SourceAssembly()); Assert.Equal("MTTestLib2", asm4[1].Identity.Name); Assert.NotSame(asm4[1], varC_MTTestLib2.SourceAssembly()); Assert.NotSame(asm4[1], asm2[1]); Assert.NotSame(asm4[1], asm3[1]); Assert.Same(((RetargetingAssemblySymbol)asm4[1]).UnderlyingAssembly, varC_MTTestLib2.SourceAssembly()); Assert.Equal(4, (from a in asm4[1].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(2, (from a in asm4[1].BoundReferences() where object.ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal(2, (from a in asm4[1].BoundReferences() where object.ReferenceEquals(a, asm4[2]) select a).Count()); var retval6 = asm4[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Foo").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval6.Kind); Assert.Same(retval6, asm4[2].GlobalNamespace.GetMembers("Class1").Single()); Assert.Equal("MTTestLib1", asm4[2].Identity.Name); Assert.NotSame(asm4[2], asm2[2]); Assert.NotSame(asm4[2], asm3[2]); Assert.NotSame(((PEAssemblySymbol)asm4[2]).Assembly, ((PEAssemblySymbol)asm2[2]).Assembly); Assert.NotSame(((PEAssemblySymbol)asm4[2]).Assembly, ((PEAssemblySymbol)asm3[2]).Assembly); Assert.Equal(3, asm4[2].Identity.Version.Major); Assert.Equal(1, (from a in asm4[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm4[2].BoundReferences() where object.ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal("MTTestLib3", asm4[3].Identity.Name); Assert.NotSame(asm4[3], asm3[3]); Assert.Same(((RetargetingAssemblySymbol)asm4[3]).UnderlyingAssembly, asm3[3]); Assert.Equal(6, (from a in asm4[3].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(2, (from a in asm4[3].BoundReferences() where object.ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal(2, (from a in asm4[3].BoundReferences() where object.ReferenceEquals(a, asm4[1]) select a).Count()); Assert.Equal(2, (from a in asm4[3].BoundReferences() where object.ReferenceEquals(a, asm4[2]) select a).Count()); var type2 = asm4[3].GlobalNamespace.GetTypeMembers("Class5"). Single(); var retval7 = type2.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval7.Kind); Assert.Same(retval7, asm4[2].GlobalNamespace.GetMembers("Class1").Single()); var retval8 = type2.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval8.Kind); Assert.Same(retval8, asm4[2].GlobalNamespace.GetMembers("Class2").Single()); var retval9 = type2.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval9.Kind); Assert.Same(retval9, asm4[1].GlobalNamespace.GetMembers("Class4").Single()); Assert.Equal("MTTestLib4", asm4[4].Identity.Name); Assert.Equal(8, (from a in asm4[4].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(2, (from a in asm4[4].BoundReferences() where object.ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal(2, (from a in asm4[4].BoundReferences() where object.ReferenceEquals(a, asm4[1]) select a).Count()); Assert.Equal(2, (from a in asm4[4].BoundReferences() where object.ReferenceEquals(a, asm4[2]) select a).Count()); Assert.Equal(2, (from a in asm4[4].BoundReferences() where object.ReferenceEquals(a, asm4[3]) select a).Count()); var type3 = asm4[4].GlobalNamespace.GetTypeMembers("Class6"). Single(); var retval10 = type3.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval10.Kind); Assert.Same(retval10, asm4[2].GlobalNamespace.GetMembers("Class1").Single()); var retval11 = type3.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval11.Kind); Assert.Same(retval11, asm4[2].GlobalNamespace.GetMembers("Class2").Single()); var retval12 = type3.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval12.Kind); Assert.Same(retval12, asm4[2].GlobalNamespace.GetMembers("Class3").Single()); var retval13 = type3.GetMembers("Foo4").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval13.Kind); Assert.Same(retval13, asm4[1].GlobalNamespace.GetMembers("Class4").Single()); var retval14 = type3.GetMembers("Foo5").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval14.Kind); Assert.Same(retval14, asm4[3].GlobalNamespace.GetMembers("Class5").Single()); var c5 = CreateCompilation(new AssemblyIdentity("c5"), null, new MetadataReference[] { Net451.mscorlib, new CSharpCompilationReference(varC_MTTestLib3) }); var asm5 = c5.SourceAssembly().BoundReferences(); Assert.Same(asm5[0], asm2[0]); Assert.True(asm5[1].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(asm3[3])); var c6 = CreateCompilation(new AssemblyIdentity("c6"), null, new MetadataReference[] { Net451.mscorlib, new CSharpCompilationReference(varC_MTTestLib2) }); var asm6 = c6.SourceAssembly().BoundReferences(); Assert.Same(asm6[0], asm2[0]); Assert.True(asm6[1].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(varC_MTTestLib2.SourceAssembly())); var c7 = CreateCompilation(new AssemblyIdentity("c7"), null, new MetadataReference[] { Net451.mscorlib, new CSharpCompilationReference(varC_MTTestLib2), new CSharpCompilationReference(varC_MTTestLib3), new CSharpCompilationReference(varC_MTTestLib4) }); var asm7 = c7.SourceAssembly().BoundReferences(); Assert.Same(asm7[0], asm2[0]); Assert.True(asm7[1].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(varC_MTTestLib2.SourceAssembly())); Assert.NotSame(asm7[2], asm3[3]); Assert.NotSame(asm7[2], asm4[3]); Assert.NotSame(asm7[3], asm4[4]); Assert.Equal("MTTestLib3", asm7[2].Identity.Name); Assert.Same(((RetargetingAssemblySymbol)asm7[2]).UnderlyingAssembly, asm3[3]); Assert.Equal(4, (from a in asm7[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(2, (from a in asm7[2].BoundReferences() where object.ReferenceEquals(a, asm7[0]) select a).Count()); Assert.Equal(2, (from a in asm7[2].BoundReferences() where object.ReferenceEquals(a, asm7[1]) select a).Count()); var type4 = asm7[2].GlobalNamespace.GetTypeMembers("Class5"). Single(); var retval15 = type4.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; AssemblySymbol missingAssembly; missingAssembly = retval15.ContainingAssembly; Assert.True(missingAssembly.IsMissing); Assert.Equal("MTTestLib1", missingAssembly.Identity.Name); var retval16 = type4.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.Same(missingAssembly, retval16.ContainingAssembly); var retval17 = type4.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval17.Kind); Assert.Same(retval17, asm7[1].GlobalNamespace.GetMembers("Class4").Single()); Assert.Equal("MTTestLib4", asm7[3].Identity.Name); Assert.Same(((RetargetingAssemblySymbol)asm7[3]).UnderlyingAssembly, asm4[4]); Assert.Equal(6, (from a in asm7[3].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(2, (from a in asm7[3].BoundReferences() where object.ReferenceEquals(a, asm7[0]) select a).Count()); Assert.Equal(2, (from a in asm7[3].BoundReferences() where object.ReferenceEquals(a, asm7[1]) select a).Count()); Assert.Equal(2, (from a in asm7[3].BoundReferences() where object.ReferenceEquals(a, asm7[2]) select a).Count()); var type5 = asm7[3].GlobalNamespace.GetTypeMembers("Class6"). Single(); var retval18 = type5.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal("MTTestLib1", ((MissingMetadataTypeSymbol)retval18).ContainingAssembly.Identity.Name); var retval19 = type5.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.Same(retval18.ContainingAssembly, retval19.ContainingAssembly); var retval20 = type5.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.Same(retval18.ContainingAssembly, retval20.ContainingAssembly); var retval21 = type5.GetMembers("Foo4").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval21.Kind); Assert.Same(retval21, asm7[1].GlobalNamespace.GetMembers("Class4").Single()); var retval22 = type5.GetMembers("Foo5").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval22.Kind); Assert.Same(retval22, asm7[2].GlobalNamespace.GetMembers("Class5").Single()); // This test shows that simple reordering of references doesn't pick different set of assemblies var c8 = CreateCompilation(new AssemblyIdentity("c8"), null, new MetadataReference[] { Net451.mscorlib, new CSharpCompilationReference(varC_MTTestLib4), new CSharpCompilationReference(varC_MTTestLib2), new CSharpCompilationReference(varC_MTTestLib3) }); var asm8 = c8.SourceAssembly().BoundReferences(); Assert.Same(asm8[0], asm2[0]); Assert.True(asm8[2].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(asm4[1])); Assert.Same(asm8[2], asm7[1]); Assert.True(asm8[3].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(asm4[3])); Assert.Same(asm8[3], asm7[2]); Assert.True(asm8[1].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(asm4[4])); Assert.Same(asm8[1], asm7[3]); var c9 = CreateCompilation(new AssemblyIdentity("c9"), null, new MetadataReference[] { Net451.mscorlib, new CSharpCompilationReference(varC_MTTestLib4) }); var asm9 = c9.SourceAssembly().BoundReferences(); Assert.Same(asm9[0], asm2[0]); Assert.True(asm9[1].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(asm4[4])); var c10 = CreateCompilation(new AssemblyIdentity("c10"), null, new MetadataReference[] { Net451.mscorlib, TestReferences.SymbolsTests.V3.MTTestLib1.dll, new CSharpCompilationReference(varC_MTTestLib2), new CSharpCompilationReference(varC_MTTestLib3), new CSharpCompilationReference(varC_MTTestLib4) }); var asm10Prime = c10.SourceAssembly().BoundReferences(); var asm10 = new AssemblySymbol[] { asm10Prime[0], asm10Prime[2], asm10Prime[1], asm10Prime[3], asm10Prime[4] }; Assert.Same(asm10[0], asm2[0]); Assert.Same(asm10[1], asm4[1]); Assert.Same(asm10[2], asm4[2]); Assert.Same(asm10[3], asm4[3]); Assert.Same(asm10[4], asm4[4]); // Run the same tests again to make sure we didn't corrupt prior state by loading additional assemblies Assert.Same(asm2[0], asm_MTTestLib2[0]); Assert.Equal("MTTestLib2", asm2[1].Identity.Name); Assert.Equal(4, (from a in asm2[1].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(2, (from a in asm2[1].BoundReferences() where object.ReferenceEquals(a, asm2[0]) select a).Count()); Assert.Equal(2, (from a in asm2[1].BoundReferences() where object.ReferenceEquals(a, asm2[2]) select a).Count()); retval1 = asm2[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Foo").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval1.Kind); Assert.Same(retval1, asm2[2].GlobalNamespace.GetMembers("Class1").Single()); Assert.Equal("MTTestLib1", asm2[2].Identity.Name); Assert.Equal(1, asm2[2].Identity.Version.Major); Assert.Equal(1, (from a in asm2[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm2[2].BoundReferences() where object.ReferenceEquals(a, asm2[0]) select a).Count()); Assert.Same(asm_MTTestLib3[0], asm_MTTestLib2[0]); Assert.NotSame(asm_MTTestLib3[1], varC_MTTestLib2.SourceAssembly()); Assert.NotSame(asm_MTTestLib3[2], asm_MTTestLib2[1]); Assert.Same(asm3[0], asm_MTTestLib2[0]); Assert.Same(asm3[1], asm_MTTestLib3[1]); Assert.Same(asm3[2], asm_MTTestLib3[2]); Assert.Same(asm3[3], varC_MTTestLib3.SourceAssembly()); Assert.Equal("MTTestLib2", asm3[1].Identity.Name); Assert.Same(((RetargetingAssemblySymbol)asm3[1]).UnderlyingAssembly, varC_MTTestLib2.SourceAssembly()); Assert.Equal(4, (from a in asm3[1].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(2, (from a in asm3[1].BoundReferences() where object.ReferenceEquals(a, asm3[0]) select a).Count()); Assert.Equal(2, (from a in asm3[1].BoundReferences() where object.ReferenceEquals(a, asm3[2]) select a).Count()); retval2 = asm3[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Foo").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval2.Kind); Assert.Same(retval2, asm3[2].GlobalNamespace.GetMembers("Class1").Single()); Assert.Equal("MTTestLib1", asm3[2].Identity.Name); Assert.NotSame(asm3[2], asm2[2]); Assert.NotSame(((PEAssemblySymbol)asm3[2]).Assembly, ((PEAssemblySymbol)asm2[2]).Assembly); Assert.Equal(2, asm3[2].Identity.Version.Major); Assert.Equal(1, (from a in asm3[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm3[2].BoundReferences() where object.ReferenceEquals(a, asm3[0]) select a).Count()); Assert.Equal("MTTestLib3", asm3[3].Identity.Name); Assert.Equal(6, (from a in asm3[3].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(2, (from a in asm3[3].BoundReferences() where object.ReferenceEquals(a, asm3[0]) select a).Count()); Assert.Equal(2, (from a in asm3[3].BoundReferences() where object.ReferenceEquals(a, asm3[1]) select a).Count()); Assert.Equal(2, (from a in asm3[3].BoundReferences() where object.ReferenceEquals(a, asm3[2]) select a).Count()); type1 = asm3[3].GlobalNamespace.GetTypeMembers("Class5"). Single(); retval3 = type1.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval3.Kind); Assert.Same(retval3, asm3[2].GlobalNamespace.GetMembers("Class1").Single()); retval4 = type1.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval4.Kind); Assert.Same(retval4, asm3[2].GlobalNamespace.GetMembers("Class2").Single()); retval5 = type1.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval5.Kind); Assert.Same(retval5, asm3[1].GlobalNamespace.GetMembers("Class4").Single()); Assert.Same(asm4[0], asm_MTTestLib2[0]); Assert.Same(asm4[1], asm_MTTestLib4[1]); Assert.Same(asm4[2], asm_MTTestLib4[2]); Assert.Same(asm4[3], asm_MTTestLib4[3]); Assert.Same(asm4[4], varC_MTTestLib4.SourceAssembly()); Assert.Equal("MTTestLib2", asm4[1].Identity.Name); Assert.NotSame(asm4[1], varC_MTTestLib2.SourceAssembly()); Assert.NotSame(asm4[1], asm2[1]); Assert.NotSame(asm4[1], asm3[1]); Assert.Same(((RetargetingAssemblySymbol)asm4[1]).UnderlyingAssembly, varC_MTTestLib2.SourceAssembly()); Assert.Equal(4, (from a in asm4[1].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(2, (from a in asm4[1].BoundReferences() where object.ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal(2, (from a in asm4[1].BoundReferences() where object.ReferenceEquals(a, asm4[2]) select a).Count()); retval6 = asm4[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Foo").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval6.Kind); Assert.Same(retval6, asm4[2].GlobalNamespace.GetMembers("Class1").Single()); Assert.Equal("MTTestLib1", asm4[2].Identity.Name); Assert.NotSame(asm4[2], asm2[2]); Assert.NotSame(asm4[2], asm3[2]); Assert.NotSame(((PEAssemblySymbol)asm4[2]).Assembly, ((PEAssemblySymbol)asm2[2]).Assembly); Assert.NotSame(((PEAssemblySymbol)asm4[2]).Assembly, ((PEAssemblySymbol)asm3[2]).Assembly); Assert.Equal(3, asm4[2].Identity.Version.Major); Assert.Equal(1, (from a in asm4[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm4[2].BoundReferences() where object.ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal("MTTestLib3", asm4[3].Identity.Name); Assert.NotSame(asm4[3], asm3[3]); Assert.Same(((RetargetingAssemblySymbol)asm4[3]).UnderlyingAssembly, asm3[3]); Assert.Equal(6, (from a in asm4[3].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(2, (from a in asm4[3].BoundReferences() where object.ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal(2, (from a in asm4[3].BoundReferences() where object.ReferenceEquals(a, asm4[1]) select a).Count()); Assert.Equal(2, (from a in asm4[3].BoundReferences() where object.ReferenceEquals(a, asm4[2]) select a).Count()); type2 = asm4[3].GlobalNamespace.GetTypeMembers("Class5"). Single(); retval7 = type2.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval7.Kind); Assert.Same(retval7, asm4[2].GlobalNamespace.GetMembers("Class1").Single()); retval8 = type2.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval8.Kind); Assert.Same(retval8, asm4[2].GlobalNamespace.GetMembers("Class2").Single()); retval9 = type2.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval9.Kind); Assert.Same(retval9, asm4[1].GlobalNamespace.GetMembers("Class4").Single()); Assert.Equal("MTTestLib4", asm4[4].Identity.Name); Assert.Equal(8, (from a in asm4[4].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(2, (from a in asm4[4].BoundReferences() where object.ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal(2, (from a in asm4[4].BoundReferences() where object.ReferenceEquals(a, asm4[1]) select a).Count()); Assert.Equal(2, (from a in asm4[4].BoundReferences() where object.ReferenceEquals(a, asm4[2]) select a).Count()); Assert.Equal(2, (from a in asm4[4].BoundReferences() where object.ReferenceEquals(a, asm4[3]) select a).Count()); type3 = asm4[4].GlobalNamespace.GetTypeMembers("Class6"). Single(); retval10 = type3.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval10.Kind); Assert.Same(retval10, asm4[2].GlobalNamespace.GetMembers("Class1").Single()); retval11 = type3.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval11.Kind); Assert.Same(retval11, asm4[2].GlobalNamespace.GetMembers("Class2").Single()); retval12 = type3.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval12.Kind); Assert.Same(retval12, asm4[2].GlobalNamespace.GetMembers("Class3").Single()); retval13 = type3.GetMembers("Foo4").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval13.Kind); Assert.Same(retval13, asm4[1].GlobalNamespace.GetMembers("Class4").Single()); retval14 = type3.GetMembers("Foo5").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval14.Kind); Assert.Same(retval14, asm4[3].GlobalNamespace.GetMembers("Class5").Single()); Assert.Same(asm5[0], asm2[0]); Assert.True(asm5[1].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(asm3[3])); Assert.Same(asm6[0], asm2[0]); Assert.True(asm6[1].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(varC_MTTestLib2.SourceAssembly())); Assert.Same(asm7[0], asm2[0]); Assert.True(asm7[1].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(varC_MTTestLib2.SourceAssembly())); Assert.NotSame(asm7[2], asm3[3]); Assert.NotSame(asm7[2], asm4[3]); Assert.NotSame(asm7[3], asm4[4]); Assert.Equal("MTTestLib3", asm7[2].Identity.Name); Assert.Same(((RetargetingAssemblySymbol)asm7[2]).UnderlyingAssembly, asm3[3]); Assert.Equal(4, (from a in asm7[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(2, (from a in asm7[2].BoundReferences() where object.ReferenceEquals(a, asm7[0]) select a).Count()); Assert.Equal(2, (from a in asm7[2].BoundReferences() where object.ReferenceEquals(a, asm7[1]) select a).Count()); type4 = asm7[2].GlobalNamespace.GetTypeMembers("Class5"). Single(); retval15 = type4.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; missingAssembly = retval15.ContainingAssembly; Assert.True(missingAssembly.IsMissing); Assert.Equal("MTTestLib1", missingAssembly.Identity.Name); retval16 = type4.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.Same(missingAssembly, retval16.ContainingAssembly); retval17 = type4.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval17.Kind); Assert.Same(retval17, asm7[1].GlobalNamespace.GetMembers("Class4").Single()); Assert.Equal("MTTestLib4", asm7[3].Identity.Name); Assert.Same(((RetargetingAssemblySymbol)asm7[3]).UnderlyingAssembly, asm4[4]); Assert.Equal(6, (from a in asm7[3].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(2, (from a in asm7[3].BoundReferences() where object.ReferenceEquals(a, asm7[0]) select a).Count()); Assert.Equal(2, (from a in asm7[3].BoundReferences() where object.ReferenceEquals(a, asm7[1]) select a).Count()); Assert.Equal(2, (from a in asm7[3].BoundReferences() where object.ReferenceEquals(a, asm7[2]) select a).Count()); type5 = asm7[3].GlobalNamespace.GetTypeMembers("Class6"). Single(); retval18 = type5.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal("MTTestLib1", ((MissingMetadataTypeSymbol)retval18).ContainingAssembly.Identity.Name); retval19 = type5.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.Same(retval18.ContainingAssembly, retval19.ContainingAssembly); retval20 = type5.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.Same(retval18.ContainingAssembly, retval20.ContainingAssembly); retval21 = type5.GetMembers("Foo4").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval21.Kind); Assert.Same(retval21, asm7[1].GlobalNamespace.GetMembers("Class4").Single()); retval22 = type5.GetMembers("Foo5").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval22.Kind); Assert.Same(retval22, asm7[2].GlobalNamespace.GetMembers("Class5").Single()); } [Fact] public void MultiTargeting4() { var localC1_V1_Name = new AssemblyIdentity("c1", new Version("1.0.0.0")); var localC1_V1 = CreateCompilation(localC1_V1_Name, new string[] { // AssemblyPaths.SymbolsTests.MultiTargeting.Source1Module.netmodule @" public class C1<T> { public class C2<S> { public C1<T>.C2<S> Foo() { return null; } } } " }, new[] { Net451.mscorlib }); var asm1_V1 = localC1_V1.SourceAssembly(); var localC1_V2_Name = new AssemblyIdentity("c1", new Version("2.0.0.0")); var localC1_V2 = CreateCompilation(localC1_V2_Name, new string[] { // AssemblyPaths.SymbolsTests.MultiTargeting.Source1Module.netmodule @" public class C1<T> { public class C2<S> { public C1<T>.C2<S> Foo() { return null; } } } " }, new MetadataReference[] { Net451.mscorlib }); var asm1_V2 = localC1_V2.SourceAssembly(); var localC4_V1_Name = new AssemblyIdentity("c4", new Version("1.0.0.0")); var localC4_V1 = CreateCompilation(localC4_V1_Name, new string[] { // AssemblyPaths.SymbolsTests.MultiTargeting.Source4Module.netmodule @" public class C4 { } " }, new MetadataReference[] { Net451.mscorlib }); var asm4_V1 = localC4_V1.SourceAssembly(); var localC4_V2_Name = new AssemblyIdentity("c4", new Version("2.0.0.0")); var localC4_V2 = CreateCompilation(localC4_V2_Name, new string[] { // AssemblyPaths.SymbolsTests.MultiTargeting.Source4Module.netmodule @" public class C4 { } " }, new MetadataReference[] { Net451.mscorlib }); var asm4_V2 = localC4_V2.SourceAssembly(); var c7 = CreateCompilation(new AssemblyIdentity("C7"), new string[] { // AssemblyPaths.SymbolsTests.MultiTargeting.Source7Module.netmodule @" public class C7 {} public class C8<T> { } " }, new MetadataReference[] { Net451.mscorlib }); var asm7 = c7.SourceAssembly(); var c3 = CreateCompilation(new AssemblyIdentity("C3"), new string[] { // AssemblyPaths.SymbolsTests.MultiTargeting.Source3Module.netmodule @" public class C3 { public C1<C3>.C2<C4> Foo() { return null; } public static C6<C4> Bar() { return null; } public C8<C7> Foo1() { return null; } public void Foo2(ref C300[,] x1, out C4 x2, ref C7[] x3, C4 x4 = null) { x2 = null; } internal virtual TFoo3 Foo3<TFoo3>() where TFoo3: C4 { return null; } public C8<C4> Foo4() { return null; } public abstract class C301 : I1 { } internal class C302 { } } public class C6<T> where T: new () {} public class C300 {} public interface I1 {} namespace ns1 { namespace ns2 { public class C303 {} } public class C304 { public class C305 {} } } " }, new MetadataReference[] { Net451.mscorlib, new CSharpCompilationReference(localC1_V1), new CSharpCompilationReference(localC4_V1), new CSharpCompilationReference(c7) }); var asm3 = c3.SourceAssembly(); var localC3Foo2 = asm3.GlobalNamespace.GetTypeMembers("C3"). Single().GetMembers("Foo2").OfType<MethodSymbol>().Single(); var c5 = CreateCompilation(new AssemblyIdentity("C5"), new string[] { // AssemblyPaths.SymbolsTests.MultiTargeting.Source5Module.netmodule @" public class C5 : ns1.C304.C305 {} " }, new MetadataReference[] { Net451.mscorlib, new CSharpCompilationReference(c3), new CSharpCompilationReference(localC1_V2), new CSharpCompilationReference(localC4_V2), new CSharpCompilationReference(c7) }); var asm5 = c5.SourceAssembly().BoundReferences(); Assert.NotSame(asm5[1], asm3); Assert.Same(((RetargetingAssemblySymbol)asm5[1]).UnderlyingAssembly, asm3); Assert.Same(asm5[2], asm1_V2); Assert.Same(asm5[3], asm4_V2); Assert.Same(asm5[4], asm7); var type3 = asm5[1].GlobalNamespace.GetTypeMembers("C3"). Single(); var type1 = asm1_V2.GlobalNamespace.GetTypeMembers("C1"). Single(); var type2 = type1.GetTypeMembers("C2"). Single(); var type4 = asm4_V2.GlobalNamespace.GetTypeMembers("C4"). Single(); var retval1 = (NamedTypeSymbol)type3.GetMembers("Foo").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal("C1<C3>.C2<C4>", retval1.ToTestDisplayString()); Assert.Same(retval1.OriginalDefinition, type2); var args1 = retval1.ContainingType.TypeArguments().Concat(retval1.TypeArguments()); var params1 = retval1.ContainingType.TypeParameters.Concat(retval1.TypeParameters); Assert.Same(params1[0], type1.TypeParameters[0]); Assert.Same(params1[1].OriginalDefinition, type2.TypeParameters[0].OriginalDefinition); Assert.Same(args1[0], type3); Assert.Same(args1[0].ContainingAssembly, asm5[1]); Assert.Same(args1[1], type4); var retval2 = retval1.ContainingType; Assert.Equal("C1<C3>", retval2.ToTestDisplayString()); Assert.Same(retval2.OriginalDefinition, type1); var bar = type3.GetMembers("Bar").OfType<MethodSymbol>().Single(); var retval3 = (NamedTypeSymbol)bar.ReturnType; var type6 = asm5[1].GlobalNamespace.GetTypeMembers("C6"). Single(); Assert.Equal("C6<C4>", retval3.ToTestDisplayString()); Assert.Same(retval3.OriginalDefinition, type6); Assert.Same(retval3.ContainingAssembly, asm5[1]); var args3 = retval3.TypeArguments(); var params3 = retval3.TypeParameters; Assert.Same(params3[0], type6.TypeParameters[0]); Assert.Same(params3[0].ContainingAssembly, asm5[1]); Assert.Same(args3[0], type4); var foo1 = type3.GetMembers("Foo1").OfType<MethodSymbol>().Single(); var retval4 = foo1.ReturnType; Assert.Equal("C8<C7>", retval4.ToTestDisplayString()); Assert.Same(retval4, asm3.GlobalNamespace.GetTypeMembers("C3"). Single(). GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType); var foo1Params = foo1.Parameters; Assert.Equal(0, foo1Params.Length); var foo2 = type3.GetMembers("Foo2").OfType<MethodSymbol>().Single(); Assert.NotEqual(localC3Foo2, foo2); Assert.Same(localC3Foo2, ((RetargetingMethodSymbol)foo2).UnderlyingMethod); Assert.Equal(1, ((RetargetingMethodSymbol)foo2).Locations.Length); var foo2Params = foo2.Parameters; Assert.Equal(4, foo2Params.Length); Assert.Same(localC3Foo2.Parameters[0], ((RetargetingParameterSymbol)foo2Params[0]).UnderlyingParameter); Assert.Same(localC3Foo2.Parameters[1], ((RetargetingParameterSymbol)foo2Params[1]).UnderlyingParameter); Assert.Same(localC3Foo2.Parameters[2], ((RetargetingParameterSymbol)foo2Params[2]).UnderlyingParameter); Assert.Same(localC3Foo2.Parameters[3], ((RetargetingParameterSymbol)foo2Params[3]).UnderlyingParameter); var x1 = foo2Params[0]; var x2 = foo2Params[1]; var x3 = foo2Params[2]; var x4 = foo2Params[3]; Assert.Equal("x1", x1.Name); Assert.NotEqual(localC3Foo2.Parameters[0].Type, x1.Type); Assert.Equal(localC3Foo2.Parameters[0].ToTestDisplayString(), x1.ToTestDisplayString()); Assert.Same(asm5[1], x1.ContainingAssembly); Assert.Same(foo2, x1.ContainingSymbol); Assert.False(x1.HasExplicitDefaultValue); Assert.False(x1.IsOptional); Assert.Equal(RefKind.Ref, x1.RefKind); Assert.Equal(2, ((ArrayTypeSymbol)x1.Type).Rank); Assert.Equal("x2", x2.Name); Assert.NotEqual(localC3Foo2.Parameters[1].Type, x2.Type); Assert.Equal(RefKind.Out, x2.RefKind); Assert.Equal("x3", x3.Name); Assert.Same(localC3Foo2.Parameters[2].Type, x3.Type); Assert.Equal("x4", x4.Name); Assert.True(x4.HasExplicitDefaultValue); Assert.True(x4.IsOptional); Assert.Equal("Foo2", foo2.Name); Assert.Equal(localC3Foo2.ToTestDisplayString(), foo2.ToTestDisplayString()); Assert.Same(asm5[1], foo2.ContainingAssembly); Assert.Same(type3, foo2.ContainingSymbol); Assert.Equal(Accessibility.Public, foo2.DeclaredAccessibility); Assert.False(foo2.HidesBaseMethodsByName); Assert.False(foo2.IsAbstract); Assert.False(foo2.IsExtern); Assert.False(foo2.IsGenericMethod); Assert.False(foo2.IsOverride); Assert.False(foo2.IsSealed); Assert.False(foo2.IsStatic); Assert.False(foo2.IsVararg); Assert.False(foo2.IsVirtual); Assert.True(foo2.ReturnsVoid); Assert.Equal(0, foo2.TypeParameters.Length); Assert.Equal(0, foo2.TypeArgumentsWithAnnotations.Length); Assert.True(bar.IsStatic); Assert.False(bar.ReturnsVoid); var foo3 = type3.GetMembers("Foo3").OfType<MethodSymbol>().Single(); Assert.Equal(Accessibility.Internal, foo3.DeclaredAccessibility); Assert.True(foo3.IsGenericMethod); Assert.True(foo3.IsVirtual); var foo3TypeParams = foo3.TypeParameters; Assert.Equal(1, foo3TypeParams.Length); Assert.Equal(1, foo3.TypeArgumentsWithAnnotations.Length); Assert.Same(foo3TypeParams[0], foo3.TypeArgumentsWithAnnotations[0].Type); var typeC301 = type3.GetTypeMembers("C301").Single(); var typeC302 = type3.GetTypeMembers("C302").Single(); var typeC6 = asm5[1].GlobalNamespace.GetTypeMembers("C6").Single(); Assert.Equal(typeC301.ToTestDisplayString(), asm3.GlobalNamespace.GetTypeMembers("C3").Single(). GetTypeMembers("C301").Single().ToTestDisplayString()); Assert.Equal(typeC6.ToTestDisplayString(), asm3.GlobalNamespace.GetTypeMembers("C6").Single().ToTestDisplayString()); Assert.Equal(typeC301.ToDisplayString(SymbolDisplayFormat.QualifiedNameArityFormat), asm3.GlobalNamespace.GetTypeMembers("C3").Single(). GetTypeMembers("C301").Single().ToDisplayString(SymbolDisplayFormat.QualifiedNameArityFormat)); Assert.Equal(typeC6.ToDisplayString(SymbolDisplayFormat.QualifiedNameArityFormat), asm3.GlobalNamespace.GetTypeMembers("C6").Single().ToDisplayString(SymbolDisplayFormat.QualifiedNameArityFormat)); Assert.Equal(type3.GetMembers().Length, asm3.GlobalNamespace.GetTypeMembers("C3").Single().GetMembers().Length); Assert.Equal(type3.GetTypeMembers().Length, asm3.GlobalNamespace.GetTypeMembers("C3").Single().GetTypeMembers().Length); Assert.Same(typeC301, type3.GetTypeMembers("C301", 0).Single()); Assert.Equal(0, type3.Arity); Assert.Equal(1, typeC6.Arity); Assert.NotNull(type3.BaseType()); Assert.Equal("System.Object", type3.BaseType().ToTestDisplayString()); Assert.Equal(Accessibility.Public, type3.DeclaredAccessibility); Assert.Equal(Accessibility.Internal, typeC302.DeclaredAccessibility); Assert.Equal(0, type3.Interfaces().Length); Assert.Equal(1, typeC301.Interfaces().Length); Assert.Equal("I1", typeC301.Interfaces().Single().Name); Assert.False(type3.IsAbstract); Assert.True(typeC301.IsAbstract); Assert.False(type3.IsSealed); Assert.False(type3.IsStatic); Assert.Equal(0, type3.TypeArguments().Length); Assert.Equal(0, type3.TypeParameters.Length); var localC6Params = typeC6.TypeParameters; Assert.Equal(1, localC6Params.Length); Assert.Equal(1, typeC6.TypeArguments().Length); Assert.Same(localC6Params[0], typeC6.TypeArguments()[0]); Assert.Same(((RetargetingNamedTypeSymbol)type3).UnderlyingNamedType, asm3.GlobalNamespace.GetTypeMembers("C3").Single()); Assert.Equal(1, ((RetargetingNamedTypeSymbol)type3).Locations.Length); Assert.Equal(TypeKind.Class, type3.TypeKind); Assert.Equal(TypeKind.Interface, asm5[1].GlobalNamespace.GetTypeMembers("I1").Single().TypeKind); var localC6_T = localC6Params[0]; var foo3TypeParam = foo3TypeParams[0]; Assert.Equal(0, localC6_T.ConstraintTypes().Length); Assert.Equal(1, foo3TypeParam.ConstraintTypes().Length); Assert.Same(type4, foo3TypeParam.ConstraintTypes().Single()); Assert.Same(typeC6, localC6_T.ContainingSymbol); Assert.False(foo3TypeParam.HasConstructorConstraint); Assert.True(localC6_T.HasConstructorConstraint); Assert.False(foo3TypeParam.HasReferenceTypeConstraint); Assert.False(foo3TypeParam.HasValueTypeConstraint); Assert.Equal("TFoo3", foo3TypeParam.Name); Assert.Equal("T", localC6_T.Name); Assert.Equal(0, foo3TypeParam.Ordinal); Assert.Equal(0, localC6_T.Ordinal); Assert.Equal(VarianceKind.None, foo3TypeParam.Variance); Assert.Same(((RetargetingTypeParameterSymbol)localC6_T).UnderlyingTypeParameter, asm3.GlobalNamespace.GetTypeMembers("C6").Single().TypeParameters[0]); var ns1 = asm5[1].GlobalNamespace.GetMembers("ns1").OfType<NamespaceSymbol>().Single(); var ns2 = ns1.GetMembers("ns2").OfType<NamespaceSymbol>().Single(); Assert.Equal("ns1.ns2", ns2.ToTestDisplayString()); Assert.Equal(2, ns1.GetMembers().Length); Assert.Equal(1, ns1.GetTypeMembers().Length); Assert.Same(ns1.GetTypeMembers("C304").Single(), ns1.GetTypeMembers("C304", 0).Single()); Assert.Same(asm5[1].Modules[0], asm5[1].Modules[0].GlobalNamespace.ContainingSymbol); Assert.Same(asm5[1].Modules[0].GlobalNamespace, ns1.ContainingSymbol); Assert.Same(asm5[1].Modules[0], ns1.Extent.Module); Assert.Equal(1, ns1.ConstituentNamespaces.Length); Assert.Same(ns1, ns1.ConstituentNamespaces[0]); Assert.False(ns1.IsGlobalNamespace); Assert.True(asm5[1].Modules[0].GlobalNamespace.IsGlobalNamespace); Assert.Same(asm3.Modules[0].GlobalNamespace, ((RetargetingNamespaceSymbol)asm5[1].Modules[0].GlobalNamespace).UnderlyingNamespace); Assert.Same(asm3.Modules[0].GlobalNamespace.GetMembers("ns1").Single(), ((RetargetingNamespaceSymbol)ns1).UnderlyingNamespace); var module3 = (RetargetingModuleSymbol)asm5[1].Modules[0]; Assert.Equal("C3.dll", module3.ToTestDisplayString()); Assert.Equal("C3.dll", module3.Name); Assert.Same(asm5[1], module3.ContainingSymbol); Assert.Same(asm5[1], module3.ContainingAssembly); Assert.Null(module3.ContainingType); var retval5 = type3.GetMembers("Foo4").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal("C8<C4>", retval5.ToTestDisplayString()); var typeC5 = c5.Assembly.GlobalNamespace.GetTypeMembers("C5").Single(); Assert.Same(asm5[1], typeC5.BaseType().ContainingAssembly); Assert.Equal("ns1.C304.C305", typeC5.BaseType().ToTestDisplayString()); Assert.NotEqual(SymbolKind.ErrorType, typeC5.Kind); } [Fact] public void MultiTargeting5() { var c1_Name = new AssemblyIdentity("c1"); var text = @" class Module1 { Class4 M1() {} Class4.Class4_1 M2() {} Class4 M3() {} } "; var c1 = CreateEmptyCompilation(text, new MetadataReference[] { MscorlibRef, TestReferences.SymbolsTests.V1.MTTestLib1.dll, TestReferences.SymbolsTests.V1.MTTestModule2.netmodule }); var c2_Name = new AssemblyIdentity("MTTestLib2"); var c2 = CreateCompilation(c2_Name, null, new MetadataReference[] { Net451.mscorlib, TestReferences.SymbolsTests.V2.MTTestLib1.dll, new CSharpCompilationReference(c1) }); SourceAssemblySymbol c1AsmSource = (SourceAssemblySymbol)c1.Assembly; PEAssemblySymbol Lib1_V1 = (PEAssemblySymbol)c1AsmSource.Modules[0].GetReferencedAssemblySymbols()[1]; PEModuleSymbol module1 = (PEModuleSymbol)c1AsmSource.Modules[1]; Assert.Equal(LocationKind.MetadataFile, ((MetadataLocation)Lib1_V1.Locations[0]).Kind); SourceAssemblySymbol c2AsmSource = (SourceAssemblySymbol)c2.Assembly; RetargetingAssemblySymbol c1AsmRef = (RetargetingAssemblySymbol)c2AsmSource.Modules[0].GetReferencedAssemblySymbols()[2]; PEAssemblySymbol Lib1_V2 = (PEAssemblySymbol)c2AsmSource.Modules[0].GetReferencedAssemblySymbols()[1]; PEModuleSymbol module2 = (PEModuleSymbol)c1AsmRef.Modules[1]; Assert.Equal(1, Lib1_V1.Identity.Version.Major); Assert.Equal(2, Lib1_V2.Identity.Version.Major); Assert.NotEqual(module1, module2); Assert.Same(module1.Module, module2.Module); NamedTypeSymbol classModule1 = c1AsmRef.Modules[0].GlobalNamespace.GetTypeMembers("Module1").Single(); MethodSymbol m1 = classModule1.GetMembers("M1").OfType<MethodSymbol>().Single(); MethodSymbol m2 = classModule1.GetMembers("M2").OfType<MethodSymbol>().Single(); MethodSymbol m3 = classModule1.GetMembers("M3").OfType<MethodSymbol>().Single(); Assert.Same(module2, m1.ReturnType.ContainingModule); Assert.Same(module2, m2.ReturnType.ContainingModule); Assert.Same(module2, m3.ReturnType.ContainingModule); } // Very simplistic test if a compilation has a single type with the given full name. Does NOT handle generics. private bool HasSingleTypeOfKind(CSharpCompilation c, TypeKind kind, string fullName) { string[] names = fullName.Split('.'); NamespaceOrTypeSymbol current = c.GlobalNamespace; foreach (string name in names) { var matchingSym = current.GetMembers(name); if (matchingSym.Length != 1) { return false; } current = (NamespaceOrTypeSymbol)matchingSym.First(); } return current is TypeSymbol && ((TypeSymbol)current).TypeKind == kind; } [Fact] public void AddRemoveReferences() { var mscorlibRef = Net451.mscorlib; var systemCoreRef = Net451.SystemCore; var systemRef = Net451.System; CSharpCompilation c = CSharpCompilation.Create("Test"); Assert.False(HasSingleTypeOfKind(c, TypeKind.Struct, "System.Int32")); c = c.AddReferences(mscorlibRef); Assert.True(HasSingleTypeOfKind(c, TypeKind.Struct, "System.Int32")); Assert.False(HasSingleTypeOfKind(c, TypeKind.Class, "System.Linq.Enumerable")); c = c.AddReferences(systemCoreRef); Assert.True(HasSingleTypeOfKind(c, TypeKind.Class, "System.Linq.Enumerable")); Assert.False(HasSingleTypeOfKind(c, TypeKind.Class, "System.Uri")); c = c.ReplaceReference(systemCoreRef, systemRef); Assert.False(HasSingleTypeOfKind(c, TypeKind.Class, "System.Linq.Enumerable")); Assert.True(HasSingleTypeOfKind(c, TypeKind.Class, "System.Uri")); c = c.RemoveReferences(systemRef); Assert.False(HasSingleTypeOfKind(c, TypeKind.Class, "System.Uri")); Assert.True(HasSingleTypeOfKind(c, TypeKind.Struct, "System.Int32")); c = c.RemoveReferences(mscorlibRef); Assert.False(HasSingleTypeOfKind(c, TypeKind.Struct, "System.Int32")); } private sealed class Resolver : MetadataReferenceResolver { private readonly string _data, _core, _system; public Resolver(string data, string core, string system) { _data = data; _core = core; _system = system; } public override ImmutableArray<PortableExecutableReference> ResolveReference(string reference, string baseFilePath, MetadataReferenceProperties properties) { switch (reference) { case "System.Data": return ImmutableArray.Create(MetadataReference.CreateFromFile(_data)); case "System.Core": return ImmutableArray.Create(MetadataReference.CreateFromFile(_core)); case "System": return ImmutableArray.Create(MetadataReference.CreateFromFile(_system)); default: if (File.Exists(reference)) { return ImmutableArray.Create(MetadataReference.CreateFromFile(reference)); } return ImmutableArray<PortableExecutableReference>.Empty; } } public override bool Equals(object other) => true; public override int GetHashCode() => 1; } [Fact] public void CompilationWithReferenceDirectives() { var data = Temp.CreateFile().WriteAllBytes(ResourcesNet451.SystemData).Path; var core = Temp.CreateFile().WriteAllBytes(ResourcesNet451.SystemCore).Path; var xml = Temp.CreateFile().WriteAllBytes(ResourcesNet451.SystemXml).Path; var system = Temp.CreateFile().WriteAllBytes(ResourcesNet451.System).Path; var trees = new[] { SyntaxFactory.ParseSyntaxTree($@" #r ""System.Data"" #r ""{xml}"" #r ""{core}"" ", options: TestOptions.Script), SyntaxFactory.ParseSyntaxTree(@" #r ""System"" ", options: TestOptions.Script), SyntaxFactory.ParseSyntaxTree(@" new System.Data.DataSet(); System.Linq.Expressions.Expression.Constant(123); System.Diagnostics.Process.GetCurrentProcess(); ", options: TestOptions.Script) }; var compilation = CreateCompilationWithMscorlib45( trees, options: TestOptions.ReleaseDll.WithMetadataReferenceResolver(new Resolver(data, core, system))); compilation.VerifyDiagnostics(); var boundRefs = compilation.Assembly.BoundReferences(); AssertEx.Equal(new[] { "System.Data", "System.Xml", "System.Core", "System", "mscorlib" }, boundRefs.Select(r => r.Name)); } [Fact] public void CompilationWithReferenceDirectives_Errors() { var data = Temp.CreateFile().WriteAllBytes(ResourcesNet451.SystemData).Path; var core = Temp.CreateFile().WriteAllBytes(ResourcesNet451.SystemCore).Path; var system = Temp.CreateFile().WriteAllBytes(ResourcesNet451.System).Path; var trees = new[] { SyntaxFactory.ParseSyntaxTree(@" #r System #r ""~!@#$%^&*():\?/"" #r ""non-existing-reference"" ", options: TestOptions.Script), SyntaxFactory.ParseSyntaxTree(@" #r ""System.Core"" ", TestOptions.Regular) }; var compilation = CreateCompilationWithMscorlib45( trees, options: TestOptions.ReleaseDll.WithMetadataReferenceResolver(new Resolver(data, core, system))); compilation.VerifyDiagnostics( // (3,1): error CS0006: Metadata file '~!@#$%^&*():\?/' could not be found Diagnostic(ErrorCode.ERR_NoMetadataFile, @"#r ""~!@#$%^&*():\?/""").WithArguments(@"~!@#$%^&*():\?/"), // (4,1): error CS0006: Metadata file 'non-existing-reference' could not be found Diagnostic(ErrorCode.ERR_NoMetadataFile, @"#r ""non-existing-reference""").WithArguments("non-existing-reference"), // (2,4): error CS7010: Quoted file name expected Diagnostic(ErrorCode.ERR_ExpectedPPFile, "System"), // (2,1): error CS7011: #r is only allowed in scripts Diagnostic(ErrorCode.ERR_ReferenceDirectiveOnlyAllowedInScripts, "r")); } private class DummyReferenceResolver : MetadataReferenceResolver { private readonly string _targetDll; public DummyReferenceResolver(string targetDll) { _targetDll = targetDll; } public override ImmutableArray<PortableExecutableReference> ResolveReference(string reference, string baseFilePath, MetadataReferenceProperties properties) { var path = reference.EndsWith("-resolve", StringComparison.Ordinal) ? _targetDll : reference; return ImmutableArray.Create(MetadataReference.CreateFromFile(path, properties)); } public override bool Equals(object other) => true; public override int GetHashCode() => 1; } [Fact] public void MetadataReferenceProvider() { var csClasses01 = Temp.CreateFile().WriteAllBytes(TestResources.MetadataTests.InterfaceAndClass.CSClasses01).Path; var csInterfaces01 = Temp.CreateFile().WriteAllBytes(TestResources.MetadataTests.InterfaceAndClass.CSInterfaces01).Path; var source = @" #r """ + "!@#$%^/&*-resolve" + @""" #r """ + csInterfaces01 + @""" class C : Metadata.ICSPropImpl { }"; var compilation = CreateCompilationWithMscorlib45( new[] { Parse(source, options: TestOptions.Script) }, options: TestOptions.ReleaseDll.WithMetadataReferenceResolver(new DummyReferenceResolver(csClasses01))); compilation.VerifyDiagnostics(); } [Fact] public void CompilationWithReferenceDirective_NoResolver() { var compilation = CreateCompilationWithMscorlib45( new[] { SyntaxFactory.ParseSyntaxTree(@"#r ""bar""", TestOptions.Script, "a.csx", Encoding.UTF8) }, options: TestOptions.ReleaseDll.WithMetadataReferenceResolver(null)); compilation.VerifyDiagnostics( // a.csx(1,1): error CS7099: Metadata references not supported. // #r "bar" Diagnostic(ErrorCode.ERR_MetadataReferencesNotSupported, @"#r ""bar""")); } [Fact] public void GlobalUsings1() { var trees = new[] { SyntaxFactory.ParseSyntaxTree(@" WriteLine(1); Console.WriteLine(2); ", options: TestOptions.Script), SyntaxFactory.ParseSyntaxTree(@" class C { void Foo() { Console.WriteLine(3); } } ", TestOptions.Regular) }; var compilation = CreateCompilationWithMscorlib45( trees, options: TestOptions.ReleaseDll.WithUsings(ImmutableArray.Create("System.Console", "System"))); var diagnostics = compilation.GetDiagnostics().ToArray(); // global usings are only visible in script code: DiagnosticsUtils.VerifyErrorCodes(diagnostics, // (4,18): error CS0103: The name 'Console' does not exist in the current context new ErrorDescription() { Code = (int)ErrorCode.ERR_NameNotInContext, Line = 4, Column = 18 }); } [Fact] public void GlobalUsings_Errors() { var trees = new[] { SyntaxFactory.ParseSyntaxTree(@" WriteLine(1); Console.WriteLine(2); ", options: TestOptions.Script) }; var compilation = CreateCompilationWithMscorlib45( trees, options: TestOptions.ReleaseDll.WithUsings("System.Console!", "Blah")); compilation.VerifyDiagnostics( // error CS0234: The type or namespace name 'Console!' does not exist in the namespace 'System' (are you missing an assembly reference?) Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS).WithArguments("Console!", "System"), // error CS0246: The type or namespace name 'Blah' could not be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound).WithArguments("Blah"), // (2,1): error CS0103: The name 'WriteLine' does not exist in the current context Diagnostic(ErrorCode.ERR_NameNotInContext, "WriteLine").WithArguments("WriteLine"), // (3,1): error CS0103: The name 'Console' does not exist in the current context Diagnostic(ErrorCode.ERR_NameNotInContext, "Console").WithArguments("Console")); } [Fact] public void ReferenceToAssemblyWithSpecialCharactersInName() { var r = TestReferences.SymbolsTests.Metadata.InvalidCharactersInAssemblyName; var st = SyntaxFactory.ParseSyntaxTree("class C { static void Main() { new lib.Class1(); } }"); var compilation = CSharpCompilation.Create("foo", references: new[] { MscorlibRef, r }, syntaxTrees: new[] { st }); var diags = compilation.GetDiagnostics().ToArray(); Assert.Equal(0, diags.Length); using (var stream = new MemoryStream()) { compilation.Emit(stream); } } [Fact] public void SyntaxTreeOrderConstruct() { var tree1 = CreateSyntaxTree("A"); var tree2 = CreateSyntaxTree("B"); SyntaxTree[] treeOrder1 = new[] { tree1, tree2 }; var compilation1 = CSharpCompilation.Create("Compilation1", syntaxTrees: treeOrder1); CheckCompilationSyntaxTrees(compilation1, treeOrder1); SyntaxTree[] treeOrder2 = new[] { tree2, tree1 }; var compilation2 = CSharpCompilation.Create("Compilation2", syntaxTrees: treeOrder2); CheckCompilationSyntaxTrees(compilation2, treeOrder2); } [Fact] public void SyntaxTreeOrderAdd() { var tree1 = CreateSyntaxTree("A"); var tree2 = CreateSyntaxTree("B"); var tree3 = CreateSyntaxTree("C"); var tree4 = CreateSyntaxTree("D"); SyntaxTree[] treeList1 = new[] { tree1, tree2 }; var compilation1 = CSharpCompilation.Create("Compilation1", syntaxTrees: treeList1); CheckCompilationSyntaxTrees(compilation1, treeList1); SyntaxTree[] treeList2 = new[] { tree3, tree4 }; var compilation2 = compilation1.AddSyntaxTrees(treeList2); CheckCompilationSyntaxTrees(compilation1, treeList1); //compilation1 untouched CheckCompilationSyntaxTrees(compilation2, treeList1.Concat(treeList2).ToArray()); SyntaxTree[] treeList3 = new[] { tree4, tree3 }; var compilation3 = CSharpCompilation.Create("Compilation3", syntaxTrees: treeList3); CheckCompilationSyntaxTrees(compilation3, treeList3); SyntaxTree[] treeList4 = new[] { tree2, tree1 }; var compilation4 = compilation3.AddSyntaxTrees(treeList4); CheckCompilationSyntaxTrees(compilation3, treeList3); //compilation3 untouched CheckCompilationSyntaxTrees(compilation4, treeList3.Concat(treeList4).ToArray()); } [Fact] public void SyntaxTreeOrderRemove() { var tree1 = CreateSyntaxTree("A"); var tree2 = CreateSyntaxTree("B"); var tree3 = CreateSyntaxTree("C"); var tree4 = CreateSyntaxTree("D"); SyntaxTree[] treeList1 = new[] { tree1, tree2, tree3, tree4 }; var compilation1 = CSharpCompilation.Create("Compilation1", syntaxTrees: treeList1); CheckCompilationSyntaxTrees(compilation1, treeList1); SyntaxTree[] treeList2 = new[] { tree3, tree1 }; var compilation2 = compilation1.RemoveSyntaxTrees(treeList2); CheckCompilationSyntaxTrees(compilation1, treeList1); //compilation1 untouched CheckCompilationSyntaxTrees(compilation2, tree2, tree4); SyntaxTree[] treeList3 = new[] { tree4, tree3, tree2, tree1 }; var compilation3 = CSharpCompilation.Create("Compilation3", syntaxTrees: treeList3); CheckCompilationSyntaxTrees(compilation3, treeList3); SyntaxTree[] treeList4 = new[] { tree3, tree1 }; var compilation4 = compilation3.RemoveSyntaxTrees(treeList4); CheckCompilationSyntaxTrees(compilation3, treeList3); //compilation3 untouched CheckCompilationSyntaxTrees(compilation4, tree4, tree2); } [Fact] public void SyntaxTreeOrderReplace() { var tree1 = CreateSyntaxTree("A"); var tree2 = CreateSyntaxTree("B"); var tree3 = CreateSyntaxTree("C"); SyntaxTree[] treeList1 = new[] { tree1, tree2 }; var compilation1 = CSharpCompilation.Create("Compilation1", syntaxTrees: treeList1); CheckCompilationSyntaxTrees(compilation1, treeList1); var compilation2 = compilation1.ReplaceSyntaxTree(tree1, tree3); CheckCompilationSyntaxTrees(compilation1, treeList1); //compilation1 untouched CheckCompilationSyntaxTrees(compilation2, tree3, tree2); SyntaxTree[] treeList3 = new[] { tree2, tree1 }; var compilation3 = CSharpCompilation.Create("Compilation3", syntaxTrees: treeList3); CheckCompilationSyntaxTrees(compilation3, treeList3); var compilation4 = compilation3.ReplaceSyntaxTree(tree1, tree3); CheckCompilationSyntaxTrees(compilation3, treeList3); //compilation3 untouched CheckCompilationSyntaxTrees(compilation4, tree2, tree3); } [WorkItem(578706, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578706")] [Fact] public void DeclaringCompilationOfAddedModule() { var source1 = "public class C1 { }"; var source2 = "public class C2 { }"; var lib1 = CreateCompilation(source1, assemblyName: "Lib1", options: TestOptions.ReleaseModule); var ref1 = lib1.EmitToImageReference(); // NOTE: can't use a compilation reference for a module. var lib2 = CreateCompilation(source2, new[] { ref1 }, assemblyName: "Lib2"); lib2.VerifyDiagnostics(); var sourceAssembly = lib2.Assembly; var sourceModule = sourceAssembly.Modules[0]; var sourceType = sourceModule.GlobalNamespace.GetMember<NamedTypeSymbol>("C2"); Assert.IsType<SourceAssemblySymbol>(sourceAssembly); Assert.Equal(lib2, sourceAssembly.DeclaringCompilation); Assert.IsType<SourceModuleSymbol>(sourceModule); Assert.Equal(lib2, sourceModule.DeclaringCompilation); Assert.IsType<SourceNamedTypeSymbol>(sourceType); Assert.Equal(lib2, sourceType.DeclaringCompilation); var addedModule = sourceAssembly.Modules[1]; var addedModuleAssembly = addedModule.ContainingAssembly; var addedModuleType = addedModule.GlobalNamespace.GetMember<NamedTypeSymbol>("C1"); Assert.IsType<SourceAssemblySymbol>(addedModuleAssembly); Assert.Equal(lib2, addedModuleAssembly.DeclaringCompilation); //NB: not lib1, not null Assert.IsType<PEModuleSymbol>(addedModule); Assert.Null(addedModule.DeclaringCompilation); Assert.IsAssignableFrom<PENamedTypeSymbol>(addedModuleType); Assert.Null(addedModuleType.DeclaringCompilation); } } }
-1
dotnet/roslyn
56,419
Fix partial method doc comments
Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
RikkiGibson
"2021-09-15T20:47:39Z"
"2021-09-21T23:49:10Z"
0f60b3e9446f5d0fc14a570998c81a5d6c40cc23
8cda7462843d43d9b72039eede2f4cb43126cac2
Fix partial method doc comments. Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
./src/Compilers/Core/Portable/DiagnosticAnalyzer/DiagnosticStartAnalysisScope.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Concurrent; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using System.Threading; using Microsoft.CodeAnalysis.FlowAnalysis; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.Diagnostics { /// <summary> /// Scope for setting up analyzers for an entire session, automatically associating actions with analyzers. /// </summary> internal sealed class AnalyzerAnalysisContext : AnalysisContext { private readonly DiagnosticAnalyzer _analyzer; private readonly HostSessionStartAnalysisScope _scope; public AnalyzerAnalysisContext(DiagnosticAnalyzer analyzer, HostSessionStartAnalysisScope scope) { _analyzer = analyzer; _scope = scope; } public override void RegisterCompilationStartAction(Action<CompilationStartAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterCompilationStartAction(_analyzer, action); } public override void RegisterCompilationAction(Action<CompilationAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterCompilationAction(_analyzer, action); } public override void RegisterSyntaxTreeAction(Action<SyntaxTreeAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterSyntaxTreeAction(_analyzer, action); } public override void RegisterAdditionalFileAction(Action<AdditionalFileAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterAdditionalFileAction(_analyzer, action); } public override void RegisterSemanticModelAction(Action<SemanticModelAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterSemanticModelAction(_analyzer, action); } public override void RegisterSymbolAction(Action<SymbolAnalysisContext> action, ImmutableArray<SymbolKind> symbolKinds) { DiagnosticAnalysisContextHelpers.VerifyArguments(action, symbolKinds); _scope.RegisterSymbolAction(_analyzer, action, symbolKinds); } public override void RegisterSymbolStartAction(Action<SymbolStartAnalysisContext> action, SymbolKind symbolKind) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterSymbolStartAction(_analyzer, action, symbolKind); } public override void RegisterCodeBlockStartAction<TLanguageKindEnum>(Action<CodeBlockStartAnalysisContext<TLanguageKindEnum>> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterCodeBlockStartAction<TLanguageKindEnum>(_analyzer, action); } public override void RegisterCodeBlockAction(Action<CodeBlockAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterCodeBlockAction(_analyzer, action); } public override void RegisterSyntaxNodeAction<TLanguageKindEnum>(Action<SyntaxNodeAnalysisContext> action, ImmutableArray<TLanguageKindEnum> syntaxKinds) { DiagnosticAnalysisContextHelpers.VerifyArguments(action, syntaxKinds); _scope.RegisterSyntaxNodeAction(_analyzer, action, syntaxKinds); } public override void RegisterOperationAction(Action<OperationAnalysisContext> action, ImmutableArray<OperationKind> operationKinds) { DiagnosticAnalysisContextHelpers.VerifyArguments(action, operationKinds); _scope.RegisterOperationAction(_analyzer, action, operationKinds); } public override void RegisterOperationBlockStartAction(Action<OperationBlockStartAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterOperationBlockStartAction(_analyzer, action); } public override void RegisterOperationBlockAction(Action<OperationBlockAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterOperationBlockAction(_analyzer, action); } public override void EnableConcurrentExecution() { _scope.EnableConcurrentExecution(_analyzer); } public override void ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags mode) { _scope.ConfigureGeneratedCodeAnalysis(_analyzer, mode); } } /// <summary> /// Scope for setting up analyzers for a compilation, automatically associating actions with analyzers. /// </summary> internal sealed class AnalyzerCompilationStartAnalysisContext : CompilationStartAnalysisContext { private readonly DiagnosticAnalyzer _analyzer; private readonly HostCompilationStartAnalysisScope _scope; private readonly CompilationAnalysisValueProviderFactory _compilationAnalysisValueProviderFactory; public AnalyzerCompilationStartAnalysisContext( DiagnosticAnalyzer analyzer, HostCompilationStartAnalysisScope scope, Compilation compilation, AnalyzerOptions options, CompilationAnalysisValueProviderFactory compilationAnalysisValueProviderFactory, CancellationToken cancellationToken) : base(compilation, options, cancellationToken) { _analyzer = analyzer; _scope = scope; _compilationAnalysisValueProviderFactory = compilationAnalysisValueProviderFactory; } public override void RegisterCompilationEndAction(Action<CompilationAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterCompilationEndAction(_analyzer, action); } public override void RegisterSyntaxTreeAction(Action<SyntaxTreeAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterSyntaxTreeAction(_analyzer, action); } public override void RegisterAdditionalFileAction(Action<AdditionalFileAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterAdditionalFileAction(_analyzer, action); } public override void RegisterSemanticModelAction(Action<SemanticModelAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterSemanticModelAction(_analyzer, action); } public override void RegisterSymbolAction(Action<SymbolAnalysisContext> action, ImmutableArray<SymbolKind> symbolKinds) { DiagnosticAnalysisContextHelpers.VerifyArguments(action, symbolKinds); _scope.RegisterSymbolAction(_analyzer, action, symbolKinds); } public override void RegisterSymbolStartAction(Action<SymbolStartAnalysisContext> action, SymbolKind symbolKind) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterSymbolStartAction(_analyzer, action, symbolKind); } public override void RegisterCodeBlockStartAction<TLanguageKindEnum>(Action<CodeBlockStartAnalysisContext<TLanguageKindEnum>> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterCodeBlockStartAction<TLanguageKindEnum>(_analyzer, action); } public override void RegisterCodeBlockAction(Action<CodeBlockAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterCodeBlockAction(_analyzer, action); } public override void RegisterSyntaxNodeAction<TLanguageKindEnum>(Action<SyntaxNodeAnalysisContext> action, ImmutableArray<TLanguageKindEnum> syntaxKinds) { DiagnosticAnalysisContextHelpers.VerifyArguments(action, syntaxKinds); _scope.RegisterSyntaxNodeAction(_analyzer, action, syntaxKinds); } public override void RegisterOperationBlockStartAction(Action<OperationBlockStartAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterOperationBlockStartAction(_analyzer, action); } public override void RegisterOperationBlockAction(Action<OperationBlockAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterOperationBlockAction(_analyzer, action); } public override void RegisterOperationAction(Action<OperationAnalysisContext> action, ImmutableArray<OperationKind> operationKinds) { DiagnosticAnalysisContextHelpers.VerifyArguments(action, operationKinds); _scope.RegisterOperationAction(_analyzer, action, operationKinds); } internal override bool TryGetValueCore<TKey, TValue>(TKey key, AnalysisValueProvider<TKey, TValue> valueProvider, [MaybeNullWhen(false)] out TValue value) { var compilationAnalysisValueProvider = _compilationAnalysisValueProviderFactory.GetValueProvider(valueProvider); return compilationAnalysisValueProvider.TryGetValue(key, out value); } } /// <summary> /// Scope for setting up analyzers for code within a symbol and its members. /// </summary> internal sealed class AnalyzerSymbolStartAnalysisContext : SymbolStartAnalysisContext { private readonly DiagnosticAnalyzer _analyzer; private readonly HostSymbolStartAnalysisScope _scope; internal AnalyzerSymbolStartAnalysisContext(DiagnosticAnalyzer analyzer, HostSymbolStartAnalysisScope scope, ISymbol owningSymbol, Compilation compilation, AnalyzerOptions options, CancellationToken cancellationToken) : base(owningSymbol, compilation, options, cancellationToken) { _analyzer = analyzer; _scope = scope; } public override void RegisterSymbolEndAction(Action<SymbolAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterSymbolEndAction(_analyzer, action); } public override void RegisterCodeBlockStartAction<TLanguageKindEnum>(Action<CodeBlockStartAnalysisContext<TLanguageKindEnum>> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterCodeBlockStartAction<TLanguageKindEnum>(_analyzer, action); } public override void RegisterCodeBlockAction(Action<CodeBlockAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterCodeBlockAction(_analyzer, action); } public override void RegisterSyntaxNodeAction<TLanguageKindEnum>(Action<SyntaxNodeAnalysisContext> action, ImmutableArray<TLanguageKindEnum> syntaxKinds) { DiagnosticAnalysisContextHelpers.VerifyArguments(action, syntaxKinds); _scope.RegisterSyntaxNodeAction(_analyzer, action, syntaxKinds); } public override void RegisterOperationBlockStartAction(Action<OperationBlockStartAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterOperationBlockStartAction(_analyzer, action); } public override void RegisterOperationBlockAction(Action<OperationBlockAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterOperationBlockAction(_analyzer, action); } public override void RegisterOperationAction(Action<OperationAnalysisContext> action, ImmutableArray<OperationKind> operationKinds) { DiagnosticAnalysisContextHelpers.VerifyArguments(action, operationKinds); _scope.RegisterOperationAction(_analyzer, action, operationKinds); } } /// <summary> /// Scope for setting up analyzers for a code block, automatically associating actions with analyzers. /// </summary> internal sealed class AnalyzerCodeBlockStartAnalysisContext<TLanguageKindEnum> : CodeBlockStartAnalysisContext<TLanguageKindEnum> where TLanguageKindEnum : struct { private readonly DiagnosticAnalyzer _analyzer; private readonly HostCodeBlockStartAnalysisScope<TLanguageKindEnum> _scope; internal AnalyzerCodeBlockStartAnalysisContext(DiagnosticAnalyzer analyzer, HostCodeBlockStartAnalysisScope<TLanguageKindEnum> scope, SyntaxNode codeBlock, ISymbol owningSymbol, SemanticModel semanticModel, AnalyzerOptions options, CancellationToken cancellationToken) : base(codeBlock, owningSymbol, semanticModel, options, cancellationToken) { _analyzer = analyzer; _scope = scope; } public override void RegisterCodeBlockEndAction(Action<CodeBlockAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterCodeBlockEndAction(_analyzer, action); } public override void RegisterSyntaxNodeAction(Action<SyntaxNodeAnalysisContext> action, ImmutableArray<TLanguageKindEnum> syntaxKinds) { DiagnosticAnalysisContextHelpers.VerifyArguments(action, syntaxKinds); _scope.RegisterSyntaxNodeAction(_analyzer, action, syntaxKinds); } } /// <summary> /// Scope for setting up analyzers for an operation block, automatically associating actions with analyzers. /// </summary> internal sealed class AnalyzerOperationBlockStartAnalysisContext : OperationBlockStartAnalysisContext { private readonly DiagnosticAnalyzer _analyzer; private readonly HostOperationBlockStartAnalysisScope _scope; internal AnalyzerOperationBlockStartAnalysisContext(DiagnosticAnalyzer analyzer, HostOperationBlockStartAnalysisScope scope, ImmutableArray<IOperation> operationBlocks, ISymbol owningSymbol, Compilation compilation, AnalyzerOptions options, Func<IOperation, ControlFlowGraph> getControlFlowGraph, CancellationToken cancellationToken) : base(operationBlocks, owningSymbol, compilation, options, getControlFlowGraph, cancellationToken) { _analyzer = analyzer; _scope = scope; } public override void RegisterOperationBlockEndAction(Action<OperationBlockAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterOperationBlockEndAction(_analyzer, action); } public override void RegisterOperationAction(Action<OperationAnalysisContext> action, ImmutableArray<OperationKind> operationKinds) { DiagnosticAnalysisContextHelpers.VerifyArguments(action, operationKinds); _scope.RegisterOperationAction(_analyzer, action, operationKinds); } } /// <summary> /// Scope for setting up analyzers for an entire session, capable of retrieving the actions. /// </summary> internal sealed class HostSessionStartAnalysisScope : HostAnalysisScope { private ImmutableHashSet<DiagnosticAnalyzer> _concurrentAnalyzers = ImmutableHashSet<DiagnosticAnalyzer>.Empty; private readonly ConcurrentDictionary<DiagnosticAnalyzer, GeneratedCodeAnalysisFlags> _generatedCodeConfigurationMap = new ConcurrentDictionary<DiagnosticAnalyzer, GeneratedCodeAnalysisFlags>(); public bool IsConcurrentAnalyzer(DiagnosticAnalyzer analyzer) { return _concurrentAnalyzers.Contains(analyzer); } public GeneratedCodeAnalysisFlags GetGeneratedCodeAnalysisFlags(DiagnosticAnalyzer analyzer) { GeneratedCodeAnalysisFlags mode; return _generatedCodeConfigurationMap.TryGetValue(analyzer, out mode) ? mode : AnalyzerDriver.DefaultGeneratedCodeAnalysisFlags; } public void RegisterCompilationStartAction(DiagnosticAnalyzer analyzer, Action<CompilationStartAnalysisContext> action) { CompilationStartAnalyzerAction analyzerAction = new CompilationStartAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddCompilationStartAction(analyzerAction); } public void EnableConcurrentExecution(DiagnosticAnalyzer analyzer) { _concurrentAnalyzers = _concurrentAnalyzers.Add(analyzer); GetOrCreateAnalyzerActions(analyzer).Value.EnableConcurrentExecution(); } public void ConfigureGeneratedCodeAnalysis(DiagnosticAnalyzer analyzer, GeneratedCodeAnalysisFlags mode) { _generatedCodeConfigurationMap.AddOrUpdate(analyzer, addValue: mode, updateValueFactory: (a, c) => mode); } } /// <summary> /// Scope for setting up analyzers for a compilation, capable of retrieving the actions. /// </summary> internal sealed class HostCompilationStartAnalysisScope : HostAnalysisScope { private readonly HostSessionStartAnalysisScope _sessionScope; public HostCompilationStartAnalysisScope(HostSessionStartAnalysisScope sessionScope) { _sessionScope = sessionScope; } public override AnalyzerActions GetAnalyzerActions(DiagnosticAnalyzer analyzer) { AnalyzerActions compilationActions = base.GetAnalyzerActions(analyzer); AnalyzerActions sessionActions = _sessionScope.GetAnalyzerActions(analyzer); if (sessionActions.IsEmpty) { return compilationActions; } if (compilationActions.IsEmpty) { return sessionActions; } return compilationActions.Append(in sessionActions); } } /// <summary> /// Scope for setting up analyzers for analyzing a symbol and its members. /// </summary> internal sealed class HostSymbolStartAnalysisScope : HostAnalysisScope { public HostSymbolStartAnalysisScope() { } } /// <summary> /// Scope for setting up analyzers for a code block, capable of retrieving the actions. /// </summary> internal sealed class HostCodeBlockStartAnalysisScope<TLanguageKindEnum> where TLanguageKindEnum : struct { private ImmutableArray<CodeBlockAnalyzerAction> _codeBlockEndActions = ImmutableArray<CodeBlockAnalyzerAction>.Empty; private ImmutableArray<SyntaxNodeAnalyzerAction<TLanguageKindEnum>> _syntaxNodeActions = ImmutableArray<SyntaxNodeAnalyzerAction<TLanguageKindEnum>>.Empty; public ImmutableArray<CodeBlockAnalyzerAction> CodeBlockEndActions { get { return _codeBlockEndActions; } } public ImmutableArray<SyntaxNodeAnalyzerAction<TLanguageKindEnum>> SyntaxNodeActions { get { return _syntaxNodeActions; } } internal HostCodeBlockStartAnalysisScope() { } public void RegisterCodeBlockEndAction(DiagnosticAnalyzer analyzer, Action<CodeBlockAnalysisContext> action) { _codeBlockEndActions = _codeBlockEndActions.Add(new CodeBlockAnalyzerAction(action, analyzer)); } public void RegisterSyntaxNodeAction(DiagnosticAnalyzer analyzer, Action<SyntaxNodeAnalysisContext> action, ImmutableArray<TLanguageKindEnum> syntaxKinds) { _syntaxNodeActions = _syntaxNodeActions.Add(new SyntaxNodeAnalyzerAction<TLanguageKindEnum>(action, syntaxKinds, analyzer)); } } internal sealed class HostOperationBlockStartAnalysisScope { private ImmutableArray<OperationBlockAnalyzerAction> _operationBlockEndActions = ImmutableArray<OperationBlockAnalyzerAction>.Empty; private ImmutableArray<OperationAnalyzerAction> _operationActions = ImmutableArray<OperationAnalyzerAction>.Empty; public ImmutableArray<OperationBlockAnalyzerAction> OperationBlockEndActions => _operationBlockEndActions; public ImmutableArray<OperationAnalyzerAction> OperationActions => _operationActions; internal HostOperationBlockStartAnalysisScope() { } public void RegisterOperationBlockEndAction(DiagnosticAnalyzer analyzer, Action<OperationBlockAnalysisContext> action) { _operationBlockEndActions = _operationBlockEndActions.Add(new OperationBlockAnalyzerAction(action, analyzer)); } public void RegisterOperationAction(DiagnosticAnalyzer analyzer, Action<OperationAnalysisContext> action, ImmutableArray<OperationKind> operationKinds) { _operationActions = _operationActions.Add(new OperationAnalyzerAction(action, operationKinds, analyzer)); } } internal abstract class HostAnalysisScope { private readonly ConcurrentDictionary<DiagnosticAnalyzer, StrongBox<AnalyzerActions>> _analyzerActions = new ConcurrentDictionary<DiagnosticAnalyzer, StrongBox<AnalyzerActions>>(); public virtual AnalyzerActions GetAnalyzerActions(DiagnosticAnalyzer analyzer) { return this.GetOrCreateAnalyzerActions(analyzer).Value; } public void RegisterCompilationAction(DiagnosticAnalyzer analyzer, Action<CompilationAnalysisContext> action) { CompilationAnalyzerAction analyzerAction = new CompilationAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddCompilationAction(analyzerAction); } public void RegisterCompilationEndAction(DiagnosticAnalyzer analyzer, Action<CompilationAnalysisContext> action) { CompilationAnalyzerAction analyzerAction = new CompilationAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddCompilationEndAction(analyzerAction); } public void RegisterSemanticModelAction(DiagnosticAnalyzer analyzer, Action<SemanticModelAnalysisContext> action) { SemanticModelAnalyzerAction analyzerAction = new SemanticModelAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddSemanticModelAction(analyzerAction); } public void RegisterSyntaxTreeAction(DiagnosticAnalyzer analyzer, Action<SyntaxTreeAnalysisContext> action) { SyntaxTreeAnalyzerAction analyzerAction = new SyntaxTreeAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddSyntaxTreeAction(analyzerAction); } public void RegisterAdditionalFileAction(DiagnosticAnalyzer analyzer, Action<AdditionalFileAnalysisContext> action) { var analyzerAction = new AdditionalFileAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddAdditionalFileAction(analyzerAction); } public void RegisterSymbolAction(DiagnosticAnalyzer analyzer, Action<SymbolAnalysisContext> action, ImmutableArray<SymbolKind> symbolKinds) { SymbolAnalyzerAction analyzerAction = new SymbolAnalyzerAction(action, symbolKinds, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddSymbolAction(analyzerAction); // The SymbolAnalyzerAction does not handle SymbolKind.Parameter because the compiler // does not make CompilationEvents for them. As a workaround, handle them specially by // registering further SymbolActions (for Methods) and utilize the results to construct // the necessary SymbolAnalysisContexts. if (symbolKinds.Contains(SymbolKind.Parameter)) { RegisterSymbolAction( analyzer, context => { ImmutableArray<IParameterSymbol> parameters; switch (context.Symbol.Kind) { case SymbolKind.Method: parameters = ((IMethodSymbol)context.Symbol).Parameters; break; case SymbolKind.Property: parameters = ((IPropertySymbol)context.Symbol).Parameters; break; case SymbolKind.NamedType: var namedType = (INamedTypeSymbol)context.Symbol; var delegateInvokeMethod = namedType.DelegateInvokeMethod; parameters = delegateInvokeMethod?.Parameters ?? ImmutableArray.Create<IParameterSymbol>(); break; default: throw new ArgumentException($"{context.Symbol.Kind} is not supported.", nameof(context)); } foreach (var parameter in parameters) { if (!parameter.IsImplicitlyDeclared) { action(new SymbolAnalysisContext( parameter, context.Compilation, context.Options, context.ReportDiagnostic, context.IsSupportedDiagnostic, context.CancellationToken)); } } }, ImmutableArray.Create(SymbolKind.Method, SymbolKind.Property, SymbolKind.NamedType)); } } public void RegisterSymbolStartAction(DiagnosticAnalyzer analyzer, Action<SymbolStartAnalysisContext> action, SymbolKind symbolKind) { var analyzerAction = new SymbolStartAnalyzerAction(action, symbolKind, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddSymbolStartAction(analyzerAction); } public void RegisterSymbolEndAction(DiagnosticAnalyzer analyzer, Action<SymbolAnalysisContext> action) { var analyzerAction = new SymbolEndAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddSymbolEndAction(analyzerAction); } public void RegisterCodeBlockStartAction<TLanguageKindEnum>(DiagnosticAnalyzer analyzer, Action<CodeBlockStartAnalysisContext<TLanguageKindEnum>> action) where TLanguageKindEnum : struct { CodeBlockStartAnalyzerAction<TLanguageKindEnum> analyzerAction = new CodeBlockStartAnalyzerAction<TLanguageKindEnum>(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddCodeBlockStartAction(analyzerAction); } public void RegisterCodeBlockEndAction(DiagnosticAnalyzer analyzer, Action<CodeBlockAnalysisContext> action) { CodeBlockAnalyzerAction analyzerAction = new CodeBlockAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddCodeBlockEndAction(analyzerAction); } public void RegisterCodeBlockAction(DiagnosticAnalyzer analyzer, Action<CodeBlockAnalysisContext> action) { CodeBlockAnalyzerAction analyzerAction = new CodeBlockAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddCodeBlockAction(analyzerAction); } public void RegisterSyntaxNodeAction<TLanguageKindEnum>(DiagnosticAnalyzer analyzer, Action<SyntaxNodeAnalysisContext> action, ImmutableArray<TLanguageKindEnum> syntaxKinds) where TLanguageKindEnum : struct { SyntaxNodeAnalyzerAction<TLanguageKindEnum> analyzerAction = new SyntaxNodeAnalyzerAction<TLanguageKindEnum>(action, syntaxKinds, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddSyntaxNodeAction(analyzerAction); } public void RegisterOperationBlockStartAction(DiagnosticAnalyzer analyzer, Action<OperationBlockStartAnalysisContext> action) { OperationBlockStartAnalyzerAction analyzerAction = new OperationBlockStartAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddOperationBlockStartAction(analyzerAction); } public void RegisterOperationBlockEndAction(DiagnosticAnalyzer analyzer, Action<OperationBlockAnalysisContext> action) { OperationBlockAnalyzerAction analyzerAction = new OperationBlockAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddOperationBlockEndAction(analyzerAction); } public void RegisterOperationBlockAction(DiagnosticAnalyzer analyzer, Action<OperationBlockAnalysisContext> action) { OperationBlockAnalyzerAction analyzerAction = new OperationBlockAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddOperationBlockAction(analyzerAction); } public void RegisterOperationAction(DiagnosticAnalyzer analyzer, Action<OperationAnalysisContext> action, ImmutableArray<OperationKind> operationKinds) { OperationAnalyzerAction analyzerAction = new OperationAnalyzerAction(action, operationKinds, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddOperationAction(analyzerAction); } protected StrongBox<AnalyzerActions> GetOrCreateAnalyzerActions(DiagnosticAnalyzer analyzer) { return _analyzerActions.GetOrAdd(analyzer, _ => new StrongBox<AnalyzerActions>(AnalyzerActions.Empty)); } } /// <summary> /// Actions registered by a particular analyzer. /// </summary> // ToDo: AnalyzerActions, and all of the mechanism around it, can be eliminated if the IDE diagnostic analyzer driver // moves from an analyzer-centric model to an action-centric model. For example, the driver would need to stop asking // if a particular analyzer can analyze syntax trees, and instead ask if any syntax tree actions are present. Also, // the driver needs to apply all relevant actions rather then applying the actions of individual analyzers. internal struct AnalyzerActions { public static readonly AnalyzerActions Empty = new AnalyzerActions(concurrent: false); private ImmutableArray<CompilationStartAnalyzerAction> _compilationStartActions; private ImmutableArray<CompilationAnalyzerAction> _compilationEndActions; private ImmutableArray<CompilationAnalyzerAction> _compilationActions; private ImmutableArray<SyntaxTreeAnalyzerAction> _syntaxTreeActions; private ImmutableArray<AdditionalFileAnalyzerAction> _additionalFileActions; private ImmutableArray<SemanticModelAnalyzerAction> _semanticModelActions; private ImmutableArray<SymbolAnalyzerAction> _symbolActions; private ImmutableArray<SymbolStartAnalyzerAction> _symbolStartActions; private ImmutableArray<SymbolEndAnalyzerAction> _symbolEndActions; private ImmutableArray<AnalyzerAction> _codeBlockStartActions; private ImmutableArray<CodeBlockAnalyzerAction> _codeBlockEndActions; private ImmutableArray<CodeBlockAnalyzerAction> _codeBlockActions; private ImmutableArray<OperationBlockStartAnalyzerAction> _operationBlockStartActions; private ImmutableArray<OperationBlockAnalyzerAction> _operationBlockEndActions; private ImmutableArray<OperationBlockAnalyzerAction> _operationBlockActions; private ImmutableArray<AnalyzerAction> _syntaxNodeActions; private ImmutableArray<OperationAnalyzerAction> _operationActions; private bool _concurrent; internal AnalyzerActions(bool concurrent) { _compilationStartActions = ImmutableArray<CompilationStartAnalyzerAction>.Empty; _compilationEndActions = ImmutableArray<CompilationAnalyzerAction>.Empty; _compilationActions = ImmutableArray<CompilationAnalyzerAction>.Empty; _syntaxTreeActions = ImmutableArray<SyntaxTreeAnalyzerAction>.Empty; _additionalFileActions = ImmutableArray<AdditionalFileAnalyzerAction>.Empty; _semanticModelActions = ImmutableArray<SemanticModelAnalyzerAction>.Empty; _symbolActions = ImmutableArray<SymbolAnalyzerAction>.Empty; _symbolStartActions = ImmutableArray<SymbolStartAnalyzerAction>.Empty; _symbolEndActions = ImmutableArray<SymbolEndAnalyzerAction>.Empty; _codeBlockStartActions = ImmutableArray<AnalyzerAction>.Empty; _codeBlockEndActions = ImmutableArray<CodeBlockAnalyzerAction>.Empty; _codeBlockActions = ImmutableArray<CodeBlockAnalyzerAction>.Empty; _operationBlockStartActions = ImmutableArray<OperationBlockStartAnalyzerAction>.Empty; _operationBlockEndActions = ImmutableArray<OperationBlockAnalyzerAction>.Empty; _operationBlockActions = ImmutableArray<OperationBlockAnalyzerAction>.Empty; _syntaxNodeActions = ImmutableArray<AnalyzerAction>.Empty; _operationActions = ImmutableArray<OperationAnalyzerAction>.Empty; _concurrent = concurrent; IsEmpty = true; } public AnalyzerActions( ImmutableArray<CompilationStartAnalyzerAction> compilationStartActions, ImmutableArray<CompilationAnalyzerAction> compilationEndActions, ImmutableArray<CompilationAnalyzerAction> compilationActions, ImmutableArray<SyntaxTreeAnalyzerAction> syntaxTreeActions, ImmutableArray<AdditionalFileAnalyzerAction> additionalFileActions, ImmutableArray<SemanticModelAnalyzerAction> semanticModelActions, ImmutableArray<SymbolAnalyzerAction> symbolActions, ImmutableArray<SymbolStartAnalyzerAction> symbolStartActions, ImmutableArray<SymbolEndAnalyzerAction> symbolEndActions, ImmutableArray<AnalyzerAction> codeBlockStartActions, ImmutableArray<CodeBlockAnalyzerAction> codeBlockEndActions, ImmutableArray<CodeBlockAnalyzerAction> codeBlockActions, ImmutableArray<OperationBlockStartAnalyzerAction> operationBlockStartActions, ImmutableArray<OperationBlockAnalyzerAction> operationBlockEndActions, ImmutableArray<OperationBlockAnalyzerAction> operationBlockActions, ImmutableArray<AnalyzerAction> syntaxNodeActions, ImmutableArray<OperationAnalyzerAction> operationActions, bool concurrent, bool isEmpty) { _compilationStartActions = compilationStartActions; _compilationEndActions = compilationEndActions; _compilationActions = compilationActions; _syntaxTreeActions = syntaxTreeActions; _additionalFileActions = additionalFileActions; _semanticModelActions = semanticModelActions; _symbolActions = symbolActions; _symbolStartActions = symbolStartActions; _symbolEndActions = symbolEndActions; _codeBlockStartActions = codeBlockStartActions; _codeBlockEndActions = codeBlockEndActions; _codeBlockActions = codeBlockActions; _operationBlockStartActions = operationBlockStartActions; _operationBlockEndActions = operationBlockEndActions; _operationBlockActions = operationBlockActions; _syntaxNodeActions = syntaxNodeActions; _operationActions = operationActions; _concurrent = concurrent; IsEmpty = isEmpty; } public readonly int CompilationStartActionsCount { get { return _compilationStartActions.Length; } } public readonly int CompilationEndActionsCount { get { return _compilationEndActions.Length; } } public readonly int CompilationActionsCount { get { return _compilationActions.Length; } } public readonly int SyntaxTreeActionsCount { get { return _syntaxTreeActions.Length; } } public readonly int AdditionalFileActionsCount { get { return _additionalFileActions.Length; } } public readonly int SemanticModelActionsCount { get { return _semanticModelActions.Length; } } public readonly int SymbolActionsCount { get { return _symbolActions.Length; } } public readonly int SymbolStartActionsCount { get { return _symbolStartActions.Length; } } public readonly int SymbolEndActionsCount { get { return _symbolEndActions.Length; } } public readonly int SyntaxNodeActionsCount { get { return _syntaxNodeActions.Length; } } public readonly int OperationActionsCount { get { return _operationActions.Length; } } public readonly int OperationBlockStartActionsCount { get { return _operationBlockStartActions.Length; } } public readonly int OperationBlockEndActionsCount { get { return _operationBlockEndActions.Length; } } public readonly int OperationBlockActionsCount { get { return _operationBlockActions.Length; } } public readonly int CodeBlockStartActionsCount { get { return _codeBlockStartActions.Length; } } public readonly int CodeBlockEndActionsCount { get { return _codeBlockEndActions.Length; } } public readonly int CodeBlockActionsCount { get { return _codeBlockActions.Length; } } public readonly bool Concurrent => _concurrent; public bool IsEmpty { readonly get; private set; } public readonly bool IsDefault => _compilationStartActions.IsDefault; internal readonly ImmutableArray<CompilationStartAnalyzerAction> CompilationStartActions { get { return _compilationStartActions; } } internal readonly ImmutableArray<CompilationAnalyzerAction> CompilationEndActions { get { return _compilationEndActions; } } internal readonly ImmutableArray<CompilationAnalyzerAction> CompilationActions { get { return _compilationActions; } } internal readonly ImmutableArray<SyntaxTreeAnalyzerAction> SyntaxTreeActions { get { return _syntaxTreeActions; } } internal readonly ImmutableArray<AdditionalFileAnalyzerAction> AdditionalFileActions { get { return _additionalFileActions; } } internal readonly ImmutableArray<SemanticModelAnalyzerAction> SemanticModelActions { get { return _semanticModelActions; } } internal readonly ImmutableArray<SymbolAnalyzerAction> SymbolActions { get { return _symbolActions; } } internal readonly ImmutableArray<SymbolStartAnalyzerAction> SymbolStartActions { get { return _symbolStartActions; } } internal readonly ImmutableArray<SymbolEndAnalyzerAction> SymbolEndActions { get { return _symbolEndActions; } } internal readonly ImmutableArray<CodeBlockAnalyzerAction> CodeBlockEndActions { get { return _codeBlockEndActions; } } internal readonly ImmutableArray<CodeBlockAnalyzerAction> CodeBlockActions { get { return _codeBlockActions; } } internal readonly ImmutableArray<CodeBlockStartAnalyzerAction<TLanguageKindEnum>> GetCodeBlockStartActions<TLanguageKindEnum>() where TLanguageKindEnum : struct { return _codeBlockStartActions.OfType<CodeBlockStartAnalyzerAction<TLanguageKindEnum>>().ToImmutableArray(); } internal readonly ImmutableArray<SyntaxNodeAnalyzerAction<TLanguageKindEnum>> GetSyntaxNodeActions<TLanguageKindEnum>() where TLanguageKindEnum : struct { return _syntaxNodeActions.OfType<SyntaxNodeAnalyzerAction<TLanguageKindEnum>>().ToImmutableArray(); } internal readonly ImmutableArray<SyntaxNodeAnalyzerAction<TLanguageKindEnum>> GetSyntaxNodeActions<TLanguageKindEnum>(DiagnosticAnalyzer analyzer) where TLanguageKindEnum : struct { var builder = ArrayBuilder<SyntaxNodeAnalyzerAction<TLanguageKindEnum>>.GetInstance(); foreach (var action in _syntaxNodeActions) { if (action.Analyzer == analyzer && action is SyntaxNodeAnalyzerAction<TLanguageKindEnum> syntaxNodeAction) { builder.Add(syntaxNodeAction); } } return builder.ToImmutableAndFree(); } internal readonly ImmutableArray<OperationBlockAnalyzerAction> OperationBlockActions { get { return _operationBlockActions; } } internal readonly ImmutableArray<OperationBlockAnalyzerAction> OperationBlockEndActions { get { return _operationBlockEndActions; } } internal readonly ImmutableArray<OperationBlockStartAnalyzerAction> OperationBlockStartActions { get { return _operationBlockStartActions; } } internal readonly ImmutableArray<OperationAnalyzerAction> OperationActions { get { return _operationActions; } } internal void AddCompilationStartAction(CompilationStartAnalyzerAction action) { _compilationStartActions = _compilationStartActions.Add(action); IsEmpty = false; } internal void AddCompilationEndAction(CompilationAnalyzerAction action) { _compilationEndActions = _compilationEndActions.Add(action); IsEmpty = false; } internal void AddCompilationAction(CompilationAnalyzerAction action) { _compilationActions = _compilationActions.Add(action); IsEmpty = false; } internal void AddSyntaxTreeAction(SyntaxTreeAnalyzerAction action) { _syntaxTreeActions = _syntaxTreeActions.Add(action); IsEmpty = false; } internal void AddAdditionalFileAction(AdditionalFileAnalyzerAction action) { _additionalFileActions = _additionalFileActions.Add(action); IsEmpty = false; } internal void AddSemanticModelAction(SemanticModelAnalyzerAction action) { _semanticModelActions = _semanticModelActions.Add(action); IsEmpty = false; } internal void AddSymbolAction(SymbolAnalyzerAction action) { _symbolActions = _symbolActions.Add(action); IsEmpty = false; } internal void AddSymbolStartAction(SymbolStartAnalyzerAction action) { _symbolStartActions = _symbolStartActions.Add(action); IsEmpty = false; } internal void AddSymbolEndAction(SymbolEndAnalyzerAction action) { _symbolEndActions = _symbolEndActions.Add(action); IsEmpty = false; } internal void AddCodeBlockStartAction<TLanguageKindEnum>(CodeBlockStartAnalyzerAction<TLanguageKindEnum> action) where TLanguageKindEnum : struct { _codeBlockStartActions = _codeBlockStartActions.Add(action); IsEmpty = false; } internal void AddCodeBlockEndAction(CodeBlockAnalyzerAction action) { _codeBlockEndActions = _codeBlockEndActions.Add(action); IsEmpty = false; } internal void AddCodeBlockAction(CodeBlockAnalyzerAction action) { _codeBlockActions = _codeBlockActions.Add(action); IsEmpty = false; } internal void AddSyntaxNodeAction<TLanguageKindEnum>(SyntaxNodeAnalyzerAction<TLanguageKindEnum> action) where TLanguageKindEnum : struct { _syntaxNodeActions = _syntaxNodeActions.Add(action); IsEmpty = false; } internal void AddOperationBlockStartAction(OperationBlockStartAnalyzerAction action) { _operationBlockStartActions = _operationBlockStartActions.Add(action); IsEmpty = false; } internal void AddOperationBlockAction(OperationBlockAnalyzerAction action) { _operationBlockActions = _operationBlockActions.Add(action); IsEmpty = false; } internal void AddOperationBlockEndAction(OperationBlockAnalyzerAction action) { _operationBlockEndActions = _operationBlockEndActions.Add(action); IsEmpty = false; } internal void AddOperationAction(OperationAnalyzerAction action) { _operationActions = _operationActions.Add(action); IsEmpty = false; } internal void EnableConcurrentExecution() { _concurrent = true; } /// <summary> /// Append analyzer actions from <paramref name="otherActions"/> to actions from this instance. /// </summary> /// <param name="otherActions">Analyzer actions to append</param>. public readonly AnalyzerActions Append(in AnalyzerActions otherActions, bool appendSymbolStartAndSymbolEndActions = true) { if (otherActions.IsDefault) { throw new ArgumentNullException(nameof(otherActions)); } AnalyzerActions actions = new AnalyzerActions(concurrent: _concurrent || otherActions.Concurrent); actions._compilationStartActions = _compilationStartActions.AddRange(otherActions._compilationStartActions); actions._compilationEndActions = _compilationEndActions.AddRange(otherActions._compilationEndActions); actions._compilationActions = _compilationActions.AddRange(otherActions._compilationActions); actions._syntaxTreeActions = _syntaxTreeActions.AddRange(otherActions._syntaxTreeActions); actions._additionalFileActions = _additionalFileActions.AddRange(otherActions._additionalFileActions); actions._semanticModelActions = _semanticModelActions.AddRange(otherActions._semanticModelActions); actions._symbolActions = _symbolActions.AddRange(otherActions._symbolActions); actions._symbolStartActions = appendSymbolStartAndSymbolEndActions ? _symbolStartActions.AddRange(otherActions._symbolStartActions) : _symbolStartActions; actions._symbolEndActions = appendSymbolStartAndSymbolEndActions ? _symbolEndActions.AddRange(otherActions._symbolEndActions) : _symbolEndActions; actions._codeBlockStartActions = _codeBlockStartActions.AddRange(otherActions._codeBlockStartActions); actions._codeBlockEndActions = _codeBlockEndActions.AddRange(otherActions._codeBlockEndActions); actions._codeBlockActions = _codeBlockActions.AddRange(otherActions._codeBlockActions); actions._syntaxNodeActions = _syntaxNodeActions.AddRange(otherActions._syntaxNodeActions); actions._operationActions = _operationActions.AddRange(otherActions._operationActions); actions._operationBlockStartActions = _operationBlockStartActions.AddRange(otherActions._operationBlockStartActions); actions._operationBlockEndActions = _operationBlockEndActions.AddRange(otherActions._operationBlockEndActions); actions._operationBlockActions = _operationBlockActions.AddRange(otherActions._operationBlockActions); actions.IsEmpty = IsEmpty && otherActions.IsEmpty; return actions; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Concurrent; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using System.Threading; using Microsoft.CodeAnalysis.FlowAnalysis; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.Diagnostics { /// <summary> /// Scope for setting up analyzers for an entire session, automatically associating actions with analyzers. /// </summary> internal sealed class AnalyzerAnalysisContext : AnalysisContext { private readonly DiagnosticAnalyzer _analyzer; private readonly HostSessionStartAnalysisScope _scope; public AnalyzerAnalysisContext(DiagnosticAnalyzer analyzer, HostSessionStartAnalysisScope scope) { _analyzer = analyzer; _scope = scope; } public override void RegisterCompilationStartAction(Action<CompilationStartAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterCompilationStartAction(_analyzer, action); } public override void RegisterCompilationAction(Action<CompilationAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterCompilationAction(_analyzer, action); } public override void RegisterSyntaxTreeAction(Action<SyntaxTreeAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterSyntaxTreeAction(_analyzer, action); } public override void RegisterAdditionalFileAction(Action<AdditionalFileAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterAdditionalFileAction(_analyzer, action); } public override void RegisterSemanticModelAction(Action<SemanticModelAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterSemanticModelAction(_analyzer, action); } public override void RegisterSymbolAction(Action<SymbolAnalysisContext> action, ImmutableArray<SymbolKind> symbolKinds) { DiagnosticAnalysisContextHelpers.VerifyArguments(action, symbolKinds); _scope.RegisterSymbolAction(_analyzer, action, symbolKinds); } public override void RegisterSymbolStartAction(Action<SymbolStartAnalysisContext> action, SymbolKind symbolKind) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterSymbolStartAction(_analyzer, action, symbolKind); } public override void RegisterCodeBlockStartAction<TLanguageKindEnum>(Action<CodeBlockStartAnalysisContext<TLanguageKindEnum>> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterCodeBlockStartAction<TLanguageKindEnum>(_analyzer, action); } public override void RegisterCodeBlockAction(Action<CodeBlockAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterCodeBlockAction(_analyzer, action); } public override void RegisterSyntaxNodeAction<TLanguageKindEnum>(Action<SyntaxNodeAnalysisContext> action, ImmutableArray<TLanguageKindEnum> syntaxKinds) { DiagnosticAnalysisContextHelpers.VerifyArguments(action, syntaxKinds); _scope.RegisterSyntaxNodeAction(_analyzer, action, syntaxKinds); } public override void RegisterOperationAction(Action<OperationAnalysisContext> action, ImmutableArray<OperationKind> operationKinds) { DiagnosticAnalysisContextHelpers.VerifyArguments(action, operationKinds); _scope.RegisterOperationAction(_analyzer, action, operationKinds); } public override void RegisterOperationBlockStartAction(Action<OperationBlockStartAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterOperationBlockStartAction(_analyzer, action); } public override void RegisterOperationBlockAction(Action<OperationBlockAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterOperationBlockAction(_analyzer, action); } public override void EnableConcurrentExecution() { _scope.EnableConcurrentExecution(_analyzer); } public override void ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags mode) { _scope.ConfigureGeneratedCodeAnalysis(_analyzer, mode); } } /// <summary> /// Scope for setting up analyzers for a compilation, automatically associating actions with analyzers. /// </summary> internal sealed class AnalyzerCompilationStartAnalysisContext : CompilationStartAnalysisContext { private readonly DiagnosticAnalyzer _analyzer; private readonly HostCompilationStartAnalysisScope _scope; private readonly CompilationAnalysisValueProviderFactory _compilationAnalysisValueProviderFactory; public AnalyzerCompilationStartAnalysisContext( DiagnosticAnalyzer analyzer, HostCompilationStartAnalysisScope scope, Compilation compilation, AnalyzerOptions options, CompilationAnalysisValueProviderFactory compilationAnalysisValueProviderFactory, CancellationToken cancellationToken) : base(compilation, options, cancellationToken) { _analyzer = analyzer; _scope = scope; _compilationAnalysisValueProviderFactory = compilationAnalysisValueProviderFactory; } public override void RegisterCompilationEndAction(Action<CompilationAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterCompilationEndAction(_analyzer, action); } public override void RegisterSyntaxTreeAction(Action<SyntaxTreeAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterSyntaxTreeAction(_analyzer, action); } public override void RegisterAdditionalFileAction(Action<AdditionalFileAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterAdditionalFileAction(_analyzer, action); } public override void RegisterSemanticModelAction(Action<SemanticModelAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterSemanticModelAction(_analyzer, action); } public override void RegisterSymbolAction(Action<SymbolAnalysisContext> action, ImmutableArray<SymbolKind> symbolKinds) { DiagnosticAnalysisContextHelpers.VerifyArguments(action, symbolKinds); _scope.RegisterSymbolAction(_analyzer, action, symbolKinds); } public override void RegisterSymbolStartAction(Action<SymbolStartAnalysisContext> action, SymbolKind symbolKind) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterSymbolStartAction(_analyzer, action, symbolKind); } public override void RegisterCodeBlockStartAction<TLanguageKindEnum>(Action<CodeBlockStartAnalysisContext<TLanguageKindEnum>> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterCodeBlockStartAction<TLanguageKindEnum>(_analyzer, action); } public override void RegisterCodeBlockAction(Action<CodeBlockAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterCodeBlockAction(_analyzer, action); } public override void RegisterSyntaxNodeAction<TLanguageKindEnum>(Action<SyntaxNodeAnalysisContext> action, ImmutableArray<TLanguageKindEnum> syntaxKinds) { DiagnosticAnalysisContextHelpers.VerifyArguments(action, syntaxKinds); _scope.RegisterSyntaxNodeAction(_analyzer, action, syntaxKinds); } public override void RegisterOperationBlockStartAction(Action<OperationBlockStartAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterOperationBlockStartAction(_analyzer, action); } public override void RegisterOperationBlockAction(Action<OperationBlockAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterOperationBlockAction(_analyzer, action); } public override void RegisterOperationAction(Action<OperationAnalysisContext> action, ImmutableArray<OperationKind> operationKinds) { DiagnosticAnalysisContextHelpers.VerifyArguments(action, operationKinds); _scope.RegisterOperationAction(_analyzer, action, operationKinds); } internal override bool TryGetValueCore<TKey, TValue>(TKey key, AnalysisValueProvider<TKey, TValue> valueProvider, [MaybeNullWhen(false)] out TValue value) { var compilationAnalysisValueProvider = _compilationAnalysisValueProviderFactory.GetValueProvider(valueProvider); return compilationAnalysisValueProvider.TryGetValue(key, out value); } } /// <summary> /// Scope for setting up analyzers for code within a symbol and its members. /// </summary> internal sealed class AnalyzerSymbolStartAnalysisContext : SymbolStartAnalysisContext { private readonly DiagnosticAnalyzer _analyzer; private readonly HostSymbolStartAnalysisScope _scope; internal AnalyzerSymbolStartAnalysisContext(DiagnosticAnalyzer analyzer, HostSymbolStartAnalysisScope scope, ISymbol owningSymbol, Compilation compilation, AnalyzerOptions options, CancellationToken cancellationToken) : base(owningSymbol, compilation, options, cancellationToken) { _analyzer = analyzer; _scope = scope; } public override void RegisterSymbolEndAction(Action<SymbolAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterSymbolEndAction(_analyzer, action); } public override void RegisterCodeBlockStartAction<TLanguageKindEnum>(Action<CodeBlockStartAnalysisContext<TLanguageKindEnum>> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterCodeBlockStartAction<TLanguageKindEnum>(_analyzer, action); } public override void RegisterCodeBlockAction(Action<CodeBlockAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterCodeBlockAction(_analyzer, action); } public override void RegisterSyntaxNodeAction<TLanguageKindEnum>(Action<SyntaxNodeAnalysisContext> action, ImmutableArray<TLanguageKindEnum> syntaxKinds) { DiagnosticAnalysisContextHelpers.VerifyArguments(action, syntaxKinds); _scope.RegisterSyntaxNodeAction(_analyzer, action, syntaxKinds); } public override void RegisterOperationBlockStartAction(Action<OperationBlockStartAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterOperationBlockStartAction(_analyzer, action); } public override void RegisterOperationBlockAction(Action<OperationBlockAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterOperationBlockAction(_analyzer, action); } public override void RegisterOperationAction(Action<OperationAnalysisContext> action, ImmutableArray<OperationKind> operationKinds) { DiagnosticAnalysisContextHelpers.VerifyArguments(action, operationKinds); _scope.RegisterOperationAction(_analyzer, action, operationKinds); } } /// <summary> /// Scope for setting up analyzers for a code block, automatically associating actions with analyzers. /// </summary> internal sealed class AnalyzerCodeBlockStartAnalysisContext<TLanguageKindEnum> : CodeBlockStartAnalysisContext<TLanguageKindEnum> where TLanguageKindEnum : struct { private readonly DiagnosticAnalyzer _analyzer; private readonly HostCodeBlockStartAnalysisScope<TLanguageKindEnum> _scope; internal AnalyzerCodeBlockStartAnalysisContext(DiagnosticAnalyzer analyzer, HostCodeBlockStartAnalysisScope<TLanguageKindEnum> scope, SyntaxNode codeBlock, ISymbol owningSymbol, SemanticModel semanticModel, AnalyzerOptions options, CancellationToken cancellationToken) : base(codeBlock, owningSymbol, semanticModel, options, cancellationToken) { _analyzer = analyzer; _scope = scope; } public override void RegisterCodeBlockEndAction(Action<CodeBlockAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterCodeBlockEndAction(_analyzer, action); } public override void RegisterSyntaxNodeAction(Action<SyntaxNodeAnalysisContext> action, ImmutableArray<TLanguageKindEnum> syntaxKinds) { DiagnosticAnalysisContextHelpers.VerifyArguments(action, syntaxKinds); _scope.RegisterSyntaxNodeAction(_analyzer, action, syntaxKinds); } } /// <summary> /// Scope for setting up analyzers for an operation block, automatically associating actions with analyzers. /// </summary> internal sealed class AnalyzerOperationBlockStartAnalysisContext : OperationBlockStartAnalysisContext { private readonly DiagnosticAnalyzer _analyzer; private readonly HostOperationBlockStartAnalysisScope _scope; internal AnalyzerOperationBlockStartAnalysisContext(DiagnosticAnalyzer analyzer, HostOperationBlockStartAnalysisScope scope, ImmutableArray<IOperation> operationBlocks, ISymbol owningSymbol, Compilation compilation, AnalyzerOptions options, Func<IOperation, ControlFlowGraph> getControlFlowGraph, CancellationToken cancellationToken) : base(operationBlocks, owningSymbol, compilation, options, getControlFlowGraph, cancellationToken) { _analyzer = analyzer; _scope = scope; } public override void RegisterOperationBlockEndAction(Action<OperationBlockAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterOperationBlockEndAction(_analyzer, action); } public override void RegisterOperationAction(Action<OperationAnalysisContext> action, ImmutableArray<OperationKind> operationKinds) { DiagnosticAnalysisContextHelpers.VerifyArguments(action, operationKinds); _scope.RegisterOperationAction(_analyzer, action, operationKinds); } } /// <summary> /// Scope for setting up analyzers for an entire session, capable of retrieving the actions. /// </summary> internal sealed class HostSessionStartAnalysisScope : HostAnalysisScope { private ImmutableHashSet<DiagnosticAnalyzer> _concurrentAnalyzers = ImmutableHashSet<DiagnosticAnalyzer>.Empty; private readonly ConcurrentDictionary<DiagnosticAnalyzer, GeneratedCodeAnalysisFlags> _generatedCodeConfigurationMap = new ConcurrentDictionary<DiagnosticAnalyzer, GeneratedCodeAnalysisFlags>(); public bool IsConcurrentAnalyzer(DiagnosticAnalyzer analyzer) { return _concurrentAnalyzers.Contains(analyzer); } public GeneratedCodeAnalysisFlags GetGeneratedCodeAnalysisFlags(DiagnosticAnalyzer analyzer) { GeneratedCodeAnalysisFlags mode; return _generatedCodeConfigurationMap.TryGetValue(analyzer, out mode) ? mode : AnalyzerDriver.DefaultGeneratedCodeAnalysisFlags; } public void RegisterCompilationStartAction(DiagnosticAnalyzer analyzer, Action<CompilationStartAnalysisContext> action) { CompilationStartAnalyzerAction analyzerAction = new CompilationStartAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddCompilationStartAction(analyzerAction); } public void EnableConcurrentExecution(DiagnosticAnalyzer analyzer) { _concurrentAnalyzers = _concurrentAnalyzers.Add(analyzer); GetOrCreateAnalyzerActions(analyzer).Value.EnableConcurrentExecution(); } public void ConfigureGeneratedCodeAnalysis(DiagnosticAnalyzer analyzer, GeneratedCodeAnalysisFlags mode) { _generatedCodeConfigurationMap.AddOrUpdate(analyzer, addValue: mode, updateValueFactory: (a, c) => mode); } } /// <summary> /// Scope for setting up analyzers for a compilation, capable of retrieving the actions. /// </summary> internal sealed class HostCompilationStartAnalysisScope : HostAnalysisScope { private readonly HostSessionStartAnalysisScope _sessionScope; public HostCompilationStartAnalysisScope(HostSessionStartAnalysisScope sessionScope) { _sessionScope = sessionScope; } public override AnalyzerActions GetAnalyzerActions(DiagnosticAnalyzer analyzer) { AnalyzerActions compilationActions = base.GetAnalyzerActions(analyzer); AnalyzerActions sessionActions = _sessionScope.GetAnalyzerActions(analyzer); if (sessionActions.IsEmpty) { return compilationActions; } if (compilationActions.IsEmpty) { return sessionActions; } return compilationActions.Append(in sessionActions); } } /// <summary> /// Scope for setting up analyzers for analyzing a symbol and its members. /// </summary> internal sealed class HostSymbolStartAnalysisScope : HostAnalysisScope { public HostSymbolStartAnalysisScope() { } } /// <summary> /// Scope for setting up analyzers for a code block, capable of retrieving the actions. /// </summary> internal sealed class HostCodeBlockStartAnalysisScope<TLanguageKindEnum> where TLanguageKindEnum : struct { private ImmutableArray<CodeBlockAnalyzerAction> _codeBlockEndActions = ImmutableArray<CodeBlockAnalyzerAction>.Empty; private ImmutableArray<SyntaxNodeAnalyzerAction<TLanguageKindEnum>> _syntaxNodeActions = ImmutableArray<SyntaxNodeAnalyzerAction<TLanguageKindEnum>>.Empty; public ImmutableArray<CodeBlockAnalyzerAction> CodeBlockEndActions { get { return _codeBlockEndActions; } } public ImmutableArray<SyntaxNodeAnalyzerAction<TLanguageKindEnum>> SyntaxNodeActions { get { return _syntaxNodeActions; } } internal HostCodeBlockStartAnalysisScope() { } public void RegisterCodeBlockEndAction(DiagnosticAnalyzer analyzer, Action<CodeBlockAnalysisContext> action) { _codeBlockEndActions = _codeBlockEndActions.Add(new CodeBlockAnalyzerAction(action, analyzer)); } public void RegisterSyntaxNodeAction(DiagnosticAnalyzer analyzer, Action<SyntaxNodeAnalysisContext> action, ImmutableArray<TLanguageKindEnum> syntaxKinds) { _syntaxNodeActions = _syntaxNodeActions.Add(new SyntaxNodeAnalyzerAction<TLanguageKindEnum>(action, syntaxKinds, analyzer)); } } internal sealed class HostOperationBlockStartAnalysisScope { private ImmutableArray<OperationBlockAnalyzerAction> _operationBlockEndActions = ImmutableArray<OperationBlockAnalyzerAction>.Empty; private ImmutableArray<OperationAnalyzerAction> _operationActions = ImmutableArray<OperationAnalyzerAction>.Empty; public ImmutableArray<OperationBlockAnalyzerAction> OperationBlockEndActions => _operationBlockEndActions; public ImmutableArray<OperationAnalyzerAction> OperationActions => _operationActions; internal HostOperationBlockStartAnalysisScope() { } public void RegisterOperationBlockEndAction(DiagnosticAnalyzer analyzer, Action<OperationBlockAnalysisContext> action) { _operationBlockEndActions = _operationBlockEndActions.Add(new OperationBlockAnalyzerAction(action, analyzer)); } public void RegisterOperationAction(DiagnosticAnalyzer analyzer, Action<OperationAnalysisContext> action, ImmutableArray<OperationKind> operationKinds) { _operationActions = _operationActions.Add(new OperationAnalyzerAction(action, operationKinds, analyzer)); } } internal abstract class HostAnalysisScope { private readonly ConcurrentDictionary<DiagnosticAnalyzer, StrongBox<AnalyzerActions>> _analyzerActions = new ConcurrentDictionary<DiagnosticAnalyzer, StrongBox<AnalyzerActions>>(); public virtual AnalyzerActions GetAnalyzerActions(DiagnosticAnalyzer analyzer) { return this.GetOrCreateAnalyzerActions(analyzer).Value; } public void RegisterCompilationAction(DiagnosticAnalyzer analyzer, Action<CompilationAnalysisContext> action) { CompilationAnalyzerAction analyzerAction = new CompilationAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddCompilationAction(analyzerAction); } public void RegisterCompilationEndAction(DiagnosticAnalyzer analyzer, Action<CompilationAnalysisContext> action) { CompilationAnalyzerAction analyzerAction = new CompilationAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddCompilationEndAction(analyzerAction); } public void RegisterSemanticModelAction(DiagnosticAnalyzer analyzer, Action<SemanticModelAnalysisContext> action) { SemanticModelAnalyzerAction analyzerAction = new SemanticModelAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddSemanticModelAction(analyzerAction); } public void RegisterSyntaxTreeAction(DiagnosticAnalyzer analyzer, Action<SyntaxTreeAnalysisContext> action) { SyntaxTreeAnalyzerAction analyzerAction = new SyntaxTreeAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddSyntaxTreeAction(analyzerAction); } public void RegisterAdditionalFileAction(DiagnosticAnalyzer analyzer, Action<AdditionalFileAnalysisContext> action) { var analyzerAction = new AdditionalFileAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddAdditionalFileAction(analyzerAction); } public void RegisterSymbolAction(DiagnosticAnalyzer analyzer, Action<SymbolAnalysisContext> action, ImmutableArray<SymbolKind> symbolKinds) { SymbolAnalyzerAction analyzerAction = new SymbolAnalyzerAction(action, symbolKinds, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddSymbolAction(analyzerAction); // The SymbolAnalyzerAction does not handle SymbolKind.Parameter because the compiler // does not make CompilationEvents for them. As a workaround, handle them specially by // registering further SymbolActions (for Methods) and utilize the results to construct // the necessary SymbolAnalysisContexts. if (symbolKinds.Contains(SymbolKind.Parameter)) { RegisterSymbolAction( analyzer, context => { ImmutableArray<IParameterSymbol> parameters; switch (context.Symbol.Kind) { case SymbolKind.Method: parameters = ((IMethodSymbol)context.Symbol).Parameters; break; case SymbolKind.Property: parameters = ((IPropertySymbol)context.Symbol).Parameters; break; case SymbolKind.NamedType: var namedType = (INamedTypeSymbol)context.Symbol; var delegateInvokeMethod = namedType.DelegateInvokeMethod; parameters = delegateInvokeMethod?.Parameters ?? ImmutableArray.Create<IParameterSymbol>(); break; default: throw new ArgumentException($"{context.Symbol.Kind} is not supported.", nameof(context)); } foreach (var parameter in parameters) { if (!parameter.IsImplicitlyDeclared) { action(new SymbolAnalysisContext( parameter, context.Compilation, context.Options, context.ReportDiagnostic, context.IsSupportedDiagnostic, context.CancellationToken)); } } }, ImmutableArray.Create(SymbolKind.Method, SymbolKind.Property, SymbolKind.NamedType)); } } public void RegisterSymbolStartAction(DiagnosticAnalyzer analyzer, Action<SymbolStartAnalysisContext> action, SymbolKind symbolKind) { var analyzerAction = new SymbolStartAnalyzerAction(action, symbolKind, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddSymbolStartAction(analyzerAction); } public void RegisterSymbolEndAction(DiagnosticAnalyzer analyzer, Action<SymbolAnalysisContext> action) { var analyzerAction = new SymbolEndAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddSymbolEndAction(analyzerAction); } public void RegisterCodeBlockStartAction<TLanguageKindEnum>(DiagnosticAnalyzer analyzer, Action<CodeBlockStartAnalysisContext<TLanguageKindEnum>> action) where TLanguageKindEnum : struct { CodeBlockStartAnalyzerAction<TLanguageKindEnum> analyzerAction = new CodeBlockStartAnalyzerAction<TLanguageKindEnum>(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddCodeBlockStartAction(analyzerAction); } public void RegisterCodeBlockEndAction(DiagnosticAnalyzer analyzer, Action<CodeBlockAnalysisContext> action) { CodeBlockAnalyzerAction analyzerAction = new CodeBlockAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddCodeBlockEndAction(analyzerAction); } public void RegisterCodeBlockAction(DiagnosticAnalyzer analyzer, Action<CodeBlockAnalysisContext> action) { CodeBlockAnalyzerAction analyzerAction = new CodeBlockAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddCodeBlockAction(analyzerAction); } public void RegisterSyntaxNodeAction<TLanguageKindEnum>(DiagnosticAnalyzer analyzer, Action<SyntaxNodeAnalysisContext> action, ImmutableArray<TLanguageKindEnum> syntaxKinds) where TLanguageKindEnum : struct { SyntaxNodeAnalyzerAction<TLanguageKindEnum> analyzerAction = new SyntaxNodeAnalyzerAction<TLanguageKindEnum>(action, syntaxKinds, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddSyntaxNodeAction(analyzerAction); } public void RegisterOperationBlockStartAction(DiagnosticAnalyzer analyzer, Action<OperationBlockStartAnalysisContext> action) { OperationBlockStartAnalyzerAction analyzerAction = new OperationBlockStartAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddOperationBlockStartAction(analyzerAction); } public void RegisterOperationBlockEndAction(DiagnosticAnalyzer analyzer, Action<OperationBlockAnalysisContext> action) { OperationBlockAnalyzerAction analyzerAction = new OperationBlockAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddOperationBlockEndAction(analyzerAction); } public void RegisterOperationBlockAction(DiagnosticAnalyzer analyzer, Action<OperationBlockAnalysisContext> action) { OperationBlockAnalyzerAction analyzerAction = new OperationBlockAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddOperationBlockAction(analyzerAction); } public void RegisterOperationAction(DiagnosticAnalyzer analyzer, Action<OperationAnalysisContext> action, ImmutableArray<OperationKind> operationKinds) { OperationAnalyzerAction analyzerAction = new OperationAnalyzerAction(action, operationKinds, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddOperationAction(analyzerAction); } protected StrongBox<AnalyzerActions> GetOrCreateAnalyzerActions(DiagnosticAnalyzer analyzer) { return _analyzerActions.GetOrAdd(analyzer, _ => new StrongBox<AnalyzerActions>(AnalyzerActions.Empty)); } } /// <summary> /// Actions registered by a particular analyzer. /// </summary> // ToDo: AnalyzerActions, and all of the mechanism around it, can be eliminated if the IDE diagnostic analyzer driver // moves from an analyzer-centric model to an action-centric model. For example, the driver would need to stop asking // if a particular analyzer can analyze syntax trees, and instead ask if any syntax tree actions are present. Also, // the driver needs to apply all relevant actions rather then applying the actions of individual analyzers. internal struct AnalyzerActions { public static readonly AnalyzerActions Empty = new AnalyzerActions(concurrent: false); private ImmutableArray<CompilationStartAnalyzerAction> _compilationStartActions; private ImmutableArray<CompilationAnalyzerAction> _compilationEndActions; private ImmutableArray<CompilationAnalyzerAction> _compilationActions; private ImmutableArray<SyntaxTreeAnalyzerAction> _syntaxTreeActions; private ImmutableArray<AdditionalFileAnalyzerAction> _additionalFileActions; private ImmutableArray<SemanticModelAnalyzerAction> _semanticModelActions; private ImmutableArray<SymbolAnalyzerAction> _symbolActions; private ImmutableArray<SymbolStartAnalyzerAction> _symbolStartActions; private ImmutableArray<SymbolEndAnalyzerAction> _symbolEndActions; private ImmutableArray<AnalyzerAction> _codeBlockStartActions; private ImmutableArray<CodeBlockAnalyzerAction> _codeBlockEndActions; private ImmutableArray<CodeBlockAnalyzerAction> _codeBlockActions; private ImmutableArray<OperationBlockStartAnalyzerAction> _operationBlockStartActions; private ImmutableArray<OperationBlockAnalyzerAction> _operationBlockEndActions; private ImmutableArray<OperationBlockAnalyzerAction> _operationBlockActions; private ImmutableArray<AnalyzerAction> _syntaxNodeActions; private ImmutableArray<OperationAnalyzerAction> _operationActions; private bool _concurrent; internal AnalyzerActions(bool concurrent) { _compilationStartActions = ImmutableArray<CompilationStartAnalyzerAction>.Empty; _compilationEndActions = ImmutableArray<CompilationAnalyzerAction>.Empty; _compilationActions = ImmutableArray<CompilationAnalyzerAction>.Empty; _syntaxTreeActions = ImmutableArray<SyntaxTreeAnalyzerAction>.Empty; _additionalFileActions = ImmutableArray<AdditionalFileAnalyzerAction>.Empty; _semanticModelActions = ImmutableArray<SemanticModelAnalyzerAction>.Empty; _symbolActions = ImmutableArray<SymbolAnalyzerAction>.Empty; _symbolStartActions = ImmutableArray<SymbolStartAnalyzerAction>.Empty; _symbolEndActions = ImmutableArray<SymbolEndAnalyzerAction>.Empty; _codeBlockStartActions = ImmutableArray<AnalyzerAction>.Empty; _codeBlockEndActions = ImmutableArray<CodeBlockAnalyzerAction>.Empty; _codeBlockActions = ImmutableArray<CodeBlockAnalyzerAction>.Empty; _operationBlockStartActions = ImmutableArray<OperationBlockStartAnalyzerAction>.Empty; _operationBlockEndActions = ImmutableArray<OperationBlockAnalyzerAction>.Empty; _operationBlockActions = ImmutableArray<OperationBlockAnalyzerAction>.Empty; _syntaxNodeActions = ImmutableArray<AnalyzerAction>.Empty; _operationActions = ImmutableArray<OperationAnalyzerAction>.Empty; _concurrent = concurrent; IsEmpty = true; } public AnalyzerActions( ImmutableArray<CompilationStartAnalyzerAction> compilationStartActions, ImmutableArray<CompilationAnalyzerAction> compilationEndActions, ImmutableArray<CompilationAnalyzerAction> compilationActions, ImmutableArray<SyntaxTreeAnalyzerAction> syntaxTreeActions, ImmutableArray<AdditionalFileAnalyzerAction> additionalFileActions, ImmutableArray<SemanticModelAnalyzerAction> semanticModelActions, ImmutableArray<SymbolAnalyzerAction> symbolActions, ImmutableArray<SymbolStartAnalyzerAction> symbolStartActions, ImmutableArray<SymbolEndAnalyzerAction> symbolEndActions, ImmutableArray<AnalyzerAction> codeBlockStartActions, ImmutableArray<CodeBlockAnalyzerAction> codeBlockEndActions, ImmutableArray<CodeBlockAnalyzerAction> codeBlockActions, ImmutableArray<OperationBlockStartAnalyzerAction> operationBlockStartActions, ImmutableArray<OperationBlockAnalyzerAction> operationBlockEndActions, ImmutableArray<OperationBlockAnalyzerAction> operationBlockActions, ImmutableArray<AnalyzerAction> syntaxNodeActions, ImmutableArray<OperationAnalyzerAction> operationActions, bool concurrent, bool isEmpty) { _compilationStartActions = compilationStartActions; _compilationEndActions = compilationEndActions; _compilationActions = compilationActions; _syntaxTreeActions = syntaxTreeActions; _additionalFileActions = additionalFileActions; _semanticModelActions = semanticModelActions; _symbolActions = symbolActions; _symbolStartActions = symbolStartActions; _symbolEndActions = symbolEndActions; _codeBlockStartActions = codeBlockStartActions; _codeBlockEndActions = codeBlockEndActions; _codeBlockActions = codeBlockActions; _operationBlockStartActions = operationBlockStartActions; _operationBlockEndActions = operationBlockEndActions; _operationBlockActions = operationBlockActions; _syntaxNodeActions = syntaxNodeActions; _operationActions = operationActions; _concurrent = concurrent; IsEmpty = isEmpty; } public readonly int CompilationStartActionsCount { get { return _compilationStartActions.Length; } } public readonly int CompilationEndActionsCount { get { return _compilationEndActions.Length; } } public readonly int CompilationActionsCount { get { return _compilationActions.Length; } } public readonly int SyntaxTreeActionsCount { get { return _syntaxTreeActions.Length; } } public readonly int AdditionalFileActionsCount { get { return _additionalFileActions.Length; } } public readonly int SemanticModelActionsCount { get { return _semanticModelActions.Length; } } public readonly int SymbolActionsCount { get { return _symbolActions.Length; } } public readonly int SymbolStartActionsCount { get { return _symbolStartActions.Length; } } public readonly int SymbolEndActionsCount { get { return _symbolEndActions.Length; } } public readonly int SyntaxNodeActionsCount { get { return _syntaxNodeActions.Length; } } public readonly int OperationActionsCount { get { return _operationActions.Length; } } public readonly int OperationBlockStartActionsCount { get { return _operationBlockStartActions.Length; } } public readonly int OperationBlockEndActionsCount { get { return _operationBlockEndActions.Length; } } public readonly int OperationBlockActionsCount { get { return _operationBlockActions.Length; } } public readonly int CodeBlockStartActionsCount { get { return _codeBlockStartActions.Length; } } public readonly int CodeBlockEndActionsCount { get { return _codeBlockEndActions.Length; } } public readonly int CodeBlockActionsCount { get { return _codeBlockActions.Length; } } public readonly bool Concurrent => _concurrent; public bool IsEmpty { readonly get; private set; } public readonly bool IsDefault => _compilationStartActions.IsDefault; internal readonly ImmutableArray<CompilationStartAnalyzerAction> CompilationStartActions { get { return _compilationStartActions; } } internal readonly ImmutableArray<CompilationAnalyzerAction> CompilationEndActions { get { return _compilationEndActions; } } internal readonly ImmutableArray<CompilationAnalyzerAction> CompilationActions { get { return _compilationActions; } } internal readonly ImmutableArray<SyntaxTreeAnalyzerAction> SyntaxTreeActions { get { return _syntaxTreeActions; } } internal readonly ImmutableArray<AdditionalFileAnalyzerAction> AdditionalFileActions { get { return _additionalFileActions; } } internal readonly ImmutableArray<SemanticModelAnalyzerAction> SemanticModelActions { get { return _semanticModelActions; } } internal readonly ImmutableArray<SymbolAnalyzerAction> SymbolActions { get { return _symbolActions; } } internal readonly ImmutableArray<SymbolStartAnalyzerAction> SymbolStartActions { get { return _symbolStartActions; } } internal readonly ImmutableArray<SymbolEndAnalyzerAction> SymbolEndActions { get { return _symbolEndActions; } } internal readonly ImmutableArray<CodeBlockAnalyzerAction> CodeBlockEndActions { get { return _codeBlockEndActions; } } internal readonly ImmutableArray<CodeBlockAnalyzerAction> CodeBlockActions { get { return _codeBlockActions; } } internal readonly ImmutableArray<CodeBlockStartAnalyzerAction<TLanguageKindEnum>> GetCodeBlockStartActions<TLanguageKindEnum>() where TLanguageKindEnum : struct { return _codeBlockStartActions.OfType<CodeBlockStartAnalyzerAction<TLanguageKindEnum>>().ToImmutableArray(); } internal readonly ImmutableArray<SyntaxNodeAnalyzerAction<TLanguageKindEnum>> GetSyntaxNodeActions<TLanguageKindEnum>() where TLanguageKindEnum : struct { return _syntaxNodeActions.OfType<SyntaxNodeAnalyzerAction<TLanguageKindEnum>>().ToImmutableArray(); } internal readonly ImmutableArray<SyntaxNodeAnalyzerAction<TLanguageKindEnum>> GetSyntaxNodeActions<TLanguageKindEnum>(DiagnosticAnalyzer analyzer) where TLanguageKindEnum : struct { var builder = ArrayBuilder<SyntaxNodeAnalyzerAction<TLanguageKindEnum>>.GetInstance(); foreach (var action in _syntaxNodeActions) { if (action.Analyzer == analyzer && action is SyntaxNodeAnalyzerAction<TLanguageKindEnum> syntaxNodeAction) { builder.Add(syntaxNodeAction); } } return builder.ToImmutableAndFree(); } internal readonly ImmutableArray<OperationBlockAnalyzerAction> OperationBlockActions { get { return _operationBlockActions; } } internal readonly ImmutableArray<OperationBlockAnalyzerAction> OperationBlockEndActions { get { return _operationBlockEndActions; } } internal readonly ImmutableArray<OperationBlockStartAnalyzerAction> OperationBlockStartActions { get { return _operationBlockStartActions; } } internal readonly ImmutableArray<OperationAnalyzerAction> OperationActions { get { return _operationActions; } } internal void AddCompilationStartAction(CompilationStartAnalyzerAction action) { _compilationStartActions = _compilationStartActions.Add(action); IsEmpty = false; } internal void AddCompilationEndAction(CompilationAnalyzerAction action) { _compilationEndActions = _compilationEndActions.Add(action); IsEmpty = false; } internal void AddCompilationAction(CompilationAnalyzerAction action) { _compilationActions = _compilationActions.Add(action); IsEmpty = false; } internal void AddSyntaxTreeAction(SyntaxTreeAnalyzerAction action) { _syntaxTreeActions = _syntaxTreeActions.Add(action); IsEmpty = false; } internal void AddAdditionalFileAction(AdditionalFileAnalyzerAction action) { _additionalFileActions = _additionalFileActions.Add(action); IsEmpty = false; } internal void AddSemanticModelAction(SemanticModelAnalyzerAction action) { _semanticModelActions = _semanticModelActions.Add(action); IsEmpty = false; } internal void AddSymbolAction(SymbolAnalyzerAction action) { _symbolActions = _symbolActions.Add(action); IsEmpty = false; } internal void AddSymbolStartAction(SymbolStartAnalyzerAction action) { _symbolStartActions = _symbolStartActions.Add(action); IsEmpty = false; } internal void AddSymbolEndAction(SymbolEndAnalyzerAction action) { _symbolEndActions = _symbolEndActions.Add(action); IsEmpty = false; } internal void AddCodeBlockStartAction<TLanguageKindEnum>(CodeBlockStartAnalyzerAction<TLanguageKindEnum> action) where TLanguageKindEnum : struct { _codeBlockStartActions = _codeBlockStartActions.Add(action); IsEmpty = false; } internal void AddCodeBlockEndAction(CodeBlockAnalyzerAction action) { _codeBlockEndActions = _codeBlockEndActions.Add(action); IsEmpty = false; } internal void AddCodeBlockAction(CodeBlockAnalyzerAction action) { _codeBlockActions = _codeBlockActions.Add(action); IsEmpty = false; } internal void AddSyntaxNodeAction<TLanguageKindEnum>(SyntaxNodeAnalyzerAction<TLanguageKindEnum> action) where TLanguageKindEnum : struct { _syntaxNodeActions = _syntaxNodeActions.Add(action); IsEmpty = false; } internal void AddOperationBlockStartAction(OperationBlockStartAnalyzerAction action) { _operationBlockStartActions = _operationBlockStartActions.Add(action); IsEmpty = false; } internal void AddOperationBlockAction(OperationBlockAnalyzerAction action) { _operationBlockActions = _operationBlockActions.Add(action); IsEmpty = false; } internal void AddOperationBlockEndAction(OperationBlockAnalyzerAction action) { _operationBlockEndActions = _operationBlockEndActions.Add(action); IsEmpty = false; } internal void AddOperationAction(OperationAnalyzerAction action) { _operationActions = _operationActions.Add(action); IsEmpty = false; } internal void EnableConcurrentExecution() { _concurrent = true; } /// <summary> /// Append analyzer actions from <paramref name="otherActions"/> to actions from this instance. /// </summary> /// <param name="otherActions">Analyzer actions to append</param>. public readonly AnalyzerActions Append(in AnalyzerActions otherActions, bool appendSymbolStartAndSymbolEndActions = true) { if (otherActions.IsDefault) { throw new ArgumentNullException(nameof(otherActions)); } AnalyzerActions actions = new AnalyzerActions(concurrent: _concurrent || otherActions.Concurrent); actions._compilationStartActions = _compilationStartActions.AddRange(otherActions._compilationStartActions); actions._compilationEndActions = _compilationEndActions.AddRange(otherActions._compilationEndActions); actions._compilationActions = _compilationActions.AddRange(otherActions._compilationActions); actions._syntaxTreeActions = _syntaxTreeActions.AddRange(otherActions._syntaxTreeActions); actions._additionalFileActions = _additionalFileActions.AddRange(otherActions._additionalFileActions); actions._semanticModelActions = _semanticModelActions.AddRange(otherActions._semanticModelActions); actions._symbolActions = _symbolActions.AddRange(otherActions._symbolActions); actions._symbolStartActions = appendSymbolStartAndSymbolEndActions ? _symbolStartActions.AddRange(otherActions._symbolStartActions) : _symbolStartActions; actions._symbolEndActions = appendSymbolStartAndSymbolEndActions ? _symbolEndActions.AddRange(otherActions._symbolEndActions) : _symbolEndActions; actions._codeBlockStartActions = _codeBlockStartActions.AddRange(otherActions._codeBlockStartActions); actions._codeBlockEndActions = _codeBlockEndActions.AddRange(otherActions._codeBlockEndActions); actions._codeBlockActions = _codeBlockActions.AddRange(otherActions._codeBlockActions); actions._syntaxNodeActions = _syntaxNodeActions.AddRange(otherActions._syntaxNodeActions); actions._operationActions = _operationActions.AddRange(otherActions._operationActions); actions._operationBlockStartActions = _operationBlockStartActions.AddRange(otherActions._operationBlockStartActions); actions._operationBlockEndActions = _operationBlockEndActions.AddRange(otherActions._operationBlockEndActions); actions._operationBlockActions = _operationBlockActions.AddRange(otherActions._operationBlockActions); actions.IsEmpty = IsEmpty && otherActions.IsEmpty; return actions; } } }
-1
dotnet/roslyn
56,419
Fix partial method doc comments
Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
RikkiGibson
"2021-09-15T20:47:39Z"
"2021-09-21T23:49:10Z"
0f60b3e9446f5d0fc14a570998c81a5d6c40cc23
8cda7462843d43d9b72039eede2f4cb43126cac2
Fix partial method doc comments. Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
./src/Test/Perf/StackDepthTest/Program.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using System; using System.Runtime.InteropServices; using System.Text; namespace OverflowSensitivity { public class Program { [DllImport("kernel32.dll")] private static extern ErrorModes SetErrorMode(ErrorModes uMode); [Flags] private enum ErrorModes : uint { SYSTEM_DEFAULT = 0x0, SEM_FAILCRITICALERRORS = 0x0001, SEM_NOALIGNMENTFAULTEXCEPT = 0x0004, SEM_NOGPFAULTERRORBOX = 0x0002, SEM_NOOPENFILEERRORBOX = 0x8000 } public static int Main(string[] args) { // Prevent the "This program has stopped working" messages. SetErrorMode(ErrorModes.SEM_NOGPFAULTERRORBOX); if (args.Length != 1) { Console.WriteLine("You must pass an integer argument in to this program."); return -1; } Console.WriteLine($"Running in {IntPtr.Size * 8}-bit mode"); if (int.TryParse(args[0], out var i)) { CompileCode(MakeCode(i)); return 0; } else { Console.WriteLine($"Could not parse {args[0]}"); return -1; } } private static string MakeCode(int depth) { var builder = new StringBuilder(); builder.AppendLine( @"class C { C M(string x) { return this; } void M2() { new C() "); for (int i = 0; i < depth; i++) { builder.AppendLine(@" .M(""test"")"); } builder.AppendLine( @" .M(""test""); } }"); return builder.ToString(); } private static void CompileCode(string stringText) { var parseOptions = new CSharpParseOptions(kind: SourceCodeKind.Regular, documentationMode: DocumentationMode.None); var options = new CSharpCompilationOptions(outputKind: OutputKind.DynamicallyLinkedLibrary, concurrentBuild: false); var tree = SyntaxFactory.ParseSyntaxTree(stringText, parseOptions); var reference = MetadataReference.CreateFromFile(@"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5.2\mscorlib.dll"); var comp = CSharpCompilation.Create("assemblyName", new SyntaxTree[] { tree }, references: new MetadataReference[] { reference }, options: options); var diag = comp.GetDiagnostics(); if (!diag.IsDefaultOrEmpty) { throw new Exception(diag[0].ToString()); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using System; using System.Runtime.InteropServices; using System.Text; namespace OverflowSensitivity { public class Program { [DllImport("kernel32.dll")] private static extern ErrorModes SetErrorMode(ErrorModes uMode); [Flags] private enum ErrorModes : uint { SYSTEM_DEFAULT = 0x0, SEM_FAILCRITICALERRORS = 0x0001, SEM_NOALIGNMENTFAULTEXCEPT = 0x0004, SEM_NOGPFAULTERRORBOX = 0x0002, SEM_NOOPENFILEERRORBOX = 0x8000 } public static int Main(string[] args) { // Prevent the "This program has stopped working" messages. SetErrorMode(ErrorModes.SEM_NOGPFAULTERRORBOX); if (args.Length != 1) { Console.WriteLine("You must pass an integer argument in to this program."); return -1; } Console.WriteLine($"Running in {IntPtr.Size * 8}-bit mode"); if (int.TryParse(args[0], out var i)) { CompileCode(MakeCode(i)); return 0; } else { Console.WriteLine($"Could not parse {args[0]}"); return -1; } } private static string MakeCode(int depth) { var builder = new StringBuilder(); builder.AppendLine( @"class C { C M(string x) { return this; } void M2() { new C() "); for (int i = 0; i < depth; i++) { builder.AppendLine(@" .M(""test"")"); } builder.AppendLine( @" .M(""test""); } }"); return builder.ToString(); } private static void CompileCode(string stringText) { var parseOptions = new CSharpParseOptions(kind: SourceCodeKind.Regular, documentationMode: DocumentationMode.None); var options = new CSharpCompilationOptions(outputKind: OutputKind.DynamicallyLinkedLibrary, concurrentBuild: false); var tree = SyntaxFactory.ParseSyntaxTree(stringText, parseOptions); var reference = MetadataReference.CreateFromFile(@"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5.2\mscorlib.dll"); var comp = CSharpCompilation.Create("assemblyName", new SyntaxTree[] { tree }, references: new MetadataReference[] { reference }, options: options); var diag = comp.GetDiagnostics(); if (!diag.IsDefaultOrEmpty) { throw new Exception(diag[0].ToString()); } } } }
-1
dotnet/roslyn
56,419
Fix partial method doc comments
Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
RikkiGibson
"2021-09-15T20:47:39Z"
"2021-09-21T23:49:10Z"
0f60b3e9446f5d0fc14a570998c81a5d6c40cc23
8cda7462843d43d9b72039eede2f4cb43126cac2
Fix partial method doc comments. Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
./src/Compilers/Core/MSBuildTask/xlf/ErrorString.fr.xlf
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="fr" original="../ErrorString.resx"> <body> <trans-unit id="Compiler_UnexpectedException"> <source>MSB3883: Unexpected exception: </source> <target state="translated">MSB3883: Exception inattendue : </target> <note>{StrBegin="MSB3883: "}</note> </trans-unit> <trans-unit id="Csc_AssemblyAliasContainsIllegalCharacters"> <source>MSB3053: The assembly alias "{1}" on reference "{0}" contains illegal characters.</source> <target state="translated">MSB3053: L'alias de l'assembly "{1}" sur la référence "{0}" contient des caractères non conformes.</target> <note>{StrBegin="MSB3053: "}</note> </trans-unit> <trans-unit id="Csc_InvalidParameter"> <source>MSB3051: The parameter to the compiler is invalid. {0}</source> <target state="translated">MSB3051: Le paramètre du compilateur n'est pas valide. {0}</target> <note>{StrBegin="MSB3051: "}</note> </trans-unit> <trans-unit id="Csc_InvalidParameterWarning"> <source>MSB3052: The parameter to the compiler is invalid, '{0}{1}' will be ignored.</source> <target state="translated">MSB3052: Le paramètre du compilateur n'est pas valide. '{0}{1}' sera ignoré.</target> <note>{StrBegin="MSB3052: "}</note> </trans-unit> <trans-unit id="General_CannotConvertStringToBool"> <source>The string "{0}" cannot be converted to a boolean (true/false) value.</source> <target state="translated">Impossible de convertir la chaîne "{0}" en valeur booléenne (true/false).</target> <note /> </trans-unit> <trans-unit id="General_CouldNotSetHostObjectParameter"> <source>MSB3081: A problem occurred while trying to set the "{0}" parameter for the IDE's in-process compiler. {1}</source> <target state="translated">MSB3081: Un problème s'est produit durant la tentative de définition du paramètre "{0}" pour le compilateur in-process de l'IDE. {1}</target> <note>{StrBegin="MSB3081: "}</note> </trans-unit> <trans-unit id="General_DuplicateItemsNotSupported"> <source>MSB3105: The item "{0}" was specified more than once in the "{1}" parameter. Duplicate items are not supported by the "{1}" parameter.</source> <target state="translated">MSB3105: L'élément "{0}" a été spécifié plus d'une fois dans le paramètre "{1}". Les éléments dupliqués ne sont pas pris en charge par le paramètre "{1}".</target> <note>{StrBegin="MSB3105: "}</note> </trans-unit> <trans-unit id="General_DuplicateItemsNotSupportedWithMetadata"> <source>MSB3083: The item "{0}" was specified more than once in the "{1}" parameter and both items had the same value "{2}" for the "{3}" metadata. Duplicate items are not supported by the "{1}" parameter unless they have different values for the "{3}" metadata.</source> <target state="translated">MSB3083: L'élément "{0}" a été spécifié plusieurs fois dans le paramètre "{1}". Les deux éléments avaient la même valeur "{2}" pour les métadonnées "{3}". Les éléments dupliqués ne sont pas pris en charge par le paramètre "{1}" à moins qu'ils n'aient des valeurs différentes pour les métadonnées "{3}".</target> <note>{StrBegin="MSB3083: "}</note> </trans-unit> <trans-unit id="General_ExpectedFileMissing"> <source>Expected file "{0}" does not exist.</source> <target state="translated">Le fichier attendu "{0}" n'existe pas.</target> <note /> </trans-unit> <trans-unit id="CopyRefAssembly_SkippingCopy1"> <source>Reference assembly "{0}" already has latest information. Leaving it untouched.</source> <target state="translated">L'assembly de référence "{0}" a déjà les informations les plus récentes. Aucun changement ne sera apporté.</target> <note /> </trans-unit> <trans-unit id="CopyRefAssembly_SourceNotRef1"> <source>Could not extract the MVID from "{0}". Are you sure it is a reference assembly?</source> <target state="translated">Impossible d'extraire le MVID à partir de "{0}". Êtes-vous sûr qu'il s'agit d'un assembly de référence ?</target> <note /> </trans-unit> <trans-unit id="CopyRefAssembly_BadSource3"> <source>Failed to check the content hash of the source ref assembly '{0}': {1} {2}</source> <target state="translated">Échec de la vérification du hachage de contenu de l'assembly de référence source '{0}' : {1} {2}</target> <note /> </trans-unit> <trans-unit id="CopyRefAssembly_BadDestination1"> <source>Failed to check the content hash of the destination ref assembly '{0}'. It will be overwritten.</source> <target state="translated">Échec de la vérification du hachage de contenu de l'assembly de référence de destination '{0}'. Il sera remplacé.</target> <note /> </trans-unit> <trans-unit id="General_ToolFileNotFound"> <source>MSB3082: Task failed because "{0}" was not found.</source> <target state="translated">MSB3082: Échec de la tâche, car "{0}" est introuvable.</target> <note>{StrBegin="MSB3082: "}</note> </trans-unit> <trans-unit id="General_IncorrectHostObject"> <source>MSB3087: An incompatible host object was passed into the "{0}" task. The host object for this task must implement the "{1}" interface.</source> <target state="translated">MSB3087: Un objet hôte incompatible a été passé à la tâche "{0}". L'objet hôte pour cette tâche doit implémenter l'interface "{1}".</target> <note>{StrBegin="MSB3087: "}</note> </trans-unit> <trans-unit id="General_InvalidAttributeMetadata"> <source>Item "{0}" has attribute "{1}" with value "{2}" that could not be converted to "{3}".</source> <target state="translated">L'élément "{0}" a l'attribut "{1}" avec la valeur "{2}", qui n'a pas pu être convertie en "{3}".</target> <note /> </trans-unit> <trans-unit id="General_ParameterUnsupportedOnHostCompiler"> <source>The IDE's in-process compiler does not support the specified values for the "{0}" parameter. Therefore, this task will fallback to using the command-line compiler.</source> <target state="translated">Le compilateur in-process de l'IDE ne prend pas en charge les valeurs spécifiées pour le paramètre "{0}". Cette tâche utilisera donc le compilateur de ligne de commande.</target> <note /> </trans-unit> <trans-unit id="General_ReferenceDoesNotExist"> <source>MSB3104: The referenced assembly "{0}" was not found. If this assembly is produced by another one of your projects, please make sure to build that project before building this one.</source> <target state="translated">MSB3104: L'assembly référencé "{0}" est introuvable. Si cet assembly est produit par l'un de vos projets, assurez-vous de générer ce projet avant de générer celui-ci.</target> <note>{StrBegin="MSB3104: "}</note> </trans-unit> <trans-unit id="General_UnableToReadFile"> <source>File "{0}" could not be read: {1}</source> <target state="translated">Impossible de lire le fichier "{0}" : {1}</target> <note /> </trans-unit> <trans-unit id="ImplicitlySkipAnalyzersMessage"> <source>Skipping analyzers to speed up the build. You can execute 'Build' or 'Rebuild' command to run analyzers.</source> <target state="new">Skipping analyzers to speed up the build. You can execute 'Build' or 'Rebuild' command to run analyzers.</target> <note /> </trans-unit> <trans-unit id="SharedCompilationFallback"> <source>Shared compilation failed; falling back to tool: {0}</source> <target state="translated">Échec de la compilation partagée ; retour à l'outil : {0}</target> <note /> </trans-unit> <trans-unit id="UsingSharedCompilation"> <source>Using shared compilation with compiler from directory: {0}</source> <target state="translated">Utilisation de la compilation partagée avec le compilateur du répertoire : {0}</target> <note /> </trans-unit> <trans-unit id="Vbc_EnumParameterHasInvalidValue"> <source>MSB3401: "{1}" is an invalid value for the "{0}" parameter. The valid values are: {2}</source> <target state="translated">MSB3401: "{1}" n'est pas une valeur valide pour le paramètre "{0}". Les valeurs valides sont : {2}</target> <note>{StrBegin="MSB3401: "}</note> </trans-unit> <trans-unit id="Vbc_ParameterHasInvalidValue"> <source>"{1}" is an invalid value for the "{0}" parameter.</source> <target state="translated">"{1}" n'est pas une valeur valide pour le paramètre "{0}".</target> <note /> </trans-unit> <trans-unit id="Vbc_RenamePDB"> <source>MSB3402: There was an error creating the pdb file "{0}". {1}</source> <target state="translated">MSB3402: Une erreur s'est produite durant la création du fichier pdb "{0}". {1}</target> <note>{StrBegin="MSB3402: "}</note> </trans-unit> <trans-unit id="MapSourceRoots.ContainsDuplicate"> <source>{0} contains duplicate items '{1}' with conflicting metadata '{2}': '{3}' and '{4}'</source> <target state="translated">{0} contient des éléments dupliqués '{1}' avec des métadonnées en conflit '{2}' : '{3}' et '{4}'</target> <note /> </trans-unit> <trans-unit id="MapSourceRoots.PathMustEndWithSlashOrBackslash"> <source>{0} paths are required to end with a slash or backslash: '{1}'</source> <target state="translated">Les chemins {0} doivent finir par une barre oblique ou une barre oblique inverse : '{1}'</target> <note /> </trans-unit> <trans-unit id="MapSourceRoots.NoTopLevelSourceRoot"> <source>{0} items must include at least one top-level (not nested) item when {1} is true</source> <target state="translated">Les éléments {0} doivent inclure au moins un élément de niveau supérieur (non imbriqué) quand {1} a la valeur true</target> <note /> </trans-unit> <trans-unit id="MapSourceRoots.NoSuchTopLevelSourceRoot"> <source>The value of {0} not found in {1} items, or the corresponding item is not a top-level source root: '{2}'</source> <target state="translated">La valeur de {0} est introuvable dans les éléments {1}, ou l'élément correspondant n'est pas une racine source de niveau supérieur : '{2}'</target> <note /> </trans-unit> </body> </file> </xliff>
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="fr" original="../ErrorString.resx"> <body> <trans-unit id="Compiler_UnexpectedException"> <source>MSB3883: Unexpected exception: </source> <target state="translated">MSB3883: Exception inattendue : </target> <note>{StrBegin="MSB3883: "}</note> </trans-unit> <trans-unit id="Csc_AssemblyAliasContainsIllegalCharacters"> <source>MSB3053: The assembly alias "{1}" on reference "{0}" contains illegal characters.</source> <target state="translated">MSB3053: L'alias de l'assembly "{1}" sur la référence "{0}" contient des caractères non conformes.</target> <note>{StrBegin="MSB3053: "}</note> </trans-unit> <trans-unit id="Csc_InvalidParameter"> <source>MSB3051: The parameter to the compiler is invalid. {0}</source> <target state="translated">MSB3051: Le paramètre du compilateur n'est pas valide. {0}</target> <note>{StrBegin="MSB3051: "}</note> </trans-unit> <trans-unit id="Csc_InvalidParameterWarning"> <source>MSB3052: The parameter to the compiler is invalid, '{0}{1}' will be ignored.</source> <target state="translated">MSB3052: Le paramètre du compilateur n'est pas valide. '{0}{1}' sera ignoré.</target> <note>{StrBegin="MSB3052: "}</note> </trans-unit> <trans-unit id="General_CannotConvertStringToBool"> <source>The string "{0}" cannot be converted to a boolean (true/false) value.</source> <target state="translated">Impossible de convertir la chaîne "{0}" en valeur booléenne (true/false).</target> <note /> </trans-unit> <trans-unit id="General_CouldNotSetHostObjectParameter"> <source>MSB3081: A problem occurred while trying to set the "{0}" parameter for the IDE's in-process compiler. {1}</source> <target state="translated">MSB3081: Un problème s'est produit durant la tentative de définition du paramètre "{0}" pour le compilateur in-process de l'IDE. {1}</target> <note>{StrBegin="MSB3081: "}</note> </trans-unit> <trans-unit id="General_DuplicateItemsNotSupported"> <source>MSB3105: The item "{0}" was specified more than once in the "{1}" parameter. Duplicate items are not supported by the "{1}" parameter.</source> <target state="translated">MSB3105: L'élément "{0}" a été spécifié plus d'une fois dans le paramètre "{1}". Les éléments dupliqués ne sont pas pris en charge par le paramètre "{1}".</target> <note>{StrBegin="MSB3105: "}</note> </trans-unit> <trans-unit id="General_DuplicateItemsNotSupportedWithMetadata"> <source>MSB3083: The item "{0}" was specified more than once in the "{1}" parameter and both items had the same value "{2}" for the "{3}" metadata. Duplicate items are not supported by the "{1}" parameter unless they have different values for the "{3}" metadata.</source> <target state="translated">MSB3083: L'élément "{0}" a été spécifié plusieurs fois dans le paramètre "{1}". Les deux éléments avaient la même valeur "{2}" pour les métadonnées "{3}". Les éléments dupliqués ne sont pas pris en charge par le paramètre "{1}" à moins qu'ils n'aient des valeurs différentes pour les métadonnées "{3}".</target> <note>{StrBegin="MSB3083: "}</note> </trans-unit> <trans-unit id="General_ExpectedFileMissing"> <source>Expected file "{0}" does not exist.</source> <target state="translated">Le fichier attendu "{0}" n'existe pas.</target> <note /> </trans-unit> <trans-unit id="CopyRefAssembly_SkippingCopy1"> <source>Reference assembly "{0}" already has latest information. Leaving it untouched.</source> <target state="translated">L'assembly de référence "{0}" a déjà les informations les plus récentes. Aucun changement ne sera apporté.</target> <note /> </trans-unit> <trans-unit id="CopyRefAssembly_SourceNotRef1"> <source>Could not extract the MVID from "{0}". Are you sure it is a reference assembly?</source> <target state="translated">Impossible d'extraire le MVID à partir de "{0}". Êtes-vous sûr qu'il s'agit d'un assembly de référence ?</target> <note /> </trans-unit> <trans-unit id="CopyRefAssembly_BadSource3"> <source>Failed to check the content hash of the source ref assembly '{0}': {1} {2}</source> <target state="translated">Échec de la vérification du hachage de contenu de l'assembly de référence source '{0}' : {1} {2}</target> <note /> </trans-unit> <trans-unit id="CopyRefAssembly_BadDestination1"> <source>Failed to check the content hash of the destination ref assembly '{0}'. It will be overwritten.</source> <target state="translated">Échec de la vérification du hachage de contenu de l'assembly de référence de destination '{0}'. Il sera remplacé.</target> <note /> </trans-unit> <trans-unit id="General_ToolFileNotFound"> <source>MSB3082: Task failed because "{0}" was not found.</source> <target state="translated">MSB3082: Échec de la tâche, car "{0}" est introuvable.</target> <note>{StrBegin="MSB3082: "}</note> </trans-unit> <trans-unit id="General_IncorrectHostObject"> <source>MSB3087: An incompatible host object was passed into the "{0}" task. The host object for this task must implement the "{1}" interface.</source> <target state="translated">MSB3087: Un objet hôte incompatible a été passé à la tâche "{0}". L'objet hôte pour cette tâche doit implémenter l'interface "{1}".</target> <note>{StrBegin="MSB3087: "}</note> </trans-unit> <trans-unit id="General_InvalidAttributeMetadata"> <source>Item "{0}" has attribute "{1}" with value "{2}" that could not be converted to "{3}".</source> <target state="translated">L'élément "{0}" a l'attribut "{1}" avec la valeur "{2}", qui n'a pas pu être convertie en "{3}".</target> <note /> </trans-unit> <trans-unit id="General_ParameterUnsupportedOnHostCompiler"> <source>The IDE's in-process compiler does not support the specified values for the "{0}" parameter. Therefore, this task will fallback to using the command-line compiler.</source> <target state="translated">Le compilateur in-process de l'IDE ne prend pas en charge les valeurs spécifiées pour le paramètre "{0}". Cette tâche utilisera donc le compilateur de ligne de commande.</target> <note /> </trans-unit> <trans-unit id="General_ReferenceDoesNotExist"> <source>MSB3104: The referenced assembly "{0}" was not found. If this assembly is produced by another one of your projects, please make sure to build that project before building this one.</source> <target state="translated">MSB3104: L'assembly référencé "{0}" est introuvable. Si cet assembly est produit par l'un de vos projets, assurez-vous de générer ce projet avant de générer celui-ci.</target> <note>{StrBegin="MSB3104: "}</note> </trans-unit> <trans-unit id="General_UnableToReadFile"> <source>File "{0}" could not be read: {1}</source> <target state="translated">Impossible de lire le fichier "{0}" : {1}</target> <note /> </trans-unit> <trans-unit id="ImplicitlySkipAnalyzersMessage"> <source>Skipping analyzers to speed up the build. You can execute 'Build' or 'Rebuild' command to run analyzers.</source> <target state="new">Skipping analyzers to speed up the build. You can execute 'Build' or 'Rebuild' command to run analyzers.</target> <note /> </trans-unit> <trans-unit id="SharedCompilationFallback"> <source>Shared compilation failed; falling back to tool: {0}</source> <target state="translated">Échec de la compilation partagée ; retour à l'outil : {0}</target> <note /> </trans-unit> <trans-unit id="UsingSharedCompilation"> <source>Using shared compilation with compiler from directory: {0}</source> <target state="translated">Utilisation de la compilation partagée avec le compilateur du répertoire : {0}</target> <note /> </trans-unit> <trans-unit id="Vbc_EnumParameterHasInvalidValue"> <source>MSB3401: "{1}" is an invalid value for the "{0}" parameter. The valid values are: {2}</source> <target state="translated">MSB3401: "{1}" n'est pas une valeur valide pour le paramètre "{0}". Les valeurs valides sont : {2}</target> <note>{StrBegin="MSB3401: "}</note> </trans-unit> <trans-unit id="Vbc_ParameterHasInvalidValue"> <source>"{1}" is an invalid value for the "{0}" parameter.</source> <target state="translated">"{1}" n'est pas une valeur valide pour le paramètre "{0}".</target> <note /> </trans-unit> <trans-unit id="Vbc_RenamePDB"> <source>MSB3402: There was an error creating the pdb file "{0}". {1}</source> <target state="translated">MSB3402: Une erreur s'est produite durant la création du fichier pdb "{0}". {1}</target> <note>{StrBegin="MSB3402: "}</note> </trans-unit> <trans-unit id="MapSourceRoots.ContainsDuplicate"> <source>{0} contains duplicate items '{1}' with conflicting metadata '{2}': '{3}' and '{4}'</source> <target state="translated">{0} contient des éléments dupliqués '{1}' avec des métadonnées en conflit '{2}' : '{3}' et '{4}'</target> <note /> </trans-unit> <trans-unit id="MapSourceRoots.PathMustEndWithSlashOrBackslash"> <source>{0} paths are required to end with a slash or backslash: '{1}'</source> <target state="translated">Les chemins {0} doivent finir par une barre oblique ou une barre oblique inverse : '{1}'</target> <note /> </trans-unit> <trans-unit id="MapSourceRoots.NoTopLevelSourceRoot"> <source>{0} items must include at least one top-level (not nested) item when {1} is true</source> <target state="translated">Les éléments {0} doivent inclure au moins un élément de niveau supérieur (non imbriqué) quand {1} a la valeur true</target> <note /> </trans-unit> <trans-unit id="MapSourceRoots.NoSuchTopLevelSourceRoot"> <source>The value of {0} not found in {1} items, or the corresponding item is not a top-level source root: '{2}'</source> <target state="translated">La valeur de {0} est introuvable dans les éléments {1}, ou l'élément correspondant n'est pas une racine source de niveau supérieur : '{2}'</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
56,419
Fix partial method doc comments
Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
RikkiGibson
"2021-09-15T20:47:39Z"
"2021-09-21T23:49:10Z"
0f60b3e9446f5d0fc14a570998c81a5d6c40cc23
8cda7462843d43d9b72039eede2f4cb43126cac2
Fix partial method doc comments. Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
./src/EditorFeatures/CSharp/BlockCommentEditing/CloseBlockCommentCommandHandler.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.ComponentModel.Composition; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Options; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.CSharp.BlockCommentEditing { [Export(typeof(ICommandHandler))] [ContentType(ContentTypeNames.CSharpContentType)] [Name(nameof(CloseBlockCommentCommandHandler))] [Order(After = nameof(BlockCommentEditingCommandHandler))] internal sealed class CloseBlockCommentCommandHandler : ICommandHandler<TypeCharCommandArgs> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CloseBlockCommentCommandHandler() { } public string DisplayName => EditorFeaturesResources.Block_Comment_Editing; public bool ExecuteCommand(TypeCharCommandArgs args, CommandExecutionContext executionContext) { if (args.TypedChar == '/') { var caret = args.TextView.GetCaretPoint(args.SubjectBuffer); if (caret != null) { var (snapshot, position) = caret.Value; // Check that the line is all whitespace ending with an asterisk and a single space (| marks caret position): // * | if (position >= 2 && snapshot[position - 1] == ' ' && snapshot[position - 2] == '*') { var line = snapshot.GetLineFromPosition(position); if (line.End == position && line.IsEmptyOrWhitespace(0, line.Length - 2)) { if (args.SubjectBuffer.GetFeatureOnOffOption(FeatureOnOffOptions.AutoInsertBlockCommentStartString) && BlockCommentEditingCommandHandler.IsCaretInsideBlockCommentSyntax(caret.Value, out _, out _)) { args.SubjectBuffer.Replace(new VisualStudio.Text.Span(position - 1, 1), "/"); return true; } } } } } return false; } public CommandState GetCommandState(TypeCharCommandArgs args) => CommandState.Unspecified; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.ComponentModel.Composition; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Options; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.CSharp.BlockCommentEditing { [Export(typeof(ICommandHandler))] [ContentType(ContentTypeNames.CSharpContentType)] [Name(nameof(CloseBlockCommentCommandHandler))] [Order(After = nameof(BlockCommentEditingCommandHandler))] internal sealed class CloseBlockCommentCommandHandler : ICommandHandler<TypeCharCommandArgs> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CloseBlockCommentCommandHandler() { } public string DisplayName => EditorFeaturesResources.Block_Comment_Editing; public bool ExecuteCommand(TypeCharCommandArgs args, CommandExecutionContext executionContext) { if (args.TypedChar == '/') { var caret = args.TextView.GetCaretPoint(args.SubjectBuffer); if (caret != null) { var (snapshot, position) = caret.Value; // Check that the line is all whitespace ending with an asterisk and a single space (| marks caret position): // * | if (position >= 2 && snapshot[position - 1] == ' ' && snapshot[position - 2] == '*') { var line = snapshot.GetLineFromPosition(position); if (line.End == position && line.IsEmptyOrWhitespace(0, line.Length - 2)) { if (args.SubjectBuffer.GetFeatureOnOffOption(FeatureOnOffOptions.AutoInsertBlockCommentStartString) && BlockCommentEditingCommandHandler.IsCaretInsideBlockCommentSyntax(caret.Value, out _, out _)) { args.SubjectBuffer.Replace(new VisualStudio.Text.Span(position - 1, 1), "/"); return true; } } } } } return false; } public CommandState GetCommandState(TypeCharCommandArgs args) => CommandState.Unspecified; } }
-1
dotnet/roslyn
56,419
Fix partial method doc comments
Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
RikkiGibson
"2021-09-15T20:47:39Z"
"2021-09-21T23:49:10Z"
0f60b3e9446f5d0fc14a570998c81a5d6c40cc23
8cda7462843d43d9b72039eede2f4cb43126cac2
Fix partial method doc comments. Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
./src/EditorFeatures/CSharpTest/CodeActions/MoveType/MoveTypeTests.RenameFile.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeActions.MoveType { public partial class MoveTypeTests : CSharpMoveTypeTestsBase { [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task SingleClassInFile_RenameFile() { var code = @"[||]class Class1 { }"; var expectedDocumentName = "Class1.cs"; await TestRenameFileToMatchTypeAsync(code, expectedDocumentName); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoreThanOneTypeInFile_RenameFile() { var code = @"[||]class Class1 { class Inner { } }"; var expectedDocumentName = "Class1.cs"; await TestRenameFileToMatchTypeAsync(code, expectedDocumentName); } [WorkItem(16284, "https://github.com/dotnet/roslyn/issues/16284")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoreThanOneTypeInFile_RenameFile_InnerType() { var code = @"class Class1 { [||]class Inner { } }"; var expectedDocumentName = "Class1.Inner.cs"; await TestRenameFileToMatchTypeAsync(code, expectedDocumentName); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task TestRenameFileWithFolders() { var code = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document Folders=""A\B""> [||]class Class1 { class Inner { } } </Document> </Project> </Workspace>"; var expectedDocumentName = "Class1.cs"; await TestRenameFileToMatchTypeAsync(code, expectedDocumentName, destinationDocumentContainers: new[] { "A", "B" }); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task TestMissing_TypeNameMatchesFileName_RenameFile() { // testworkspace creates files like test1.cs, test2.cs and so on.. // so type name matches filename here and rename file action should not be offered. var code = @"[||]class test1 { }"; await TestRenameFileToMatchTypeAsync(code, expectedCodeAction: false); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task TestMissing_MultipleTopLevelTypesInFileAndAtleastOneMatchesFileName_RenameFile() { var code = @"[||]class Class1 { } class test1 { }"; await TestRenameFileToMatchTypeAsync(code, expectedCodeAction: false); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MultipleTopLevelTypesInFileAndNoneMatchFileName_RenameFile() { var code = @"[||]class Class1 { } class Class2 { }"; var expectedDocumentName = "Class1.cs"; await TestRenameFileToMatchTypeAsync(code, expectedDocumentName); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MultipleTopLevelTypesInFileAndNoneMatchFileName2_RenameFile() { var code = @"class Class1 { } [||]class Class2 { }"; var expectedDocumentName = "Class2.cs"; await TestRenameFileToMatchTypeAsync(code, expectedDocumentName); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task NestedFile_Simple_RenameFile() { var code = @"class OuterType { [||]class InnerType { } }"; var expectedDocumentName = "InnerType.cs"; await TestRenameFileToMatchTypeAsync(code, expectedDocumentName); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task NestedFile_DottedName_RenameFile() { var code = @"class OuterType { [||]class InnerType { } }"; var expectedDocumentName = "OuterType.InnerType.cs"; await TestRenameFileToMatchTypeAsync(code, expectedDocumentName); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeActions.MoveType { public partial class MoveTypeTests : CSharpMoveTypeTestsBase { [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task SingleClassInFile_RenameFile() { var code = @"[||]class Class1 { }"; var expectedDocumentName = "Class1.cs"; await TestRenameFileToMatchTypeAsync(code, expectedDocumentName); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoreThanOneTypeInFile_RenameFile() { var code = @"[||]class Class1 { class Inner { } }"; var expectedDocumentName = "Class1.cs"; await TestRenameFileToMatchTypeAsync(code, expectedDocumentName); } [WorkItem(16284, "https://github.com/dotnet/roslyn/issues/16284")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoreThanOneTypeInFile_RenameFile_InnerType() { var code = @"class Class1 { [||]class Inner { } }"; var expectedDocumentName = "Class1.Inner.cs"; await TestRenameFileToMatchTypeAsync(code, expectedDocumentName); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task TestRenameFileWithFolders() { var code = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document Folders=""A\B""> [||]class Class1 { class Inner { } } </Document> </Project> </Workspace>"; var expectedDocumentName = "Class1.cs"; await TestRenameFileToMatchTypeAsync(code, expectedDocumentName, destinationDocumentContainers: new[] { "A", "B" }); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task TestMissing_TypeNameMatchesFileName_RenameFile() { // testworkspace creates files like test1.cs, test2.cs and so on.. // so type name matches filename here and rename file action should not be offered. var code = @"[||]class test1 { }"; await TestRenameFileToMatchTypeAsync(code, expectedCodeAction: false); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task TestMissing_MultipleTopLevelTypesInFileAndAtleastOneMatchesFileName_RenameFile() { var code = @"[||]class Class1 { } class test1 { }"; await TestRenameFileToMatchTypeAsync(code, expectedCodeAction: false); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MultipleTopLevelTypesInFileAndNoneMatchFileName_RenameFile() { var code = @"[||]class Class1 { } class Class2 { }"; var expectedDocumentName = "Class1.cs"; await TestRenameFileToMatchTypeAsync(code, expectedDocumentName); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MultipleTopLevelTypesInFileAndNoneMatchFileName2_RenameFile() { var code = @"class Class1 { } [||]class Class2 { }"; var expectedDocumentName = "Class2.cs"; await TestRenameFileToMatchTypeAsync(code, expectedDocumentName); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task NestedFile_Simple_RenameFile() { var code = @"class OuterType { [||]class InnerType { } }"; var expectedDocumentName = "InnerType.cs"; await TestRenameFileToMatchTypeAsync(code, expectedDocumentName); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task NestedFile_DottedName_RenameFile() { var code = @"class OuterType { [||]class InnerType { } }"; var expectedDocumentName = "OuterType.InnerType.cs"; await TestRenameFileToMatchTypeAsync(code, expectedDocumentName); } } }
-1
dotnet/roslyn
56,419
Fix partial method doc comments
Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
RikkiGibson
"2021-09-15T20:47:39Z"
"2021-09-21T23:49:10Z"
0f60b3e9446f5d0fc14a570998c81a5d6c40cc23
8cda7462843d43d9b72039eede2f4cb43126cac2
Fix partial method doc comments. Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
./src/EditorFeatures/Test/Extensions/CollectionExtensionsTest.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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 Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Extensions { public class CollectionExtensionsTest { [Fact] public void PushReverse1() { var stack = new Stack<int>(); stack.PushReverse(new int[] { 1, 2, 3 }); Assert.Equal(1, stack.Pop()); Assert.Equal(2, stack.Pop()); Assert.Equal(3, stack.Pop()); Assert.Equal(0, stack.Count); } [Fact] public void PushReverse2() { var stack = new Stack<int>(); stack.PushReverse(Array.Empty<int>()); Assert.Equal(0, stack.Count); } [Fact] public void PushReverse3() { var stack = new Stack<int>(); stack.Push(3); stack.PushReverse(new int[] { 1, 2 }); Assert.Equal(1, stack.Pop()); Assert.Equal(2, stack.Pop()); Assert.Equal(3, stack.Pop()); Assert.Equal(0, stack.Count); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Extensions { public class CollectionExtensionsTest { [Fact] public void PushReverse1() { var stack = new Stack<int>(); stack.PushReverse(new int[] { 1, 2, 3 }); Assert.Equal(1, stack.Pop()); Assert.Equal(2, stack.Pop()); Assert.Equal(3, stack.Pop()); Assert.Equal(0, stack.Count); } [Fact] public void PushReverse2() { var stack = new Stack<int>(); stack.PushReverse(Array.Empty<int>()); Assert.Equal(0, stack.Count); } [Fact] public void PushReverse3() { var stack = new Stack<int>(); stack.Push(3); stack.PushReverse(new int[] { 1, 2 }); Assert.Equal(1, stack.Pop()); Assert.Equal(2, stack.Pop()); Assert.Equal(3, stack.Pop()); Assert.Equal(0, stack.Count); } } }
-1
dotnet/roslyn
56,419
Fix partial method doc comments
Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
RikkiGibson
"2021-09-15T20:47:39Z"
"2021-09-21T23:49:10Z"
0f60b3e9446f5d0fc14a570998c81a5d6c40cc23
8cda7462843d43d9b72039eede2f4cb43126cac2
Fix partial method doc comments. Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
./docs/features/dynamic-analysis.work.md
Dynamic Analysis =============== This feature enables instrumentation of binaries to collect information for dynamic analysis. -------------------- TODO: - Generate code to compute MVIDs less often than once per invoked method. - Synthesize helper types to contain fields for analysis payloads so that methods of generic types can be instrumented. - Accurately identify which methods are tests. - Integrate dynamic analysis instrumentation with lowering. - Verify that instrumentation covers constructor initializers and field initializers.
Dynamic Analysis =============== This feature enables instrumentation of binaries to collect information for dynamic analysis. -------------------- TODO: - Generate code to compute MVIDs less often than once per invoked method. - Synthesize helper types to contain fields for analysis payloads so that methods of generic types can be instrumented. - Accurately identify which methods are tests. - Integrate dynamic analysis instrumentation with lowering. - Verify that instrumentation covers constructor initializers and field initializers.
-1
dotnet/roslyn
56,419
Fix partial method doc comments
Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
RikkiGibson
"2021-09-15T20:47:39Z"
"2021-09-21T23:49:10Z"
0f60b3e9446f5d0fc14a570998c81a5d6c40cc23
8cda7462843d43d9b72039eede2f4cb43126cac2
Fix partial method doc comments. Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
./src/Features/Core/Portable/GenerateMember/GenerateEnumMember/AbstractGenerateEnumMemberService.State.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.GenerateMember.GenerateEnumMember { internal abstract partial class AbstractGenerateEnumMemberService<TService, TSimpleNameSyntax, TExpressionSyntax> { private partial class State { // public TypeDeclarationSyntax ContainingTypeDeclaration { get; private set; } public INamedTypeSymbol TypeToGenerateIn { get; private set; } // Just the name of the method. i.e. "Goo" in "Goo" or "X.Goo" public SyntaxToken IdentifierToken { get; private set; } public TSimpleNameSyntax SimpleName { get; private set; } public TExpressionSyntax SimpleNameOrMemberAccessExpression { get; private set; } public static async Task<State> GenerateAsync( TService service, SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken) { var state = new State(); if (!await state.TryInitializeAsync(service, document, node, cancellationToken).ConfigureAwait(false)) { return null; } return state; } private async Task<bool> TryInitializeAsync( TService service, SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken) { if (service.IsIdentifierNameGeneration(node)) { if (!TryInitializeIdentifierName(service, document, (TSimpleNameSyntax)node, cancellationToken)) { return false; } } else { return false; } // Ok. It either didn't bind to any symbols, or it bound to a symbol but with // errors. In the former case we definitely want to offer to generate a field. In // the latter case, we want to generate a field *unless* there's an existing member // with the same name. Note: it's ok if there's an existing field with the same // name. var existingMembers = TypeToGenerateIn.GetMembers(IdentifierToken.ValueText); if (existingMembers.Any()) { // TODO: Code coverage There was an existing member that the new member would // clash with. return false; } cancellationToken.ThrowIfCancellationRequested(); TypeToGenerateIn = await SymbolFinder.FindSourceDefinitionAsync(TypeToGenerateIn, document.Project.Solution, cancellationToken).ConfigureAwait(false) as INamedTypeSymbol; if (!ValidateTypeToGenerateIn(TypeToGenerateIn, true, EnumType)) { return false; } return CodeGenerator.CanAdd(document.Project.Solution, TypeToGenerateIn, cancellationToken); } private bool TryInitializeIdentifierName( TService service, SemanticDocument semanticDocument, TSimpleNameSyntax identifierName, CancellationToken cancellationToken) { SimpleName = identifierName; if (!service.TryInitializeIdentifierNameState(semanticDocument, identifierName, cancellationToken, out var identifierToken, out var simpleNameOrMemberAccessExpression)) { return false; } IdentifierToken = identifierToken; SimpleNameOrMemberAccessExpression = simpleNameOrMemberAccessExpression; var semanticModel = semanticDocument.SemanticModel; var semanticFacts = semanticDocument.Document.GetLanguageService<ISemanticFactsService>(); var syntaxFacts = semanticDocument.Document.GetLanguageService<ISyntaxFactsService>(); if (semanticFacts.IsWrittenTo(semanticModel, SimpleNameOrMemberAccessExpression, cancellationToken) || syntaxFacts.IsInNamespaceOrTypeContext(SimpleNameOrMemberAccessExpression)) { return false; } // Now, try to bind the invocation and see if it succeeds or not. if it succeeds and // binds uniquely, then we don't need to offer this quick fix. cancellationToken.ThrowIfCancellationRequested(); var containingType = semanticModel.GetEnclosingNamedType(identifierToken.SpanStart, cancellationToken); if (containingType == null) { return false; } var semanticInfo = semanticModel.GetSymbolInfo(SimpleNameOrMemberAccessExpression, cancellationToken); if (cancellationToken.IsCancellationRequested) { return false; } if (semanticInfo.Symbol != null) { return false; } // Either we found no matches, or this was ambiguous. Either way, we might be able // to generate a method here. Determine where the user wants to generate the method // into, and if it's valid then proceed. if (!TryDetermineTypeToGenerateIn( semanticDocument, containingType, simpleNameOrMemberAccessExpression, cancellationToken, out var typeToGenerateIn, out var isStatic)) { return false; } if (!isStatic) { return false; } TypeToGenerateIn = typeToGenerateIn; return true; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.GenerateMember.GenerateEnumMember { internal abstract partial class AbstractGenerateEnumMemberService<TService, TSimpleNameSyntax, TExpressionSyntax> { private partial class State { // public TypeDeclarationSyntax ContainingTypeDeclaration { get; private set; } public INamedTypeSymbol TypeToGenerateIn { get; private set; } // Just the name of the method. i.e. "Goo" in "Goo" or "X.Goo" public SyntaxToken IdentifierToken { get; private set; } public TSimpleNameSyntax SimpleName { get; private set; } public TExpressionSyntax SimpleNameOrMemberAccessExpression { get; private set; } public static async Task<State> GenerateAsync( TService service, SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken) { var state = new State(); if (!await state.TryInitializeAsync(service, document, node, cancellationToken).ConfigureAwait(false)) { return null; } return state; } private async Task<bool> TryInitializeAsync( TService service, SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken) { if (service.IsIdentifierNameGeneration(node)) { if (!TryInitializeIdentifierName(service, document, (TSimpleNameSyntax)node, cancellationToken)) { return false; } } else { return false; } // Ok. It either didn't bind to any symbols, or it bound to a symbol but with // errors. In the former case we definitely want to offer to generate a field. In // the latter case, we want to generate a field *unless* there's an existing member // with the same name. Note: it's ok if there's an existing field with the same // name. var existingMembers = TypeToGenerateIn.GetMembers(IdentifierToken.ValueText); if (existingMembers.Any()) { // TODO: Code coverage There was an existing member that the new member would // clash with. return false; } cancellationToken.ThrowIfCancellationRequested(); TypeToGenerateIn = await SymbolFinder.FindSourceDefinitionAsync(TypeToGenerateIn, document.Project.Solution, cancellationToken).ConfigureAwait(false) as INamedTypeSymbol; if (!ValidateTypeToGenerateIn(TypeToGenerateIn, true, EnumType)) { return false; } return CodeGenerator.CanAdd(document.Project.Solution, TypeToGenerateIn, cancellationToken); } private bool TryInitializeIdentifierName( TService service, SemanticDocument semanticDocument, TSimpleNameSyntax identifierName, CancellationToken cancellationToken) { SimpleName = identifierName; if (!service.TryInitializeIdentifierNameState(semanticDocument, identifierName, cancellationToken, out var identifierToken, out var simpleNameOrMemberAccessExpression)) { return false; } IdentifierToken = identifierToken; SimpleNameOrMemberAccessExpression = simpleNameOrMemberAccessExpression; var semanticModel = semanticDocument.SemanticModel; var semanticFacts = semanticDocument.Document.GetLanguageService<ISemanticFactsService>(); var syntaxFacts = semanticDocument.Document.GetLanguageService<ISyntaxFactsService>(); if (semanticFacts.IsWrittenTo(semanticModel, SimpleNameOrMemberAccessExpression, cancellationToken) || syntaxFacts.IsInNamespaceOrTypeContext(SimpleNameOrMemberAccessExpression)) { return false; } // Now, try to bind the invocation and see if it succeeds or not. if it succeeds and // binds uniquely, then we don't need to offer this quick fix. cancellationToken.ThrowIfCancellationRequested(); var containingType = semanticModel.GetEnclosingNamedType(identifierToken.SpanStart, cancellationToken); if (containingType == null) { return false; } var semanticInfo = semanticModel.GetSymbolInfo(SimpleNameOrMemberAccessExpression, cancellationToken); if (cancellationToken.IsCancellationRequested) { return false; } if (semanticInfo.Symbol != null) { return false; } // Either we found no matches, or this was ambiguous. Either way, we might be able // to generate a method here. Determine where the user wants to generate the method // into, and if it's valid then proceed. if (!TryDetermineTypeToGenerateIn( semanticDocument, containingType, simpleNameOrMemberAccessExpression, cancellationToken, out var typeToGenerateIn, out var isStatic)) { return false; } if (!isStatic) { return false; } TypeToGenerateIn = typeToGenerateIn; return true; } } } }
-1
dotnet/roslyn
56,419
Fix partial method doc comments
Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
RikkiGibson
"2021-09-15T20:47:39Z"
"2021-09-21T23:49:10Z"
0f60b3e9446f5d0fc14a570998c81a5d6c40cc23
8cda7462843d43d9b72039eede2f4cb43126cac2
Fix partial method doc comments. Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
./src/EditorFeatures/VisualBasic/AutomaticCompletion/AutomaticLineEnderCommandHandler.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.ComponentModel.Composition Imports System.Threading Imports Microsoft.CodeAnalysis.Editor.Implementation.AutomaticCompletion Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.Text Imports Microsoft.VisualStudio.Commanding Imports Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion Imports Microsoft.VisualStudio.Text.Editor.Commanding.Commands Imports Microsoft.VisualStudio.Text.Operations Imports Microsoft.VisualStudio.Utilities Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.AutomaticCompletion ' <summary> ' visual basic automatic line ender command handler ' </summary> <Export(GetType(ICommandHandler))> <ContentType(ContentTypeNames.VisualBasicContentType)> <Name(PredefinedCommandHandlerNames.AutomaticLineEnder)> <Order(Before:=PredefinedCompletionNames.CompletionCommandHandler)> Friend Class AutomaticLineEnderCommandHandler Inherits AbstractAutomaticLineEnderCommandHandler <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New(undoRegistry As ITextUndoHistoryRegistry, editorOperations As IEditorOperationsFactoryService) MyBase.New(undoRegistry, editorOperations) End Sub Protected Overrides Sub NextAction(editorOperation As IEditorOperations, nextAction As Action) ' let the next action run nextAction() End Sub Protected Overrides Function TreatAsReturn(document As Document, caretPosition As Integer, cancellationToken As CancellationToken) As Boolean ' No special handling in VB. Return False End Function Protected Overrides Sub ModifySelectedNode(args as AutomaticLineEnderCommandArgs, document As Document, selectedNode As SyntaxNode, addBrace As Boolean, caretPosition As Integer, cancellationToken As CancellationToken) End Sub Protected Overrides Function GetValidNodeToModifyBraces(document As Document, caretPosition As Integer, cancellationToken As CancellationToken) As (SyntaxNode, Boolean)? Return Nothing End Function Protected Overrides Function FormatAndApplyBasedOnEndToken(document As Document, position As Integer, cancellationToken As CancellationToken) As Document ' vb does automatic line commit ' no need to do explicit formatting Return document End Function Protected Overrides Function GetEndingString(document As Document, position As Integer, cancellationToken As CancellationToken) As String ' prepare expansive information from document Dim root = document.GetSyntaxRootSynchronously(cancellationToken) Dim text = root.SyntaxTree.GetText(cancellationToken) ' get line where the caret is on Dim line = text.Lines.GetLineFromPosition(position) ' find line break token if there is one Dim lastToken = CType(root.FindTokenOnLeftOfPosition(line.End, includeSkipped:=False), SyntaxToken) lastToken = If(lastToken.Kind = SyntaxKind.EndOfFileToken, lastToken.GetPreviousToken(includeZeroWidth:=True), lastToken) ' find last token of the line If lastToken.Kind = SyntaxKind.None OrElse line.End < lastToken.Span.End Then Return Nothing End If ' properly ended If Not lastToken.IsMissing AndAlso lastToken.IsLastTokenOfStatementWithEndOfLine() Then Return Nothing End If ' so far so good. check whether we need to add explicit line continuation here Dim nonMissingToken = If(lastToken.IsMissing, lastToken.GetPreviousToken(), lastToken) ' now we have the last token, check whether it is at a valid location If (line.Span.Contains(nonMissingToken.Span.End)) Then ' make sure that there is no trailing text after last token on the line if it is not at the end of the line Dim endingString = text.ToString(TextSpan.FromBounds(nonMissingToken.Span.End, line.End)) If Not String.IsNullOrWhiteSpace(endingString) Then Return Nothing End If End If ' check whether implicit line continuation is allowed If SyntaxFacts.AllowsTrailingImplicitLineContinuation(CType(nonMissingToken, SyntaxToken)) Then Return Nothing End If Dim nextToken = nonMissingToken.GetNextToken(includeZeroWidth:=True) ' if there is skipped token between previous and next token, don't do anything If nonMissingToken.TrailingTrivia.Concat(nextToken.LeadingTrivia).Any(AddressOf HasSkippedText) Then Return Nothing End If If nextToken.IsLastTokenOfStatementWithEndOfLine() Then Return " _" End If Dim nextNonMissingToken = nextToken.GetNextNonZeroWidthTokenOrEndOfFile() If nextNonMissingToken.Kind = SyntaxKind.EndOfFileToken Then Return Nothing End If Return If(SyntaxFacts.AllowsLeadingImplicitLineContinuation(CType(nextToken, SyntaxToken)), Nothing, " _") End Function Private Shared Function HasSkippedText(trivia As SyntaxTrivia) As Boolean Return trivia.Kind = SyntaxKind.SkippedTokensTrivia End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.ComponentModel.Composition Imports System.Threading Imports Microsoft.CodeAnalysis.Editor.Implementation.AutomaticCompletion Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.Text Imports Microsoft.VisualStudio.Commanding Imports Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion Imports Microsoft.VisualStudio.Text.Editor.Commanding.Commands Imports Microsoft.VisualStudio.Text.Operations Imports Microsoft.VisualStudio.Utilities Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.AutomaticCompletion ' <summary> ' visual basic automatic line ender command handler ' </summary> <Export(GetType(ICommandHandler))> <ContentType(ContentTypeNames.VisualBasicContentType)> <Name(PredefinedCommandHandlerNames.AutomaticLineEnder)> <Order(Before:=PredefinedCompletionNames.CompletionCommandHandler)> Friend Class AutomaticLineEnderCommandHandler Inherits AbstractAutomaticLineEnderCommandHandler <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New(undoRegistry As ITextUndoHistoryRegistry, editorOperations As IEditorOperationsFactoryService) MyBase.New(undoRegistry, editorOperations) End Sub Protected Overrides Sub NextAction(editorOperation As IEditorOperations, nextAction As Action) ' let the next action run nextAction() End Sub Protected Overrides Function TreatAsReturn(document As Document, caretPosition As Integer, cancellationToken As CancellationToken) As Boolean ' No special handling in VB. Return False End Function Protected Overrides Sub ModifySelectedNode(args as AutomaticLineEnderCommandArgs, document As Document, selectedNode As SyntaxNode, addBrace As Boolean, caretPosition As Integer, cancellationToken As CancellationToken) End Sub Protected Overrides Function GetValidNodeToModifyBraces(document As Document, caretPosition As Integer, cancellationToken As CancellationToken) As (SyntaxNode, Boolean)? Return Nothing End Function Protected Overrides Function FormatAndApplyBasedOnEndToken(document As Document, position As Integer, cancellationToken As CancellationToken) As Document ' vb does automatic line commit ' no need to do explicit formatting Return document End Function Protected Overrides Function GetEndingString(document As Document, position As Integer, cancellationToken As CancellationToken) As String ' prepare expansive information from document Dim root = document.GetSyntaxRootSynchronously(cancellationToken) Dim text = root.SyntaxTree.GetText(cancellationToken) ' get line where the caret is on Dim line = text.Lines.GetLineFromPosition(position) ' find line break token if there is one Dim lastToken = CType(root.FindTokenOnLeftOfPosition(line.End, includeSkipped:=False), SyntaxToken) lastToken = If(lastToken.Kind = SyntaxKind.EndOfFileToken, lastToken.GetPreviousToken(includeZeroWidth:=True), lastToken) ' find last token of the line If lastToken.Kind = SyntaxKind.None OrElse line.End < lastToken.Span.End Then Return Nothing End If ' properly ended If Not lastToken.IsMissing AndAlso lastToken.IsLastTokenOfStatementWithEndOfLine() Then Return Nothing End If ' so far so good. check whether we need to add explicit line continuation here Dim nonMissingToken = If(lastToken.IsMissing, lastToken.GetPreviousToken(), lastToken) ' now we have the last token, check whether it is at a valid location If (line.Span.Contains(nonMissingToken.Span.End)) Then ' make sure that there is no trailing text after last token on the line if it is not at the end of the line Dim endingString = text.ToString(TextSpan.FromBounds(nonMissingToken.Span.End, line.End)) If Not String.IsNullOrWhiteSpace(endingString) Then Return Nothing End If End If ' check whether implicit line continuation is allowed If SyntaxFacts.AllowsTrailingImplicitLineContinuation(CType(nonMissingToken, SyntaxToken)) Then Return Nothing End If Dim nextToken = nonMissingToken.GetNextToken(includeZeroWidth:=True) ' if there is skipped token between previous and next token, don't do anything If nonMissingToken.TrailingTrivia.Concat(nextToken.LeadingTrivia).Any(AddressOf HasSkippedText) Then Return Nothing End If If nextToken.IsLastTokenOfStatementWithEndOfLine() Then Return " _" End If Dim nextNonMissingToken = nextToken.GetNextNonZeroWidthTokenOrEndOfFile() If nextNonMissingToken.Kind = SyntaxKind.EndOfFileToken Then Return Nothing End If Return If(SyntaxFacts.AllowsLeadingImplicitLineContinuation(CType(nextToken, SyntaxToken)), Nothing, " _") End Function Private Shared Function HasSkippedText(trivia As SyntaxTrivia) As Boolean Return trivia.Kind = SyntaxKind.SkippedTokensTrivia End Function End Class End Namespace
-1
dotnet/roslyn
56,419
Fix partial method doc comments
Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
RikkiGibson
"2021-09-15T20:47:39Z"
"2021-09-21T23:49:10Z"
0f60b3e9446f5d0fc14a570998c81a5d6c40cc23
8cda7462843d43d9b72039eede2f4cb43126cac2
Fix partial method doc comments. Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
./src/Scripting/VisualBasicTest/PrintOptionsTests.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.Scripting.Hosting Imports Microsoft.CodeAnalysis.Scripting.Hosting.UnitTests Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.Scripting.Hosting.UnitTests Public Class PrintOptionsTests Inherits ObjectFormatterTestBase Private Shared ReadOnly s_formatter As ObjectFormatter = New TestVisualBasicObjectFormatter() <Fact> Public Sub NullOptions() Assert.Throws(Of ArgumentNullException)(Sub() s_formatter.FormatObject("hello", options:=Nothing)) End Sub <Fact> Public Sub InvalidNumberRadix() Assert.Throws(Of ArgumentOutOfRangeException)( Sub() Dim options As New PrintOptions() options.NumberRadix = 3 End Sub) End Sub <Fact> Public Sub InvalidMemberDisplayFormat() Assert.Throws(Of ArgumentOutOfRangeException)( Sub() Dim options As New PrintOptions() options.MemberDisplayFormat = CType(-1, MemberDisplayFormat) End Sub) End Sub <Fact> Public Sub InvalidMaximumOutputLength() Assert.Throws(Of ArgumentOutOfRangeException)( Sub() Dim options As New PrintOptions() options.MaximumOutputLength = -1 End Sub) Assert.Throws(Of ArgumentOutOfRangeException)( Sub() Dim options As New PrintOptions() options.MaximumOutputLength = 0 End Sub) End Sub <Fact> Public Sub ValidNumberRadix() Dim options = New PrintOptions() Dim array(9) As Integer options.NumberRadix = 10 Assert.Equal("10", s_formatter.FormatObject(10, options)) Assert.Equal("Integer(10) { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }", s_formatter.FormatObject(array, options)) Assert.Equal("ChrW(16)", s_formatter.FormatObject(ChrW(&H10), options)) options.NumberRadix = 16 Assert.Equal("&H0000000A", s_formatter.FormatObject(10, options)) Assert.Equal("Integer(&H0000000A) { &H00000000, &H00000000, &H00000000, &H00000000, &H00000000, &H00000000, &H00000000, &H00000000, &H00000000, &H00000000 }", s_formatter.FormatObject(array, options)) Assert.Equal("ChrW(&H10)", s_formatter.FormatObject(ChrW(&H10), options)) End Sub <Fact(Skip:="https://github.com/dotnet/roslyn/issues/8241")> Public Sub ValidMemberDisplayFormat() Dim options = New PrintOptions() options.MemberDisplayFormat = MemberDisplayFormat.Hidden Assert.Equal("PrintOptions", s_formatter.FormatObject(options, options)) options.MemberDisplayFormat = MemberDisplayFormat.SingleLine Assert.Equal("PrintOptions { Ellipsis=""..."", EscapeNonPrintableCharacters=True, MaximumOutputLength=1024, MemberDisplayFormat=SingleLine, NumberRadix=10 }", s_formatter.FormatObject(options, options)) options.MemberDisplayFormat = MemberDisplayFormat.SeparateLines Assert.Equal("PrintOptions { Ellipsis: ""..."", EscapeNonPrintableCharacters: True, MaximumOutputLength: 1024, MemberDisplayFormat: SeparateLines, NumberRadix: 10, _maximumOutputLength: 1024, _memberDisplayFormat: SeparateLines, _numberRadix: 10 } ", s_formatter.FormatObject(options, options)) End Sub <Fact> Public Sub ValidEscapeNonPrintableCharacters() Dim options = New PrintOptions() options.EscapeNonPrintableCharacters = True Assert.Equal("vbTab", s_formatter.FormatObject(vbTab, options)) Assert.Equal("vbTab", s_formatter.FormatObject(vbTab(0), options)) options.EscapeNonPrintableCharacters = False Assert.Equal("""" + vbTab + """", s_formatter.FormatObject(vbTab, options)) Assert.Equal("""" + vbTab + """c", s_formatter.FormatObject(vbTab(0), options)) End Sub <Fact> Public Sub ValidMaximumOutputLength() Dim options = New PrintOptions() options.MaximumOutputLength = 1 Assert.Equal("1...", s_formatter.FormatObject(123456, options)) options.MaximumOutputLength = 2 Assert.Equal("12...", s_formatter.FormatObject(123456, options)) options.MaximumOutputLength = 3 Assert.Equal("123...", s_formatter.FormatObject(123456, options)) options.MaximumOutputLength = 4 Assert.Equal("1234...", s_formatter.FormatObject(123456, options)) options.MaximumOutputLength = 5 Assert.Equal("12345...", s_formatter.FormatObject(123456, options)) options.MaximumOutputLength = 6 Assert.Equal("123456", s_formatter.FormatObject(123456, options)) options.MaximumOutputLength = 7 Assert.Equal("123456", s_formatter.FormatObject(123456, options)) End Sub <Fact> Public Sub ValidEllipsis() Dim options = New PrintOptions() options.MaximumOutputLength = 1 options.Ellipsis = "." Assert.Equal("1.", s_formatter.FormatObject(123456, options)) options.Ellipsis = ".." Assert.Equal("1..", s_formatter.FormatObject(123456, options)) options.Ellipsis = "" Assert.Equal("1", s_formatter.FormatObject(123456, options)) options.Ellipsis = Nothing Assert.Equal("1", s_formatter.FormatObject(123456, options)) End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Scripting.Hosting Imports Microsoft.CodeAnalysis.Scripting.Hosting.UnitTests Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.Scripting.Hosting.UnitTests Public Class PrintOptionsTests Inherits ObjectFormatterTestBase Private Shared ReadOnly s_formatter As ObjectFormatter = New TestVisualBasicObjectFormatter() <Fact> Public Sub NullOptions() Assert.Throws(Of ArgumentNullException)(Sub() s_formatter.FormatObject("hello", options:=Nothing)) End Sub <Fact> Public Sub InvalidNumberRadix() Assert.Throws(Of ArgumentOutOfRangeException)( Sub() Dim options As New PrintOptions() options.NumberRadix = 3 End Sub) End Sub <Fact> Public Sub InvalidMemberDisplayFormat() Assert.Throws(Of ArgumentOutOfRangeException)( Sub() Dim options As New PrintOptions() options.MemberDisplayFormat = CType(-1, MemberDisplayFormat) End Sub) End Sub <Fact> Public Sub InvalidMaximumOutputLength() Assert.Throws(Of ArgumentOutOfRangeException)( Sub() Dim options As New PrintOptions() options.MaximumOutputLength = -1 End Sub) Assert.Throws(Of ArgumentOutOfRangeException)( Sub() Dim options As New PrintOptions() options.MaximumOutputLength = 0 End Sub) End Sub <Fact> Public Sub ValidNumberRadix() Dim options = New PrintOptions() Dim array(9) As Integer options.NumberRadix = 10 Assert.Equal("10", s_formatter.FormatObject(10, options)) Assert.Equal("Integer(10) { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }", s_formatter.FormatObject(array, options)) Assert.Equal("ChrW(16)", s_formatter.FormatObject(ChrW(&H10), options)) options.NumberRadix = 16 Assert.Equal("&H0000000A", s_formatter.FormatObject(10, options)) Assert.Equal("Integer(&H0000000A) { &H00000000, &H00000000, &H00000000, &H00000000, &H00000000, &H00000000, &H00000000, &H00000000, &H00000000, &H00000000 }", s_formatter.FormatObject(array, options)) Assert.Equal("ChrW(&H10)", s_formatter.FormatObject(ChrW(&H10), options)) End Sub <Fact(Skip:="https://github.com/dotnet/roslyn/issues/8241")> Public Sub ValidMemberDisplayFormat() Dim options = New PrintOptions() options.MemberDisplayFormat = MemberDisplayFormat.Hidden Assert.Equal("PrintOptions", s_formatter.FormatObject(options, options)) options.MemberDisplayFormat = MemberDisplayFormat.SingleLine Assert.Equal("PrintOptions { Ellipsis=""..."", EscapeNonPrintableCharacters=True, MaximumOutputLength=1024, MemberDisplayFormat=SingleLine, NumberRadix=10 }", s_formatter.FormatObject(options, options)) options.MemberDisplayFormat = MemberDisplayFormat.SeparateLines Assert.Equal("PrintOptions { Ellipsis: ""..."", EscapeNonPrintableCharacters: True, MaximumOutputLength: 1024, MemberDisplayFormat: SeparateLines, NumberRadix: 10, _maximumOutputLength: 1024, _memberDisplayFormat: SeparateLines, _numberRadix: 10 } ", s_formatter.FormatObject(options, options)) End Sub <Fact> Public Sub ValidEscapeNonPrintableCharacters() Dim options = New PrintOptions() options.EscapeNonPrintableCharacters = True Assert.Equal("vbTab", s_formatter.FormatObject(vbTab, options)) Assert.Equal("vbTab", s_formatter.FormatObject(vbTab(0), options)) options.EscapeNonPrintableCharacters = False Assert.Equal("""" + vbTab + """", s_formatter.FormatObject(vbTab, options)) Assert.Equal("""" + vbTab + """c", s_formatter.FormatObject(vbTab(0), options)) End Sub <Fact> Public Sub ValidMaximumOutputLength() Dim options = New PrintOptions() options.MaximumOutputLength = 1 Assert.Equal("1...", s_formatter.FormatObject(123456, options)) options.MaximumOutputLength = 2 Assert.Equal("12...", s_formatter.FormatObject(123456, options)) options.MaximumOutputLength = 3 Assert.Equal("123...", s_formatter.FormatObject(123456, options)) options.MaximumOutputLength = 4 Assert.Equal("1234...", s_formatter.FormatObject(123456, options)) options.MaximumOutputLength = 5 Assert.Equal("12345...", s_formatter.FormatObject(123456, options)) options.MaximumOutputLength = 6 Assert.Equal("123456", s_formatter.FormatObject(123456, options)) options.MaximumOutputLength = 7 Assert.Equal("123456", s_formatter.FormatObject(123456, options)) End Sub <Fact> Public Sub ValidEllipsis() Dim options = New PrintOptions() options.MaximumOutputLength = 1 options.Ellipsis = "." Assert.Equal("1.", s_formatter.FormatObject(123456, options)) options.Ellipsis = ".." Assert.Equal("1..", s_formatter.FormatObject(123456, options)) options.Ellipsis = "" Assert.Equal("1", s_formatter.FormatObject(123456, options)) options.Ellipsis = Nothing Assert.Equal("1", s_formatter.FormatObject(123456, options)) End Sub End Class End Namespace
-1
dotnet/roslyn
56,419
Fix partial method doc comments
Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
RikkiGibson
"2021-09-15T20:47:39Z"
"2021-09-21T23:49:10Z"
0f60b3e9446f5d0fc14a570998c81a5d6c40cc23
8cda7462843d43d9b72039eede2f4cb43126cac2
Fix partial method doc comments. Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
./src/Workspaces/Core/Portable/TemporaryStorage/TemporaryStorageServiceFactory.MemoryMappedInfo.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.IO; using System.IO.MemoryMappedFiles; using System.Runtime; using System.Runtime.InteropServices; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Host { internal partial class TemporaryStorageServiceFactory { /// <summary> /// Our own abstraction on top of memory map file so that we can have shared views over mmf files. /// Otherwise, each view has minimum size of 64K due to requirement forced by windows. /// /// most of our view will have short lifetime, but there are cases where view might live a bit longer such as /// metadata dll shadow copy. shared view will help those cases. /// </summary> /// <remarks> /// <para>Instances of this class should be disposed when they are no longer needed. After disposing this /// instance, it should no longer be used. However, streams obtained through <see cref="CreateReadableStream"/> /// or <see cref="CreateWritableStream"/> will not be invalidated until they are disposed independently (which /// may occur before or after the <see cref="MemoryMappedInfo"/> is disposed.</para> /// /// <para>This class and its nested types have familiar APIs and predictable behavior when used in other code, /// but are non-trivial to work on. The implementations of <see cref="IDisposable"/> adhere to the best /// practices described in /// <see href="http://joeduffyblog.com/2005/04/08/dg-update-dispose-finalization-and-resource-management/">DG /// Update: Dispose, Finalization, and Resource Management</see>. Additional notes regarding operating system /// behavior leveraged for efficiency are given in comments.</para> /// </remarks> internal sealed class MemoryMappedInfo : IDisposable { /// <summary> /// The memory mapped file. /// </summary> /// <remarks> /// <para>It is possible for the file to be disposed prior to the view and/or the streams which use it. /// However, the operating system does not actually close the views which are in use until the file handles /// are closed as well, even if the file is disposed first.</para> /// </remarks> private readonly ReferenceCountedDisposable<MemoryMappedFile> _memoryMappedFile; /// <summary> /// A weak reference to a read-only view for the memory mapped file. /// </summary> /// <remarks> /// <para>This holds a weak counted reference to current <see cref="MemoryMappedViewAccessor"/>, which /// allows additional accessors for the same address space to be obtained up until the point when no /// external code is using it. When the memory is no longer being used by any /// <see cref="SharedReadableStream"/> objects, the view of the memory mapped file is unmapped, making the /// process address space it previously claimed available for other purposes. If/when it is needed again, a /// new view is created.</para> /// /// <para>This view is read-only, so it is only used by <see cref="CreateReadableStream"/>.</para> /// </remarks> private ReferenceCountedDisposable<MemoryMappedViewAccessor>.WeakReference _weakReadAccessor; public MemoryMappedInfo(ReferenceCountedDisposable<MemoryMappedFile> memoryMappedFile, string name, long offset, long size) { _memoryMappedFile = memoryMappedFile; Name = name; Offset = offset; Size = size; } public MemoryMappedInfo(string name, long offset, long size) : this(new ReferenceCountedDisposable<MemoryMappedFile>(MemoryMappedFile.OpenExisting(name)), name, offset, size) { } /// <summary> /// The name of the memory mapped file. /// </summary> public string Name { get; } /// <summary> /// The offset into the memory mapped file of the region described by the current /// <see cref="MemoryMappedInfo"/>. /// </summary> public long Offset { get; } /// <summary> /// The size of the region of the memory mapped file described by the current /// <see cref="MemoryMappedInfo"/>. /// </summary> public long Size { get; } /// <summary> /// Caller is responsible for disposing the returned stream. /// multiple call of this will not increase VM. /// </summary> public Stream CreateReadableStream() { // Note: TryAddReference behaves according to its documentation even if the target object has been // disposed. If it returns non-null, then the object will not be disposed before the returned // reference is disposed (see comments on _memoryMappedFile and TryAddReference). var streamAccessor = _weakReadAccessor.TryAddReference(); if (streamAccessor == null) { var rawAccessor = RunWithCompactingGCFallback( static info => { using var memoryMappedFile = info._memoryMappedFile.TryAddReference(); if (memoryMappedFile is null) throw new ObjectDisposedException(typeof(MemoryMappedInfo).FullName); return memoryMappedFile.Target.CreateViewAccessor(info.Offset, info.Size, MemoryMappedFileAccess.Read); }, this); streamAccessor = new ReferenceCountedDisposable<MemoryMappedViewAccessor>(rawAccessor); _weakReadAccessor = new ReferenceCountedDisposable<MemoryMappedViewAccessor>.WeakReference(streamAccessor); } Debug.Assert(streamAccessor.Target.CanRead); return new SharedReadableStream(streamAccessor, Size); } /// <summary> /// Caller is responsible for disposing the returned stream. /// multiple call of this will increase VM. /// </summary> public Stream CreateWritableStream() { return RunWithCompactingGCFallback( static info => { using var memoryMappedFile = info._memoryMappedFile.TryAddReference(); if (memoryMappedFile is null) throw new ObjectDisposedException(typeof(MemoryMappedInfo).FullName); return memoryMappedFile.Target.CreateViewStream(info.Offset, info.Size, MemoryMappedFileAccess.Write); }, this); } /// <summary> /// Run a function which may fail with an <see cref="IOException"/> if not enough memory is available to /// satisfy the request. In this case, a full compacting GC pass is forced and the function is attempted /// again. /// </summary> /// <remarks> /// <para><see cref="MemoryMappedFile.CreateViewAccessor(long, long, MemoryMappedFileAccess)"/> and /// <see cref="MemoryMappedFile.CreateViewStream(long, long, MemoryMappedFileAccess)"/> will use a native /// memory map, which can't trigger a GC. In this case, we'd otherwise crash with OOM, so we don't care /// about creating a UI delay with a full forced compacting GC. If it crashes the second try, it means we're /// legitimately out of resources.</para> /// </remarks> /// <typeparam name="TArg">The type of argument to pass to the callback.</typeparam> /// <typeparam name="T">The type returned by the function.</typeparam> /// <param name="function">The function to execute.</param> /// <param name="argument">The argument to pass to the function.</param> /// <returns>The value returned by <paramref name="function"/>.</returns> private static T RunWithCompactingGCFallback<TArg, T>(Func<TArg, T> function, TArg argument) { try { return function(argument); } catch (IOException) { ForceCompactingGC(); return function(argument); } } private static void ForceCompactingGC() { // repeated GC.Collect / WaitForPendingFinalizers till memory freed delta is super small, ignore the return value GC.GetTotalMemory(forceFullCollection: true); // compact the LOH GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce; GC.Collect(); } public void Dispose() { // See remarks on field for relation between _memoryMappedFile and the views/streams. There is no // need to write _weakReadAccessor here since lifetime of the target is not owned by this instance. _memoryMappedFile.Dispose(); } private sealed unsafe class SharedReadableStream : Stream, ISupportDirectMemoryAccess { private readonly ReferenceCountedDisposable<MemoryMappedViewAccessor> _accessor; private byte* _start; private byte* _current; private readonly byte* _end; public SharedReadableStream(ReferenceCountedDisposable<MemoryMappedViewAccessor> accessor, long length) { _accessor = accessor; _current = _start = (byte*)_accessor.Target.SafeMemoryMappedViewHandle.DangerousGetHandle() + _accessor.Target.PointerOffset; _end = checked(_start + length); } public override bool CanRead => true; public override bool CanSeek => true; public override bool CanWrite => false; public override long Length => _end - _start; public override long Position { get { return _current - _start; } set { var target = _start + value; if (target < _start || target >= _end) { throw new ArgumentOutOfRangeException(nameof(value)); } _current = target; } } public override int ReadByte() { // PERF: Keeping this as simple as possible since it's on the hot path if (_current >= _end) { return -1; } return *_current++; } public override int Read(byte[] buffer, int offset, int count) { if (_current >= _end) { return 0; } var adjustedCount = Math.Min(count, (int)(_end - _current)); Marshal.Copy((IntPtr)_current, buffer, offset, adjustedCount); _current += adjustedCount; return adjustedCount; } public override long Seek(long offset, SeekOrigin origin) { byte* target; try { target = origin switch { SeekOrigin.Begin => checked(_start + offset), SeekOrigin.Current => checked(_current + offset), SeekOrigin.End => checked(_end + offset), _ => throw new ArgumentOutOfRangeException(nameof(origin)), }; } catch (OverflowException) { throw new ArgumentOutOfRangeException(nameof(offset)); } if (target < _start || target >= _end) { throw new ArgumentOutOfRangeException(nameof(offset)); } _current = target; return _current - _start; } public override void Flush() => throw new NotSupportedException(); public override void SetLength(long value) => throw new NotSupportedException(); public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); protected override void Dispose(bool disposing) { base.Dispose(disposing); if (disposing) { _accessor.Dispose(); } _start = null; } /// <summary> /// Get underlying native memory directly. /// </summary> public IntPtr GetPointer() => (IntPtr)_start; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.IO; using System.IO.MemoryMappedFiles; using System.Runtime; using System.Runtime.InteropServices; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Host { internal partial class TemporaryStorageServiceFactory { /// <summary> /// Our own abstraction on top of memory map file so that we can have shared views over mmf files. /// Otherwise, each view has minimum size of 64K due to requirement forced by windows. /// /// most of our view will have short lifetime, but there are cases where view might live a bit longer such as /// metadata dll shadow copy. shared view will help those cases. /// </summary> /// <remarks> /// <para>Instances of this class should be disposed when they are no longer needed. After disposing this /// instance, it should no longer be used. However, streams obtained through <see cref="CreateReadableStream"/> /// or <see cref="CreateWritableStream"/> will not be invalidated until they are disposed independently (which /// may occur before or after the <see cref="MemoryMappedInfo"/> is disposed.</para> /// /// <para>This class and its nested types have familiar APIs and predictable behavior when used in other code, /// but are non-trivial to work on. The implementations of <see cref="IDisposable"/> adhere to the best /// practices described in /// <see href="http://joeduffyblog.com/2005/04/08/dg-update-dispose-finalization-and-resource-management/">DG /// Update: Dispose, Finalization, and Resource Management</see>. Additional notes regarding operating system /// behavior leveraged for efficiency are given in comments.</para> /// </remarks> internal sealed class MemoryMappedInfo : IDisposable { /// <summary> /// The memory mapped file. /// </summary> /// <remarks> /// <para>It is possible for the file to be disposed prior to the view and/or the streams which use it. /// However, the operating system does not actually close the views which are in use until the file handles /// are closed as well, even if the file is disposed first.</para> /// </remarks> private readonly ReferenceCountedDisposable<MemoryMappedFile> _memoryMappedFile; /// <summary> /// A weak reference to a read-only view for the memory mapped file. /// </summary> /// <remarks> /// <para>This holds a weak counted reference to current <see cref="MemoryMappedViewAccessor"/>, which /// allows additional accessors for the same address space to be obtained up until the point when no /// external code is using it. When the memory is no longer being used by any /// <see cref="SharedReadableStream"/> objects, the view of the memory mapped file is unmapped, making the /// process address space it previously claimed available for other purposes. If/when it is needed again, a /// new view is created.</para> /// /// <para>This view is read-only, so it is only used by <see cref="CreateReadableStream"/>.</para> /// </remarks> private ReferenceCountedDisposable<MemoryMappedViewAccessor>.WeakReference _weakReadAccessor; public MemoryMappedInfo(ReferenceCountedDisposable<MemoryMappedFile> memoryMappedFile, string name, long offset, long size) { _memoryMappedFile = memoryMappedFile; Name = name; Offset = offset; Size = size; } public MemoryMappedInfo(string name, long offset, long size) : this(new ReferenceCountedDisposable<MemoryMappedFile>(MemoryMappedFile.OpenExisting(name)), name, offset, size) { } /// <summary> /// The name of the memory mapped file. /// </summary> public string Name { get; } /// <summary> /// The offset into the memory mapped file of the region described by the current /// <see cref="MemoryMappedInfo"/>. /// </summary> public long Offset { get; } /// <summary> /// The size of the region of the memory mapped file described by the current /// <see cref="MemoryMappedInfo"/>. /// </summary> public long Size { get; } /// <summary> /// Caller is responsible for disposing the returned stream. /// multiple call of this will not increase VM. /// </summary> public Stream CreateReadableStream() { // Note: TryAddReference behaves according to its documentation even if the target object has been // disposed. If it returns non-null, then the object will not be disposed before the returned // reference is disposed (see comments on _memoryMappedFile and TryAddReference). var streamAccessor = _weakReadAccessor.TryAddReference(); if (streamAccessor == null) { var rawAccessor = RunWithCompactingGCFallback( static info => { using var memoryMappedFile = info._memoryMappedFile.TryAddReference(); if (memoryMappedFile is null) throw new ObjectDisposedException(typeof(MemoryMappedInfo).FullName); return memoryMappedFile.Target.CreateViewAccessor(info.Offset, info.Size, MemoryMappedFileAccess.Read); }, this); streamAccessor = new ReferenceCountedDisposable<MemoryMappedViewAccessor>(rawAccessor); _weakReadAccessor = new ReferenceCountedDisposable<MemoryMappedViewAccessor>.WeakReference(streamAccessor); } Debug.Assert(streamAccessor.Target.CanRead); return new SharedReadableStream(streamAccessor, Size); } /// <summary> /// Caller is responsible for disposing the returned stream. /// multiple call of this will increase VM. /// </summary> public Stream CreateWritableStream() { return RunWithCompactingGCFallback( static info => { using var memoryMappedFile = info._memoryMappedFile.TryAddReference(); if (memoryMappedFile is null) throw new ObjectDisposedException(typeof(MemoryMappedInfo).FullName); return memoryMappedFile.Target.CreateViewStream(info.Offset, info.Size, MemoryMappedFileAccess.Write); }, this); } /// <summary> /// Run a function which may fail with an <see cref="IOException"/> if not enough memory is available to /// satisfy the request. In this case, a full compacting GC pass is forced and the function is attempted /// again. /// </summary> /// <remarks> /// <para><see cref="MemoryMappedFile.CreateViewAccessor(long, long, MemoryMappedFileAccess)"/> and /// <see cref="MemoryMappedFile.CreateViewStream(long, long, MemoryMappedFileAccess)"/> will use a native /// memory map, which can't trigger a GC. In this case, we'd otherwise crash with OOM, so we don't care /// about creating a UI delay with a full forced compacting GC. If it crashes the second try, it means we're /// legitimately out of resources.</para> /// </remarks> /// <typeparam name="TArg">The type of argument to pass to the callback.</typeparam> /// <typeparam name="T">The type returned by the function.</typeparam> /// <param name="function">The function to execute.</param> /// <param name="argument">The argument to pass to the function.</param> /// <returns>The value returned by <paramref name="function"/>.</returns> private static T RunWithCompactingGCFallback<TArg, T>(Func<TArg, T> function, TArg argument) { try { return function(argument); } catch (IOException) { ForceCompactingGC(); return function(argument); } } private static void ForceCompactingGC() { // repeated GC.Collect / WaitForPendingFinalizers till memory freed delta is super small, ignore the return value GC.GetTotalMemory(forceFullCollection: true); // compact the LOH GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce; GC.Collect(); } public void Dispose() { // See remarks on field for relation between _memoryMappedFile and the views/streams. There is no // need to write _weakReadAccessor here since lifetime of the target is not owned by this instance. _memoryMappedFile.Dispose(); } private sealed unsafe class SharedReadableStream : Stream, ISupportDirectMemoryAccess { private readonly ReferenceCountedDisposable<MemoryMappedViewAccessor> _accessor; private byte* _start; private byte* _current; private readonly byte* _end; public SharedReadableStream(ReferenceCountedDisposable<MemoryMappedViewAccessor> accessor, long length) { _accessor = accessor; _current = _start = (byte*)_accessor.Target.SafeMemoryMappedViewHandle.DangerousGetHandle() + _accessor.Target.PointerOffset; _end = checked(_start + length); } public override bool CanRead => true; public override bool CanSeek => true; public override bool CanWrite => false; public override long Length => _end - _start; public override long Position { get { return _current - _start; } set { var target = _start + value; if (target < _start || target >= _end) { throw new ArgumentOutOfRangeException(nameof(value)); } _current = target; } } public override int ReadByte() { // PERF: Keeping this as simple as possible since it's on the hot path if (_current >= _end) { return -1; } return *_current++; } public override int Read(byte[] buffer, int offset, int count) { if (_current >= _end) { return 0; } var adjustedCount = Math.Min(count, (int)(_end - _current)); Marshal.Copy((IntPtr)_current, buffer, offset, adjustedCount); _current += adjustedCount; return adjustedCount; } public override long Seek(long offset, SeekOrigin origin) { byte* target; try { target = origin switch { SeekOrigin.Begin => checked(_start + offset), SeekOrigin.Current => checked(_current + offset), SeekOrigin.End => checked(_end + offset), _ => throw new ArgumentOutOfRangeException(nameof(origin)), }; } catch (OverflowException) { throw new ArgumentOutOfRangeException(nameof(offset)); } if (target < _start || target >= _end) { throw new ArgumentOutOfRangeException(nameof(offset)); } _current = target; return _current - _start; } public override void Flush() => throw new NotSupportedException(); public override void SetLength(long value) => throw new NotSupportedException(); public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); protected override void Dispose(bool disposing) { base.Dispose(disposing); if (disposing) { _accessor.Dispose(); } _start = null; } /// <summary> /// Get underlying native memory directly. /// </summary> public IntPtr GetPointer() => (IntPtr)_start; } } } }
-1
dotnet/roslyn
56,419
Fix partial method doc comments
Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
RikkiGibson
"2021-09-15T20:47:39Z"
"2021-09-21T23:49:10Z"
0f60b3e9446f5d0fc14a570998c81a5d6c40cc23
8cda7462843d43d9b72039eede2f4cb43126cac2
Fix partial method doc comments. Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
./src/VisualStudio/Core/Def/Implementation/InheritanceMargin/MarginGlyph/InheritanceMarginContextMenu.xaml.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Globalization; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.FindUsages; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.InheritanceMargin.MarginGlyph { /// <summary> /// Interaction logic for InheritanceMarginContextMenu.xaml /// </summary> internal partial class InheritanceMarginContextMenu : ContextMenu { private readonly IThreadingContext _threadingContext; private readonly IStreamingFindUsagesPresenter _streamingFindUsagesPresenter; private readonly IUIThreadOperationExecutor _operationExecutor; private readonly Workspace _workspace; private readonly IWpfTextView _textView; private readonly IAsynchronousOperationListener _listener; public InheritanceMarginContextMenu( IThreadingContext threadingContext, IStreamingFindUsagesPresenter streamingFindUsagesPresenter, IUIThreadOperationExecutor operationExecutor, Workspace workspace, IWpfTextView textView, IAsynchronousOperationListener listener) { _threadingContext = threadingContext; _streamingFindUsagesPresenter = streamingFindUsagesPresenter; _workspace = workspace; _operationExecutor = operationExecutor; _textView = textView; _listener = listener; InitializeComponent(); } private void TargetMenuItem_OnClick(object sender, RoutedEventArgs e) { if (e.OriginalSource is MenuItem { DataContext: TargetMenuItemViewModel viewModel }) { Logger.Log(FunctionId.InheritanceMargin_NavigateToTarget, KeyValueLogMessage.Create(LogType.UserAction)); var token = _listener.BeginAsyncOperation(nameof(TargetMenuItem_OnClick)); TargetMenuItem_OnClickAsync(viewModel).CompletesAsyncOperation(token); } } private async Task TargetMenuItem_OnClickAsync(TargetMenuItemViewModel viewModel) { using var context = _operationExecutor.BeginExecute( title: EditorFeaturesResources.Navigating, defaultDescription: string.Format(ServicesVSResources.Navigate_to_0, viewModel.DisplayContent), allowCancellation: true, showProgress: false); var cancellationToken = context.UserCancellationToken; var rehydrated = await viewModel.DefinitionItem.TryRehydrateAsync(cancellationToken).ConfigureAwait(false); if (rehydrated == null) return; _ = await _streamingFindUsagesPresenter.TryNavigateToOrPresentItemsAsync( _threadingContext, _workspace, string.Format(CultureInfo.InvariantCulture, EditorFeaturesResources._0_declarations, viewModel.DisplayContent), ImmutableArray.Create<DefinitionItem>(rehydrated), cancellationToken).ConfigureAwait(false); } private void TargetsSubmenu_OnOpen(object sender, RoutedEventArgs e) { Logger.Log(FunctionId.InheritanceMargin_TargetsMenuOpen, KeyValueLogMessage.Create(LogType.UserAction)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Globalization; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.FindUsages; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.InheritanceMargin.MarginGlyph { /// <summary> /// Interaction logic for InheritanceMarginContextMenu.xaml /// </summary> internal partial class InheritanceMarginContextMenu : ContextMenu { private readonly IThreadingContext _threadingContext; private readonly IStreamingFindUsagesPresenter _streamingFindUsagesPresenter; private readonly IUIThreadOperationExecutor _operationExecutor; private readonly Workspace _workspace; private readonly IWpfTextView _textView; private readonly IAsynchronousOperationListener _listener; public InheritanceMarginContextMenu( IThreadingContext threadingContext, IStreamingFindUsagesPresenter streamingFindUsagesPresenter, IUIThreadOperationExecutor operationExecutor, Workspace workspace, IWpfTextView textView, IAsynchronousOperationListener listener) { _threadingContext = threadingContext; _streamingFindUsagesPresenter = streamingFindUsagesPresenter; _workspace = workspace; _operationExecutor = operationExecutor; _textView = textView; _listener = listener; InitializeComponent(); } private void TargetMenuItem_OnClick(object sender, RoutedEventArgs e) { if (e.OriginalSource is MenuItem { DataContext: TargetMenuItemViewModel viewModel }) { Logger.Log(FunctionId.InheritanceMargin_NavigateToTarget, KeyValueLogMessage.Create(LogType.UserAction)); var token = _listener.BeginAsyncOperation(nameof(TargetMenuItem_OnClick)); TargetMenuItem_OnClickAsync(viewModel).CompletesAsyncOperation(token); } } private async Task TargetMenuItem_OnClickAsync(TargetMenuItemViewModel viewModel) { using var context = _operationExecutor.BeginExecute( title: EditorFeaturesResources.Navigating, defaultDescription: string.Format(ServicesVSResources.Navigate_to_0, viewModel.DisplayContent), allowCancellation: true, showProgress: false); var cancellationToken = context.UserCancellationToken; var rehydrated = await viewModel.DefinitionItem.TryRehydrateAsync(cancellationToken).ConfigureAwait(false); if (rehydrated == null) return; _ = await _streamingFindUsagesPresenter.TryNavigateToOrPresentItemsAsync( _threadingContext, _workspace, string.Format(CultureInfo.InvariantCulture, EditorFeaturesResources._0_declarations, viewModel.DisplayContent), ImmutableArray.Create<DefinitionItem>(rehydrated), cancellationToken).ConfigureAwait(false); } private void TargetsSubmenu_OnOpen(object sender, RoutedEventArgs e) { Logger.Log(FunctionId.InheritanceMargin_TargetsMenuOpen, KeyValueLogMessage.Create(LogType.UserAction)); } } }
-1
dotnet/roslyn
56,419
Fix partial method doc comments
Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
RikkiGibson
"2021-09-15T20:47:39Z"
"2021-09-21T23:49:10Z"
0f60b3e9446f5d0fc14a570998c81a5d6c40cc23
8cda7462843d43d9b72039eede2f4cb43126cac2
Fix partial method doc comments. Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
./src/EditorFeatures/CSharpTest/Completion/ArgumentProviders/ContextVariableArgumentProviderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Completion.Providers; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Completion.ArgumentProviders { [Trait(Traits.Feature, Traits.Features.Completion)] public class ContextVariableArgumentProviderTests : AbstractCSharpArgumentProviderTests { internal override Type GetArgumentProviderType() => typeof(ContextVariableArgumentProvider); [Theory] [InlineData("string")] [InlineData("bool")] [InlineData("int?")] public async Task TestLocalVariable(string type) { var markup = $@" class C {{ void Method() {{ {type} arg = default; this.Target($$); }} void Target({type} arg) {{ }} }} "; await VerifyDefaultValueAsync(markup, "arg"); await VerifyDefaultValueAsync(markup, expectedDefaultValue: null, previousDefaultValue: "prior"); } [Theory] [InlineData("string")] [InlineData("bool")] [InlineData("int?")] public async Task TestParameter(string type) { var markup = $@" class C {{ void Method({type} arg) {{ this.Target($$); }} void Target({type} arg) {{ }} }} "; await VerifyDefaultValueAsync(markup, "arg"); await VerifyDefaultValueAsync(markup, expectedDefaultValue: null, previousDefaultValue: "prior"); } [Theory] [InlineData("string")] [InlineData("bool")] [InlineData("int?")] public async Task TestInstanceVariable(string type) { var markup = $@" class C {{ {type} arg; void Method() {{ this.Target($$); }} void Target({type} arg) {{ }} }} "; await VerifyDefaultValueAsync(markup, "arg"); await VerifyDefaultValueAsync(markup, expectedDefaultValue: null, previousDefaultValue: "prior"); } // Note: The current implementation checks for exact type and name match. If this changes, some of these tests // may need to be updated to account for the new behavior. [Theory] [InlineData("object", "string")] [InlineData("string", "object")] [InlineData("bool", "bool?")] [InlineData("bool", "int")] [InlineData("int", "object")] public async Task TestMismatchType(string parameterType, string valueType) { var markup = $@" class C {{ void Method({valueType} arg) {{ this.Target($$); }} void Target({parameterType} arg) {{ }} }} "; await VerifyDefaultValueAsync(markup, null); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Completion.Providers; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Completion.ArgumentProviders { [Trait(Traits.Feature, Traits.Features.Completion)] public class ContextVariableArgumentProviderTests : AbstractCSharpArgumentProviderTests { internal override Type GetArgumentProviderType() => typeof(ContextVariableArgumentProvider); [Theory] [InlineData("string")] [InlineData("bool")] [InlineData("int?")] public async Task TestLocalVariable(string type) { var markup = $@" class C {{ void Method() {{ {type} arg = default; this.Target($$); }} void Target({type} arg) {{ }} }} "; await VerifyDefaultValueAsync(markup, "arg"); await VerifyDefaultValueAsync(markup, expectedDefaultValue: null, previousDefaultValue: "prior"); } [Theory] [InlineData("string")] [InlineData("bool")] [InlineData("int?")] public async Task TestParameter(string type) { var markup = $@" class C {{ void Method({type} arg) {{ this.Target($$); }} void Target({type} arg) {{ }} }} "; await VerifyDefaultValueAsync(markup, "arg"); await VerifyDefaultValueAsync(markup, expectedDefaultValue: null, previousDefaultValue: "prior"); } [Theory] [InlineData("string")] [InlineData("bool")] [InlineData("int?")] public async Task TestInstanceVariable(string type) { var markup = $@" class C {{ {type} arg; void Method() {{ this.Target($$); }} void Target({type} arg) {{ }} }} "; await VerifyDefaultValueAsync(markup, "arg"); await VerifyDefaultValueAsync(markup, expectedDefaultValue: null, previousDefaultValue: "prior"); } // Note: The current implementation checks for exact type and name match. If this changes, some of these tests // may need to be updated to account for the new behavior. [Theory] [InlineData("object", "string")] [InlineData("string", "object")] [InlineData("bool", "bool?")] [InlineData("bool", "int")] [InlineData("int", "object")] public async Task TestMismatchType(string parameterType, string valueType) { var markup = $@" class C {{ void Method({valueType} arg) {{ this.Target($$); }} void Target({parameterType} arg) {{ }} }} "; await VerifyDefaultValueAsync(markup, null); } } }
-1
dotnet/roslyn
56,419
Fix partial method doc comments
Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
RikkiGibson
"2021-09-15T20:47:39Z"
"2021-09-21T23:49:10Z"
0f60b3e9446f5d0fc14a570998c81a5d6c40cc23
8cda7462843d43d9b72039eede2f4cb43126cac2
Fix partial method doc comments. Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
./src/Compilers/Server/VBCSCompilerTests/Properties/launchSettings.json
{ "profiles": { "xUnit.net Console (32-bit)": { "commandName": "Executable", "executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.x86.exe", "commandLineArgs": "$(TargetPath) -noshadow -verbose" }, "xUnit.net Console (64-bit)": { "commandName": "Executable", "executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.exe", "commandLineArgs": "$(TargetPath) -noshadow -verbose" } } }
{ "profiles": { "xUnit.net Console (32-bit)": { "commandName": "Executable", "executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.x86.exe", "commandLineArgs": "$(TargetPath) -noshadow -verbose" }, "xUnit.net Console (64-bit)": { "commandName": "Executable", "executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.exe", "commandLineArgs": "$(TargetPath) -noshadow -verbose" } } }
-1
dotnet/roslyn
56,419
Fix partial method doc comments
Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
RikkiGibson
"2021-09-15T20:47:39Z"
"2021-09-21T23:49:10Z"
0f60b3e9446f5d0fc14a570998c81a5d6c40cc23
8cda7462843d43d9b72039eede2f4cb43126cac2
Fix partial method doc comments. Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
./src/Features/CSharp/Portable/ReplaceDocCommentTextWithTag/CSharpReplaceDocCommentTextWithTagCodeRefactoringProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Composition; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.ReplaceDocCommentTextWithTag; namespace Microsoft.CodeAnalysis.CSharp.ReplaceDocCommentTextWithTag { [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.ReplaceDocCommentTextWithTag), Shared] internal class CSharpReplaceDocCommentTextWithTagCodeRefactoringProvider : AbstractReplaceDocCommentTextWithTagCodeRefactoringProvider { private static readonly ImmutableHashSet<string> s_triggerKeywords = ImmutableHashSet.Create( SyntaxFacts.GetText(SyntaxKind.NullKeyword), SyntaxFacts.GetText(SyntaxKind.StaticKeyword), SyntaxFacts.GetText(SyntaxKind.VirtualKeyword), SyntaxFacts.GetText(SyntaxKind.TrueKeyword), SyntaxFacts.GetText(SyntaxKind.FalseKeyword), SyntaxFacts.GetText(SyntaxKind.AbstractKeyword), SyntaxFacts.GetText(SyntaxKind.SealedKeyword), SyntaxFacts.GetText(SyntaxKind.AsyncKeyword), SyntaxFacts.GetText(SyntaxKind.AwaitKeyword), SyntaxFacts.GetText(SyntaxKind.BaseKeyword), SyntaxFacts.GetText(SyntaxKind.ThisKeyword)); [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpReplaceDocCommentTextWithTagCodeRefactoringProvider() { } protected override bool IsXmlTextToken(SyntaxToken token) => token.Kind() is SyntaxKind.XmlTextLiteralToken or SyntaxKind.XmlTextLiteralNewLineToken; protected override bool IsInXMLAttribute(SyntaxToken token) { return (token.Parent.Kind() is SyntaxKind.XmlCrefAttribute or SyntaxKind.XmlNameAttribute or SyntaxKind.XmlTextAttribute); } protected override bool IsKeyword(string text) => s_triggerKeywords.Contains(text); protected override SyntaxNode ParseExpression(string text) => SyntaxFactory.ParseExpression(text); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Composition; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.ReplaceDocCommentTextWithTag; namespace Microsoft.CodeAnalysis.CSharp.ReplaceDocCommentTextWithTag { [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.ReplaceDocCommentTextWithTag), Shared] internal class CSharpReplaceDocCommentTextWithTagCodeRefactoringProvider : AbstractReplaceDocCommentTextWithTagCodeRefactoringProvider { private static readonly ImmutableHashSet<string> s_triggerKeywords = ImmutableHashSet.Create( SyntaxFacts.GetText(SyntaxKind.NullKeyword), SyntaxFacts.GetText(SyntaxKind.StaticKeyword), SyntaxFacts.GetText(SyntaxKind.VirtualKeyword), SyntaxFacts.GetText(SyntaxKind.TrueKeyword), SyntaxFacts.GetText(SyntaxKind.FalseKeyword), SyntaxFacts.GetText(SyntaxKind.AbstractKeyword), SyntaxFacts.GetText(SyntaxKind.SealedKeyword), SyntaxFacts.GetText(SyntaxKind.AsyncKeyword), SyntaxFacts.GetText(SyntaxKind.AwaitKeyword), SyntaxFacts.GetText(SyntaxKind.BaseKeyword), SyntaxFacts.GetText(SyntaxKind.ThisKeyword)); [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpReplaceDocCommentTextWithTagCodeRefactoringProvider() { } protected override bool IsXmlTextToken(SyntaxToken token) => token.Kind() is SyntaxKind.XmlTextLiteralToken or SyntaxKind.XmlTextLiteralNewLineToken; protected override bool IsInXMLAttribute(SyntaxToken token) { return (token.Parent.Kind() is SyntaxKind.XmlCrefAttribute or SyntaxKind.XmlNameAttribute or SyntaxKind.XmlTextAttribute); } protected override bool IsKeyword(string text) => s_triggerKeywords.Contains(text); protected override SyntaxNode ParseExpression(string text) => SyntaxFactory.ParseExpression(text); } }
-1
dotnet/roslyn
56,419
Fix partial method doc comments
Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
RikkiGibson
"2021-09-15T20:47:39Z"
"2021-09-21T23:49:10Z"
0f60b3e9446f5d0fc14a570998c81a5d6c40cc23
8cda7462843d43d9b72039eede2f4cb43126cac2
Fix partial method doc comments. Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
./src/EditorFeatures/Core/ModernCommands/SortImportsCommandArgs.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Diagnostics.CodeAnalysis; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Editor.Commanding; namespace Microsoft.CodeAnalysis.Editor.Commanding.Commands { /// <summary> /// Arguments for the Sort Imports command being invoked. /// </summary> [ExcludeFromCodeCoverage] internal class SortImportsCommandArgs : EditorCommandArgs { public SortImportsCommandArgs(ITextView textView, ITextBuffer subjectBuffer) : base(textView, subjectBuffer) { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Diagnostics.CodeAnalysis; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Editor.Commanding; namespace Microsoft.CodeAnalysis.Editor.Commanding.Commands { /// <summary> /// Arguments for the Sort Imports command being invoked. /// </summary> [ExcludeFromCodeCoverage] internal class SortImportsCommandArgs : EditorCommandArgs { public SortImportsCommandArgs(ITextView textView, ITextBuffer subjectBuffer) : base(textView, subjectBuffer) { } } }
-1
dotnet/roslyn
56,419
Fix partial method doc comments
Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
RikkiGibson
"2021-09-15T20:47:39Z"
"2021-09-21T23:49:10Z"
0f60b3e9446f5d0fc14a570998c81a5d6c40cc23
8cda7462843d43d9b72039eede2f4cb43126cac2
Fix partial method doc comments. Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
./src/VisualStudio/CSharp/Impl/ProjectSystemShim/CSharpEntryPointFinderService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Composition; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; namespace Microsoft.VisualStudio.LanguageServices.CSharp.ProjectSystemShim { [ExportLanguageService(typeof(IEntryPointFinderService), LanguageNames.CSharp), Shared] internal class CSharpEntryPointFinderService : IEntryPointFinderService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpEntryPointFinderService() { } public IEnumerable<INamedTypeSymbol> FindEntryPoints(INamespaceSymbol symbol, bool findFormsOnly) => EntryPointFinder.FindEntryPoints(symbol); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Composition; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; namespace Microsoft.VisualStudio.LanguageServices.CSharp.ProjectSystemShim { [ExportLanguageService(typeof(IEntryPointFinderService), LanguageNames.CSharp), Shared] internal class CSharpEntryPointFinderService : IEntryPointFinderService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpEntryPointFinderService() { } public IEnumerable<INamedTypeSymbol> FindEntryPoints(INamespaceSymbol symbol, bool findFormsOnly) => EntryPointFinder.FindEntryPoints(symbol); } }
-1
dotnet/roslyn
56,419
Fix partial method doc comments
Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
RikkiGibson
"2021-09-15T20:47:39Z"
"2021-09-21T23:49:10Z"
0f60b3e9446f5d0fc14a570998c81a5d6c40cc23
8cda7462843d43d9b72039eede2f4cb43126cac2
Fix partial method doc comments. Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
./src/Workspaces/Core/Portable/Workspace/Solution/DocumentState_TreeTextSource.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal partial class DocumentState { /// <summary> /// A source for <see cref="TextAndVersion"/> constructed from an syntax tree. /// </summary> private sealed class TreeTextSource : ValueSource<TextAndVersion>, ITextVersionable { private readonly ValueSource<SourceText> _lazyText; private readonly VersionStamp _version; private readonly string _filePath; public TreeTextSource(ValueSource<SourceText> text, VersionStamp version, string filePath) { _lazyText = text; _version = version; _filePath = filePath; } public override async Task<TextAndVersion> GetValueAsync(CancellationToken cancellationToken = default) { var text = await _lazyText.GetValueAsync(cancellationToken).ConfigureAwait(false); return TextAndVersion.Create(text, _version, _filePath); } public override TextAndVersion GetValue(CancellationToken cancellationToken = default) { var text = _lazyText.GetValue(cancellationToken); return TextAndVersion.Create(text, _version, _filePath); } public override bool TryGetValue(out TextAndVersion value) { if (_lazyText.TryGetValue(out var text)) { value = TextAndVersion.Create(text, _version, _filePath); return true; } else { value = null; return false; } } public bool TryGetTextVersion(out VersionStamp version) { version = _version; return version != default; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal partial class DocumentState { /// <summary> /// A source for <see cref="TextAndVersion"/> constructed from an syntax tree. /// </summary> private sealed class TreeTextSource : ValueSource<TextAndVersion>, ITextVersionable { private readonly ValueSource<SourceText> _lazyText; private readonly VersionStamp _version; private readonly string _filePath; public TreeTextSource(ValueSource<SourceText> text, VersionStamp version, string filePath) { _lazyText = text; _version = version; _filePath = filePath; } public override async Task<TextAndVersion> GetValueAsync(CancellationToken cancellationToken = default) { var text = await _lazyText.GetValueAsync(cancellationToken).ConfigureAwait(false); return TextAndVersion.Create(text, _version, _filePath); } public override TextAndVersion GetValue(CancellationToken cancellationToken = default) { var text = _lazyText.GetValue(cancellationToken); return TextAndVersion.Create(text, _version, _filePath); } public override bool TryGetValue(out TextAndVersion value) { if (_lazyText.TryGetValue(out var text)) { value = TextAndVersion.Create(text, _version, _filePath); return true; } else { value = null; return false; } } public bool TryGetTextVersion(out VersionStamp version) { version = _version; return version != default; } } } }
-1
dotnet/roslyn
56,419
Fix partial method doc comments
Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
RikkiGibson
"2021-09-15T20:47:39Z"
"2021-09-21T23:49:10Z"
0f60b3e9446f5d0fc14a570998c81a5d6c40cc23
8cda7462843d43d9b72039eede2f4cb43126cac2
Fix partial method doc comments. Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
./src/Compilers/Core/Portable/Symbols/Attributes/IMarshalAsAttributeTarget.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis { internal interface IMarshalAsAttributeTarget { MarshalPseudoCustomAttributeData GetOrCreateData(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis { internal interface IMarshalAsAttributeTarget { MarshalPseudoCustomAttributeData GetOrCreateData(); } }
-1
dotnet/roslyn
56,419
Fix partial method doc comments
Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
RikkiGibson
"2021-09-15T20:47:39Z"
"2021-09-21T23:49:10Z"
0f60b3e9446f5d0fc14a570998c81a5d6c40cc23
8cda7462843d43d9b72039eede2f4cb43126cac2
Fix partial method doc comments. Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
./src/Features/Core/Portable/Completion/CompletionItem.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.ComponentModel; using System.Diagnostics; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Completion { /// <summary> /// One of many possible completions used to form the completion list presented to the user. /// </summary> [DebuggerDisplay("{DisplayText}")] public sealed class CompletionItem : IComparable<CompletionItem> { private readonly string _filterText; /// <summary> /// The text that is displayed to the user. /// </summary> public string DisplayText { get; } /// <summary> /// An optional prefix to be displayed prepended to <see cref="DisplayText"/>. Can be null. /// Pattern-matching of user input will not be performed against this, but only against <see /// cref="DisplayText"/>. /// </summary> public string DisplayTextPrefix { get; } /// <summary> /// An optional suffix to be displayed appended to <see cref="DisplayText"/>. Can be null. /// Pattern-matching of user input will not be performed against this, but only against <see /// cref="DisplayText"/>. /// </summary> public string DisplayTextSuffix { get; } /// <summary> /// The text used to determine if the item matches the filter and is show in the list. /// This is often the same as <see cref="DisplayText"/> but may be different in certain circumstances. /// </summary> public string FilterText => _filterText ?? DisplayText; internal bool HasDifferentFilterText => _filterText != null; /// <summary> /// The text used to determine the order that the item appears in the list. /// This is often the same as the <see cref="DisplayText"/> but may be different in certain circumstances. /// </summary> public string SortText { get; } /// <summary> /// Descriptive text to place after <see cref="DisplayText"/> in the display layer. Should /// be short as it will show up in the UI. Display will present this in a way to distinguish /// this from the normal text (for example, by fading out and right-aligning). /// </summary> public string InlineDescription { get; } /// <summary> /// The span of the syntax element associated with this item. /// /// The span identifies the text in the document that is used to filter the initial list presented to the user, /// and typically represents the region of the document that will be changed if this item is committed. /// </summary> public TextSpan Span { get; internal set; } /// <summary> /// Additional information attached to a completion item by it creator. /// </summary> public ImmutableDictionary<string, string> Properties { get; } /// <summary> /// Descriptive tags from <see cref="Tags.WellKnownTags"/>. /// These tags may influence how the item is displayed. /// </summary> public ImmutableArray<string> Tags { get; } /// <summary> /// Rules that declare how this item should behave. /// </summary> public CompletionItemRules Rules { get; } /// <summary> /// Returns true if this item's text edit requires complex resolution that /// may impact performance. For example, an edit may be complex if it needs /// to format or type check the resulting code, or make complex non-local /// changes to other parts of the file. /// Complex resolution is used so we only do the minimum amount of work /// needed to display completion items. It is performed only for the /// committed item just prior to commit. Thus, it is ideal for any expensive /// completion work that does not affect the display of the item in the /// completion list, but is necessary for committing the item. /// An example of an item type requiring complex resolution is C#/VB /// override completion. /// </summary> public bool IsComplexTextEdit { get; } /// <summary> /// The name of the <see cref="CompletionProvider"/> that created this /// <see cref="CompletionItem"/>. Not available to clients. Only used by /// the Completion subsystem itself for things like getting description text /// and making additional change during commit. /// </summary> internal string ProviderName { get; set; } /// <summary> /// The automation text to use when narrating the completion item. If set to /// null, narration will use the <see cref="DisplayText"/> instead. /// </summary> internal string AutomationText { get; set; } internal CompletionItemFlags Flags { get; set; } private CompletionItem( string displayText, string filterText, string sortText, TextSpan span, ImmutableDictionary<string, string> properties, ImmutableArray<string> tags, CompletionItemRules rules, string displayTextPrefix, string displayTextSuffix, string inlineDescription, bool isComplexTextEdit) { DisplayText = displayText ?? ""; DisplayTextPrefix = displayTextPrefix ?? ""; DisplayTextSuffix = displayTextSuffix ?? ""; SortText = sortText ?? DisplayText; InlineDescription = inlineDescription ?? ""; Span = span; Properties = properties ?? ImmutableDictionary<string, string>.Empty; Tags = tags.NullToEmpty(); Rules = rules ?? CompletionItemRules.Default; IsComplexTextEdit = isComplexTextEdit; if (!DisplayText.Equals(filterText, StringComparison.Ordinal)) { _filterText = filterText; } } // binary back compat overload public static CompletionItem Create( string displayText, string filterText, string sortText, ImmutableDictionary<string, string> properties, ImmutableArray<string> tags, CompletionItemRules rules) { return Create(displayText, filterText, sortText, properties, tags, rules, displayTextPrefix: null, displayTextSuffix: null); } // binary back compat overload public static CompletionItem Create( string displayText, string filterText, string sortText, ImmutableDictionary<string, string> properties, ImmutableArray<string> tags, CompletionItemRules rules, string displayTextPrefix, string displayTextSuffix) { return Create(displayText, filterText, sortText, properties, tags, rules, displayTextPrefix, displayTextSuffix, inlineDescription: null); } // binary back compat overload public static CompletionItem Create( string displayText, string filterText, string sortText, ImmutableDictionary<string, string> properties, ImmutableArray<string> tags, CompletionItemRules rules, string displayTextPrefix, string displayTextSuffix, string inlineDescription) { return Create( displayText, filterText, sortText, properties, tags, rules, displayTextPrefix, displayTextSuffix, inlineDescription, isComplexTextEdit: false); } public static CompletionItem Create( string displayText, string filterText = null, string sortText = null, ImmutableDictionary<string, string> properties = null, ImmutableArray<string> tags = default, CompletionItemRules rules = null, string displayTextPrefix = null, string displayTextSuffix = null, string inlineDescription = null, bool isComplexTextEdit = false) { return new CompletionItem( span: default, displayText: displayText, filterText: filterText, sortText: sortText, properties: properties, tags: tags, rules: rules, displayTextPrefix: displayTextPrefix, displayTextSuffix: displayTextSuffix, inlineDescription: inlineDescription, isComplexTextEdit: isComplexTextEdit); } /// <summary> /// Creates a new <see cref="CompletionItem"/> /// </summary> /// <param name="displayText">The text that is displayed to the user.</param> /// <param name="filterText">The text used to determine if the item matches the filter and is show in the list.</param> /// <param name="sortText">The text used to determine the order that the item appears in the list.</param> /// <param name="span">The span of the syntax element in the document associated with this item.</param> /// <param name="properties">Additional information.</param> /// <param name="tags">Descriptive tags that may influence how the item is displayed.</param> /// <param name="rules">The rules that declare how this item should behave.</param> /// <returns></returns> [Obsolete("Use the Create overload that does not take a span", error: true)] [EditorBrowsable(EditorBrowsableState.Never)] public static CompletionItem Create( string displayText, string filterText, string sortText, TextSpan span, ImmutableDictionary<string, string> properties, ImmutableArray<string> tags, CompletionItemRules rules) { return new CompletionItem( span: span, displayText: displayText, filterText: filterText, sortText: sortText, properties: properties, tags: tags, rules: rules, displayTextPrefix: null, displayTextSuffix: null, inlineDescription: null, isComplexTextEdit: false); } private CompletionItem With( Optional<TextSpan> span = default, Optional<string> displayText = default, Optional<string> filterText = default, Optional<string> sortText = default, Optional<ImmutableDictionary<string, string>> properties = default, Optional<ImmutableArray<string>> tags = default, Optional<CompletionItemRules> rules = default, Optional<string> displayTextPrefix = default, Optional<string> displayTextSuffix = default, Optional<string> inlineDescription = default, Optional<bool> isComplexTextEdit = default) { var newSpan = span.HasValue ? span.Value : Span; var newDisplayText = displayText.HasValue ? displayText.Value : DisplayText; var newFilterText = filterText.HasValue ? filterText.Value : FilterText; var newSortText = sortText.HasValue ? sortText.Value : SortText; var newInlineDescription = inlineDescription.HasValue ? inlineDescription.Value : InlineDescription; var newProperties = properties.HasValue ? properties.Value : Properties; var newTags = tags.HasValue ? tags.Value : Tags; var newRules = rules.HasValue ? rules.Value : Rules; var newDisplayTextPrefix = displayTextPrefix.HasValue ? displayTextPrefix.Value : DisplayTextPrefix; var newDisplayTextSuffix = displayTextSuffix.HasValue ? displayTextSuffix.Value : DisplayTextSuffix; var newIsComplexTextEdit = isComplexTextEdit.HasValue ? isComplexTextEdit.Value : IsComplexTextEdit; if (newSpan == Span && newDisplayText == DisplayText && newFilterText == FilterText && newSortText == SortText && newProperties == Properties && newTags == Tags && newRules == Rules && newDisplayTextPrefix == DisplayTextPrefix && newDisplayTextSuffix == DisplayTextSuffix && newInlineDescription == InlineDescription && newIsComplexTextEdit == IsComplexTextEdit) { return this; } return new CompletionItem( displayText: newDisplayText, filterText: newFilterText, span: newSpan, sortText: newSortText, properties: newProperties, tags: newTags, rules: newRules, displayTextPrefix: newDisplayTextPrefix, displayTextSuffix: newDisplayTextSuffix, inlineDescription: newInlineDescription, isComplexTextEdit: newIsComplexTextEdit) { AutomationText = AutomationText, ProviderName = ProviderName, Flags = Flags, }; } /// <summary> /// Creates a copy of this <see cref="CompletionItem"/> with the <see cref="Span"/> property changed. /// </summary> [Obsolete("Not used anymore. CompletionList.Span is used to control the span used for filtering.", error: true)] [EditorBrowsable(EditorBrowsableState.Never)] public CompletionItem WithSpan(TextSpan span) => this; /// <summary> /// Creates a copy of this <see cref="CompletionItem"/> with the <see cref="DisplayText"/> property changed. /// </summary> public CompletionItem WithDisplayText(string text) => With(displayText: text); /// <summary> /// Creates a copy of this <see cref="CompletionItem"/> with the <see cref="DisplayTextPrefix"/> property changed. /// </summary> public CompletionItem WithDisplayTextPrefix(string displayTextPrefix) => With(displayTextPrefix: displayTextPrefix); /// <summary> /// Creates a copy of this <see cref="CompletionItem"/> with the <see cref="DisplayTextSuffix"/> property changed. /// </summary> public CompletionItem WithDisplayTextSuffix(string displayTextSuffix) => With(displayTextSuffix: displayTextSuffix); /// <summary> /// Creates a copy of this <see cref="CompletionItem"/> with the <see cref="FilterText"/> property changed. /// </summary> public CompletionItem WithFilterText(string text) => With(filterText: text); /// <summary> /// Creates a copy of this <see cref="CompletionItem"/> with the <see cref="SortText"/> property changed. /// </summary> public CompletionItem WithSortText(string text) => With(sortText: text); /// <summary> /// Creates a copy of this <see cref="CompletionItem"/> with the <see cref="Properties"/> property changed. /// </summary> public CompletionItem WithProperties(ImmutableDictionary<string, string> properties) => With(properties: properties); /// <summary> /// Creates a copy of this <see cref="CompletionItem"/> with a property added to the <see cref="Properties"/> collection. /// </summary> public CompletionItem AddProperty(string name, string value) => With(properties: Properties.Add(name, value)); /// <summary> /// Creates a copy of this <see cref="CompletionItem"/> with the <see cref="Tags"/> property changed. /// </summary> public CompletionItem WithTags(ImmutableArray<string> tags) => With(tags: tags); /// <summary> /// Creates a copy of this <see cref="CompletionItem"/> with a tag added to the <see cref="Tags"/> collection. /// </summary> public CompletionItem AddTag(string tag) { if (tag == null) { throw new ArgumentNullException(nameof(tag)); } if (Tags.Contains(tag)) { return this; } else { return With(tags: Tags.Add(tag)); } } /// <summary> /// Creates a copy of this <see cref="CompletionItem"/> with the <see cref="Rules"/> property changed. /// </summary> public CompletionItem WithRules(CompletionItemRules rules) => With(rules: rules); /// <summary> /// Creates a copy of this <see cref="CompletionItem"/> with the <see cref="IsComplexTextEdit"/> property changed. /// </summary> public CompletionItem WithIsComplexTextEdit(bool isComplexTextEdit) => With(isComplexTextEdit: isComplexTextEdit); private string _entireDisplayText; int IComparable<CompletionItem>.CompareTo(CompletionItem other) { // Make sure expanded items are listed after non-expanded ones var thisIsExpandItem = Flags.IsExpanded(); var otherIsExpandItem = other.Flags.IsExpanded(); if (thisIsExpandItem == otherIsExpandItem) { var result = StringComparer.OrdinalIgnoreCase.Compare(SortText, other.SortText); if (result == 0) { result = StringComparer.OrdinalIgnoreCase.Compare(GetEntireDisplayText(), other.GetEntireDisplayText()); } return result; } else if (thisIsExpandItem) { return 1; } else { return -1; } } internal string GetEntireDisplayText() { if (_entireDisplayText == null) { _entireDisplayText = DisplayTextPrefix + DisplayText + DisplayTextSuffix; } return _entireDisplayText; } public override string ToString() => GetEntireDisplayText(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.ComponentModel; using System.Diagnostics; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Completion { /// <summary> /// One of many possible completions used to form the completion list presented to the user. /// </summary> [DebuggerDisplay("{DisplayText}")] public sealed class CompletionItem : IComparable<CompletionItem> { private readonly string _filterText; /// <summary> /// The text that is displayed to the user. /// </summary> public string DisplayText { get; } /// <summary> /// An optional prefix to be displayed prepended to <see cref="DisplayText"/>. Can be null. /// Pattern-matching of user input will not be performed against this, but only against <see /// cref="DisplayText"/>. /// </summary> public string DisplayTextPrefix { get; } /// <summary> /// An optional suffix to be displayed appended to <see cref="DisplayText"/>. Can be null. /// Pattern-matching of user input will not be performed against this, but only against <see /// cref="DisplayText"/>. /// </summary> public string DisplayTextSuffix { get; } /// <summary> /// The text used to determine if the item matches the filter and is show in the list. /// This is often the same as <see cref="DisplayText"/> but may be different in certain circumstances. /// </summary> public string FilterText => _filterText ?? DisplayText; internal bool HasDifferentFilterText => _filterText != null; /// <summary> /// The text used to determine the order that the item appears in the list. /// This is often the same as the <see cref="DisplayText"/> but may be different in certain circumstances. /// </summary> public string SortText { get; } /// <summary> /// Descriptive text to place after <see cref="DisplayText"/> in the display layer. Should /// be short as it will show up in the UI. Display will present this in a way to distinguish /// this from the normal text (for example, by fading out and right-aligning). /// </summary> public string InlineDescription { get; } /// <summary> /// The span of the syntax element associated with this item. /// /// The span identifies the text in the document that is used to filter the initial list presented to the user, /// and typically represents the region of the document that will be changed if this item is committed. /// </summary> public TextSpan Span { get; internal set; } /// <summary> /// Additional information attached to a completion item by it creator. /// </summary> public ImmutableDictionary<string, string> Properties { get; } /// <summary> /// Descriptive tags from <see cref="Tags.WellKnownTags"/>. /// These tags may influence how the item is displayed. /// </summary> public ImmutableArray<string> Tags { get; } /// <summary> /// Rules that declare how this item should behave. /// </summary> public CompletionItemRules Rules { get; } /// <summary> /// Returns true if this item's text edit requires complex resolution that /// may impact performance. For example, an edit may be complex if it needs /// to format or type check the resulting code, or make complex non-local /// changes to other parts of the file. /// Complex resolution is used so we only do the minimum amount of work /// needed to display completion items. It is performed only for the /// committed item just prior to commit. Thus, it is ideal for any expensive /// completion work that does not affect the display of the item in the /// completion list, but is necessary for committing the item. /// An example of an item type requiring complex resolution is C#/VB /// override completion. /// </summary> public bool IsComplexTextEdit { get; } /// <summary> /// The name of the <see cref="CompletionProvider"/> that created this /// <see cref="CompletionItem"/>. Not available to clients. Only used by /// the Completion subsystem itself for things like getting description text /// and making additional change during commit. /// </summary> internal string ProviderName { get; set; } /// <summary> /// The automation text to use when narrating the completion item. If set to /// null, narration will use the <see cref="DisplayText"/> instead. /// </summary> internal string AutomationText { get; set; } internal CompletionItemFlags Flags { get; set; } private CompletionItem( string displayText, string filterText, string sortText, TextSpan span, ImmutableDictionary<string, string> properties, ImmutableArray<string> tags, CompletionItemRules rules, string displayTextPrefix, string displayTextSuffix, string inlineDescription, bool isComplexTextEdit) { DisplayText = displayText ?? ""; DisplayTextPrefix = displayTextPrefix ?? ""; DisplayTextSuffix = displayTextSuffix ?? ""; SortText = sortText ?? DisplayText; InlineDescription = inlineDescription ?? ""; Span = span; Properties = properties ?? ImmutableDictionary<string, string>.Empty; Tags = tags.NullToEmpty(); Rules = rules ?? CompletionItemRules.Default; IsComplexTextEdit = isComplexTextEdit; if (!DisplayText.Equals(filterText, StringComparison.Ordinal)) { _filterText = filterText; } } // binary back compat overload public static CompletionItem Create( string displayText, string filterText, string sortText, ImmutableDictionary<string, string> properties, ImmutableArray<string> tags, CompletionItemRules rules) { return Create(displayText, filterText, sortText, properties, tags, rules, displayTextPrefix: null, displayTextSuffix: null); } // binary back compat overload public static CompletionItem Create( string displayText, string filterText, string sortText, ImmutableDictionary<string, string> properties, ImmutableArray<string> tags, CompletionItemRules rules, string displayTextPrefix, string displayTextSuffix) { return Create(displayText, filterText, sortText, properties, tags, rules, displayTextPrefix, displayTextSuffix, inlineDescription: null); } // binary back compat overload public static CompletionItem Create( string displayText, string filterText, string sortText, ImmutableDictionary<string, string> properties, ImmutableArray<string> tags, CompletionItemRules rules, string displayTextPrefix, string displayTextSuffix, string inlineDescription) { return Create( displayText, filterText, sortText, properties, tags, rules, displayTextPrefix, displayTextSuffix, inlineDescription, isComplexTextEdit: false); } public static CompletionItem Create( string displayText, string filterText = null, string sortText = null, ImmutableDictionary<string, string> properties = null, ImmutableArray<string> tags = default, CompletionItemRules rules = null, string displayTextPrefix = null, string displayTextSuffix = null, string inlineDescription = null, bool isComplexTextEdit = false) { return new CompletionItem( span: default, displayText: displayText, filterText: filterText, sortText: sortText, properties: properties, tags: tags, rules: rules, displayTextPrefix: displayTextPrefix, displayTextSuffix: displayTextSuffix, inlineDescription: inlineDescription, isComplexTextEdit: isComplexTextEdit); } /// <summary> /// Creates a new <see cref="CompletionItem"/> /// </summary> /// <param name="displayText">The text that is displayed to the user.</param> /// <param name="filterText">The text used to determine if the item matches the filter and is show in the list.</param> /// <param name="sortText">The text used to determine the order that the item appears in the list.</param> /// <param name="span">The span of the syntax element in the document associated with this item.</param> /// <param name="properties">Additional information.</param> /// <param name="tags">Descriptive tags that may influence how the item is displayed.</param> /// <param name="rules">The rules that declare how this item should behave.</param> /// <returns></returns> [Obsolete("Use the Create overload that does not take a span", error: true)] [EditorBrowsable(EditorBrowsableState.Never)] public static CompletionItem Create( string displayText, string filterText, string sortText, TextSpan span, ImmutableDictionary<string, string> properties, ImmutableArray<string> tags, CompletionItemRules rules) { return new CompletionItem( span: span, displayText: displayText, filterText: filterText, sortText: sortText, properties: properties, tags: tags, rules: rules, displayTextPrefix: null, displayTextSuffix: null, inlineDescription: null, isComplexTextEdit: false); } private CompletionItem With( Optional<TextSpan> span = default, Optional<string> displayText = default, Optional<string> filterText = default, Optional<string> sortText = default, Optional<ImmutableDictionary<string, string>> properties = default, Optional<ImmutableArray<string>> tags = default, Optional<CompletionItemRules> rules = default, Optional<string> displayTextPrefix = default, Optional<string> displayTextSuffix = default, Optional<string> inlineDescription = default, Optional<bool> isComplexTextEdit = default) { var newSpan = span.HasValue ? span.Value : Span; var newDisplayText = displayText.HasValue ? displayText.Value : DisplayText; var newFilterText = filterText.HasValue ? filterText.Value : FilterText; var newSortText = sortText.HasValue ? sortText.Value : SortText; var newInlineDescription = inlineDescription.HasValue ? inlineDescription.Value : InlineDescription; var newProperties = properties.HasValue ? properties.Value : Properties; var newTags = tags.HasValue ? tags.Value : Tags; var newRules = rules.HasValue ? rules.Value : Rules; var newDisplayTextPrefix = displayTextPrefix.HasValue ? displayTextPrefix.Value : DisplayTextPrefix; var newDisplayTextSuffix = displayTextSuffix.HasValue ? displayTextSuffix.Value : DisplayTextSuffix; var newIsComplexTextEdit = isComplexTextEdit.HasValue ? isComplexTextEdit.Value : IsComplexTextEdit; if (newSpan == Span && newDisplayText == DisplayText && newFilterText == FilterText && newSortText == SortText && newProperties == Properties && newTags == Tags && newRules == Rules && newDisplayTextPrefix == DisplayTextPrefix && newDisplayTextSuffix == DisplayTextSuffix && newInlineDescription == InlineDescription && newIsComplexTextEdit == IsComplexTextEdit) { return this; } return new CompletionItem( displayText: newDisplayText, filterText: newFilterText, span: newSpan, sortText: newSortText, properties: newProperties, tags: newTags, rules: newRules, displayTextPrefix: newDisplayTextPrefix, displayTextSuffix: newDisplayTextSuffix, inlineDescription: newInlineDescription, isComplexTextEdit: newIsComplexTextEdit) { AutomationText = AutomationText, ProviderName = ProviderName, Flags = Flags, }; } /// <summary> /// Creates a copy of this <see cref="CompletionItem"/> with the <see cref="Span"/> property changed. /// </summary> [Obsolete("Not used anymore. CompletionList.Span is used to control the span used for filtering.", error: true)] [EditorBrowsable(EditorBrowsableState.Never)] public CompletionItem WithSpan(TextSpan span) => this; /// <summary> /// Creates a copy of this <see cref="CompletionItem"/> with the <see cref="DisplayText"/> property changed. /// </summary> public CompletionItem WithDisplayText(string text) => With(displayText: text); /// <summary> /// Creates a copy of this <see cref="CompletionItem"/> with the <see cref="DisplayTextPrefix"/> property changed. /// </summary> public CompletionItem WithDisplayTextPrefix(string displayTextPrefix) => With(displayTextPrefix: displayTextPrefix); /// <summary> /// Creates a copy of this <see cref="CompletionItem"/> with the <see cref="DisplayTextSuffix"/> property changed. /// </summary> public CompletionItem WithDisplayTextSuffix(string displayTextSuffix) => With(displayTextSuffix: displayTextSuffix); /// <summary> /// Creates a copy of this <see cref="CompletionItem"/> with the <see cref="FilterText"/> property changed. /// </summary> public CompletionItem WithFilterText(string text) => With(filterText: text); /// <summary> /// Creates a copy of this <see cref="CompletionItem"/> with the <see cref="SortText"/> property changed. /// </summary> public CompletionItem WithSortText(string text) => With(sortText: text); /// <summary> /// Creates a copy of this <see cref="CompletionItem"/> with the <see cref="Properties"/> property changed. /// </summary> public CompletionItem WithProperties(ImmutableDictionary<string, string> properties) => With(properties: properties); /// <summary> /// Creates a copy of this <see cref="CompletionItem"/> with a property added to the <see cref="Properties"/> collection. /// </summary> public CompletionItem AddProperty(string name, string value) => With(properties: Properties.Add(name, value)); /// <summary> /// Creates a copy of this <see cref="CompletionItem"/> with the <see cref="Tags"/> property changed. /// </summary> public CompletionItem WithTags(ImmutableArray<string> tags) => With(tags: tags); /// <summary> /// Creates a copy of this <see cref="CompletionItem"/> with a tag added to the <see cref="Tags"/> collection. /// </summary> public CompletionItem AddTag(string tag) { if (tag == null) { throw new ArgumentNullException(nameof(tag)); } if (Tags.Contains(tag)) { return this; } else { return With(tags: Tags.Add(tag)); } } /// <summary> /// Creates a copy of this <see cref="CompletionItem"/> with the <see cref="Rules"/> property changed. /// </summary> public CompletionItem WithRules(CompletionItemRules rules) => With(rules: rules); /// <summary> /// Creates a copy of this <see cref="CompletionItem"/> with the <see cref="IsComplexTextEdit"/> property changed. /// </summary> public CompletionItem WithIsComplexTextEdit(bool isComplexTextEdit) => With(isComplexTextEdit: isComplexTextEdit); private string _entireDisplayText; int IComparable<CompletionItem>.CompareTo(CompletionItem other) { // Make sure expanded items are listed after non-expanded ones var thisIsExpandItem = Flags.IsExpanded(); var otherIsExpandItem = other.Flags.IsExpanded(); if (thisIsExpandItem == otherIsExpandItem) { var result = StringComparer.OrdinalIgnoreCase.Compare(SortText, other.SortText); if (result == 0) { result = StringComparer.OrdinalIgnoreCase.Compare(GetEntireDisplayText(), other.GetEntireDisplayText()); } return result; } else if (thisIsExpandItem) { return 1; } else { return -1; } } internal string GetEntireDisplayText() { if (_entireDisplayText == null) { _entireDisplayText = DisplayTextPrefix + DisplayText + DisplayTextSuffix; } return _entireDisplayText; } public override string ToString() => GetEntireDisplayText(); } }
-1
dotnet/roslyn
56,419
Fix partial method doc comments
Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
RikkiGibson
"2021-09-15T20:47:39Z"
"2021-09-21T23:49:10Z"
0f60b3e9446f5d0fc14a570998c81a5d6c40cc23
8cda7462843d43d9b72039eede2f4cb43126cac2
Fix partial method doc comments. Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
./src/Workspaces/VisualBasicTest/Formatting/FormattingTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions Imports Microsoft.CodeAnalysis.Formatting Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Formatting Public Class FormattingTest Inherits VisualBasicFormattingTestBase <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function Format1() As Task Dim code = <Code> Namespace A End Namespace </Code> Dim expected = <Code> Namespace A End Namespace</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function NamespaceBlock() As Task Dim code = <Code> Namespace A Class C End Class End Namespace </Code> Dim expected = <Code>Namespace A Class C End Class End Namespace</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function TypeBlock() As Task Dim code = <Code> Class C Sub Method ( ) End Sub End Class </Code> Dim expected = <Code>Class C Sub Method() End Sub End Class </Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function MethodBlock() As Task Dim code = <Code> Class C Sub Method ( ) Dim a As Integer = 1 End Sub End Class </Code> Dim expected = <Code>Class C Sub Method() Dim a As Integer = 1 End Sub End Class </Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function StructBlock() As Task Dim code = <Code> Structure C Sub Method ( ) Dim a As Integer = 1 End Sub Dim field As Integer End Structure </Code> Dim expected = <Code>Structure C Sub Method() Dim a As Integer = 1 End Sub Dim field As Integer End Structure </Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function EnumBlock() As Task Dim code = <Code> Enum C A B X Z End Enum </Code> Dim expected = <Code>Enum C A B X Z End Enum</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function ModuleBlock() As Task Dim code = <Code> Module module1 Sub goo() End Sub End Module </Code> Dim expected = <Code>Module module1 Sub goo() End Sub End Module</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function InterfaceBlock() As Task Dim code = <Code> Interface IGoo Sub goo() End Interface </Code> Dim expected = <Code>Interface IGoo Sub goo() End Interface </Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function PropertyBlock() As Task Dim code = <Code> Class C Property P ( ) As Integer Get Return 1 End Get Set ( ByVal value As Integer ) End Set End Property End Class </Code> Dim expected = <Code>Class C Property P() As Integer Get Return 1 End Get Set(ByVal value As Integer) End Set End Property End Class</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function EventBlock() As Task Dim code = <Code> Class C Public Custom Event MouseDown As EventHandler AddHandler ( ByVal Value As EventHandler ) Dim i As Integer = 1 End AddHandler RemoveHandler ( ByVal Value As EventHandler ) Dim i As Integer = 1 End RemoveHandler RaiseEvent ( ByVal sender As Object, ByVal e As Object ) Dim i As Integer = 1 End RaiseEvent End Event End Class </Code> Dim expected = <Code>Class C Public Custom Event MouseDown As EventHandler AddHandler(ByVal Value As EventHandler) Dim i As Integer = 1 End AddHandler RemoveHandler(ByVal Value As EventHandler) Dim i As Integer = 1 End RemoveHandler RaiseEvent(ByVal sender As Object, ByVal e As Object) Dim i As Integer = 1 End RaiseEvent End Event End Class</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function WhileBlockNode() As Task Dim code = <Code>Class C Sub Method ( ) While True Dim i As Integer = 1 End While End Sub End Class</Code> Dim expected = <Code>Class C Sub Method() While True Dim i As Integer = 1 End While End Sub End Class</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function UsingBlockNode() As Task Dim code = <Code>Class C Sub Method() Using TraceSource Dim i = 1 End Using End Sub End Class</Code> Dim expected = <Code>Class C Sub Method() Using TraceSource Dim i = 1 End Using End Sub End Class</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function SyncLockBlockNode() As Task Dim code = <Code>Class C Sub Method() SyncLock New Object Dim i = 10 End SyncLock End Sub End Class</Code> Dim expected = <Code>Class C Sub Method() SyncLock New Object Dim i = 10 End SyncLock End Sub End Class</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function WithBlockNode() As Task Dim code = <Code>Class C Sub Method() With New Object Dim i As Integer = 1 End With End Sub End Class</Code> Dim expected = <Code>Class C Sub Method() With New Object Dim i As Integer = 1 End With End Sub End Class</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function IfBlockNode() As Task Dim code = <Code>Class C Sub Method() If True Then Dim i As Integer = 1 ElseIf True Then Dim i As Integer = 1 Else Dim i As Integer = 1 End If End Sub End Class</Code> Dim expected = <Code>Class C Sub Method() If True Then Dim i As Integer = 1 ElseIf True Then Dim i As Integer = 1 Else Dim i As Integer = 1 End If End Sub End Class</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function TryCatchBlockNode() As Task Dim code = <Code>Class C Sub Method() Try Dim i As Integer = 1 Catch e As Exception When TypeOf e Is ArgumentNullException Try Dim i As Integer = 1 Catch ex As ArgumentNullException End Try Catch e As Exception When TypeOf e Is ArgumentNullException Dim i As Integer = 1 Finally goo() End Try End Sub End Class</Code> Dim expected = <Code>Class C Sub Method() Try Dim i As Integer = 1 Catch e As Exception When TypeOf e Is ArgumentNullException Try Dim i As Integer = 1 Catch ex As ArgumentNullException End Try Catch e As Exception When TypeOf e Is ArgumentNullException Dim i As Integer = 1 Finally goo() End Try End Sub End Class</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function SelectBlockNode() As Task Dim code = <Code>Class C Sub Method() Dim i = 1 Select Case i Case 1 , 2 , 3 Dim i2 = 1 Case 1 To 3 Dim i2 = 1 Case Else Dim i2 = 1 End Select End Sub End Class</Code> Dim expected = <Code>Class C Sub Method() Dim i = 1 Select Case i Case 1, 2, 3 Dim i2 = 1 Case 1 To 3 Dim i2 = 1 Case Else Dim i2 = 1 End Select End Sub End Class</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function DoLoopBlockNode() As Task Dim code = <Code>Class C Sub Method() Do Dim i = 1 Loop End Sub End Class</Code> Dim expected = <Code>Class C Sub Method() Do Dim i = 1 Loop End Sub End Class</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function DoUntilBlockNode() As Task Dim code = <Code>Class C Sub Method() Do Until False goo() Loop End Sub End Class</Code> Dim expected = <Code>Class C Sub Method() Do Until False goo() Loop End Sub End Class</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function ForBlockNode() As Task Dim code = <Code>Class C Sub Method() For i = 1 To 10 Step 1 Dim a = 1 Next End Sub End Class</Code> Dim expected = <Code>Class C Sub Method() For i = 1 To 10 Step 1 Dim a = 1 Next End Sub End Class</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function AnchorStatement() As Task Dim code = <Code>Imports System Imports System. Collections. Generic</Code> Dim expected = <Code>Imports System Imports System. Collections. Generic</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function AnchorQueryStatement() As Task Dim code = <Code>Class C Sub Method() Dim a = From q In {1, 3, 5} Where q > 10 Select q End Sub End Class</Code> Dim expected = <Code>Class C Sub Method() Dim a = From q In {1, 3, 5} Where q > 10 Select q End Sub End Class</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function AlignQueryStatement() As Task Dim code = <Code>Class C Sub Method() Dim a = From q In {1, 3, 5} Where q > 10 Select q End Sub End Class</Code> Dim expected = <Code>Class C Sub Method() Dim a = From q In {1, 3, 5} Where q > 10 Select q End Sub End Class</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function Operators1() As Task Dim code = <Code>Class C Sub Method() Dim a = - 1 Dim a2 = 1-1 Dim a3 = + 1 Dim a4 = 1+1 Dim a5 = 2+(3*-2) Goo(2,(3)) End Sub End Class </Code> Dim expected = <Code>Class C Sub Method() Dim a = -1 Dim a2 = 1 - 1 Dim a3 = +1 Dim a4 = 1 + 1 Dim a5 = 2 + (3 * -2) Goo(2, (3)) End Sub End Class </Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function Operators2() As Task Dim code = <Code>Class C Sub Method() Dim myStr As String myStr = "Hello" &amp; " World" End Sub End Class</Code> Dim expected = <Code>Class C Sub Method() Dim myStr As String myStr = "Hello" &amp; " World" End Sub End Class</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function Operators3() As Task Dim code = <Code>Class C Sub Method() Dim a1 = 1 &lt;= 2 Dim a2 = 2 &gt;= 3 Dim a3 = 4 &lt;&gt; 5 Dim a4 = 5 ^ 4 Dim a5 = 0 a5 +=1 a5 -=1 a5 *=1 a5 /=1 a5 \=1 a5 ^=1 a5&lt;&lt;= 1 a5&gt;&gt;= 1 a5 &amp;= 1 a5 = a5&lt;&lt; 1 a5 = a5&gt;&gt; 1 End Sub End Class</Code> Dim expected = <Code>Class C Sub Method() Dim a1 = 1 &lt;= 2 Dim a2 = 2 &gt;= 3 Dim a3 = 4 &lt;&gt; 5 Dim a4 = 5 ^ 4 Dim a5 = 0 a5 += 1 a5 -= 1 a5 *= 1 a5 /= 1 a5 \= 1 a5 ^= 1 a5 &lt;&lt;= 1 a5 &gt;&gt;= 1 a5 &amp;= 1 a5 = a5 &lt;&lt; 1 a5 = a5 &gt;&gt; 1 End Sub End Class</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function Punctuation() As Task Dim code = <Code> &lt; Fact ( ) , Trait ( Traits . Feature , Traits . Features . Formatting ) &gt; Class A End Class</Code> Dim expected = <Code>&lt;Fact(), Trait(Traits.Feature, Traits.Features.Formatting)&gt; Class A End Class</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function Punctuation2() As Task Dim code = <Code>Class C Sub Method(Optional ByVal i As Integer = 1) Method(i := 1) End Sub End Class</Code> Dim expected = <Code>Class C Sub Method(Optional ByVal i As Integer = 1) Method(i:=1) End Sub End Class</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function Punctuation3() As Task Dim code = <Code><![CDATA[Class C <Attribute(goo := "value")> Sub Method() End Sub End Class]]></Code> Dim expected = <Code><![CDATA[Class C <Attribute(goo:="value")> Sub Method() End Sub End Class]]></Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function Lambda1() As Task Dim code = <Code>Class C Sub Method(Optional ByVal i As Integer = 1) Dim q = Function ( t ) 1 Dim q2=Sub ( t )Console . WriteLine ( t ) End Sub End Class</Code> Dim expected = <Code>Class C Sub Method(Optional ByVal i As Integer = 1) Dim q = Function(t) 1 Dim q2 = Sub(t) Console.WriteLine(t) End Sub End Class</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function Lambda2() As Task Dim code = <Code>Class C Sub Method(Optional ByVal i As Integer = 1) Dim q = Function ( t ) Return 1 End Function Dim q2 = Sub ( t ) Dim a = t End Sub End Sub End Class</Code> Dim expected = <Code>Class C Sub Method(Optional ByVal i As Integer = 1) Dim q = Function(t) Return 1 End Function Dim q2 = Sub(t) Dim a = t End Sub End Sub End Class</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function Lambda3() As Task Dim code = <Code>Class C Sub Method(Optional ByVal i As Integer = 1) Dim q = Function ( t ) Return 1 End Function Dim q2 = Sub ( t ) Dim a = t End Sub End Sub End Class</Code> Dim expected = <Code>Class C Sub Method(Optional ByVal i As Integer = 1) Dim q = Function(t) Return 1 End Function Dim q2 = Sub(t) Dim a = t End Sub End Sub End Class</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function Lambda4() As Task Dim code = <Code>Class C Sub Method(Optional ByVal i As Integer = 1) Dim q = Function ( t ) Return 1 End Function Dim q2 = Sub ( t ) Dim a = t Dim bbb = Function(r) Return r End Function End Sub End Sub End Class</Code> Dim expected = <Code>Class C Sub Method(Optional ByVal i As Integer = 1) Dim q = Function(t) Return 1 End Function Dim q2 = Sub(t) Dim a = t Dim bbb = Function(r) Return r End Function End Sub End Sub End Class</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Theory, Trait(Traits.Feature, Traits.Features.Formatting)> <InlineData("_")> <InlineData("_ ' Comment")> Public Async Function LineContinuation1(continuation As String) As Task Dim code = $"Class C Sub Method(Optional ByVal i As Integer = 1) Dim a = 1 + {continuation} 2 + {continuation} 3 End Sub End Class" Dim expected = $"Class C Sub Method(Optional ByVal i As Integer = 1) Dim a = 1 + {continuation} 2 + {continuation} 3 End Sub End Class" Await AssertFormatAsync(code, expected) End Function <Theory, Trait(Traits.Feature, Traits.Features.Formatting)> <InlineData("_")> <InlineData("_ ' Comment")> Public Async Function LineContinuation2(continuation As String) As Task Dim code = $"Class C Sub Method(Optional ByVal i As Integer = 1) Dim aa = 1 + {continuation} 2 + {continuation} 3 End Sub End Class" Dim expected = $"Class C Sub Method(Optional ByVal i As Integer = 1) Dim aa = 1 + {continuation} 2 + {continuation} 3 End Sub End Class" Await AssertFormatAsync(code, expected) End Function <Theory, Trait(Traits.Feature, Traits.Features.Formatting)> <InlineData("_")> <InlineData("_ ' Comment")> Public Async Function LineContinuation3(continuation As String) As Task Dim code = $"Class C Sub Method(Optional ByVal i As Integer = 1) Dim aa = 1 + {continuation} 2 + {continuation} 3 End Sub End Class" Dim expected = $"Class C Sub Method(Optional ByVal i As Integer = 1) Dim aa = 1 + {continuation} 2 + {continuation} 3 End Sub End Class" Await AssertFormatAsync(code, expected) End Function <Theory, Trait(Traits.Feature, Traits.Features.Formatting)> <InlineData("_")> <InlineData("_ ' Comment")> Public Async Function LineContinuation4(continuation As String) As Task Dim code = $"Class C Sub Method(Optional ByVal i As Integer = 1) Dim aa = 1 + {continuation} {continuation} {continuation} {continuation} {continuation} {continuation} 2 + {continuation} 3 End Sub End Class" Dim expected = $"Class C Sub Method(Optional ByVal i As Integer = 1) Dim aa = 1 + {continuation} {continuation} {continuation} {continuation} {continuation} {continuation} 2 + {continuation} 3 End Sub End Class" Await AssertFormatAsync(code, expected) End Function <Theory, Trait(Traits.Feature, Traits.Features.Formatting)> <InlineData("_")> <InlineData("_ ' Comment")> Public Async Function LineContinuation5(continuation As String) As Task Dim code = $"Class C Sub Method(Optional ByVal i As Integer = 1) Dim aa = 1 + {continuation} {continuation} {continuation} {continuation} {continuation} {continuation} 2 + {continuation} 3 End Sub End Class" Dim expected = $"Class C Sub Method(Optional ByVal i As Integer = 1) Dim aa = 1 + {continuation} {continuation} {continuation} {continuation} {continuation} {continuation} 2 + {continuation} 3 End Sub End Class" Await AssertFormatAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function AnonType() As Task Dim code = <Code>Class Goo Sub GooMethod() Dim SomeAnonType = New With { .goo = "goo", .answer = 42 } End Sub End Class</Code> Dim expected = <Code>Class Goo Sub GooMethod() Dim SomeAnonType = New With { .goo = "goo", .answer = 42 } End Sub End Class</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function CollectionInitializer() As Task Dim code = <Code>Class Goo Sub GooMethod() Dim somelist = New List(Of Integer) From { 1, 2, 3 } End Sub End Class</Code> Dim expected = <Code>Class Goo Sub GooMethod() Dim somelist = New List(Of Integer) From { 1, 2, 3 } End Sub End Class</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function Label1() As Task Dim code = <Code>Class C Sub Method() GoTo l l: Stop End Sub End Class</Code> Dim expected = <Code>Class C Sub Method() GoTo l l: Stop End Sub End Class</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function Label2() As Task Dim code = <Code>Class C Sub Method() GoTo goofoofoofoofoo goofoofoofoofoo: Stop End Sub End Class</Code> Dim expected = <Code>Class C Sub Method() GoTo goofoofoofoofoo goofoofoofoofoo: Stop End Sub End Class</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function Label3() As Task Dim code = <Code>Class C Sub Goo() goo() x : goo() y : goo() End Sub End Class</Code> Dim expected = <Code>Class C Sub Goo() goo() x: goo() y: goo() End Sub End Class</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function Trivia1() As Task Dim code = <Code>Class C Sub Method(Optional ByVal i As Integer = 1) ' Test ' Test2 ' Test 3 Dim a = 1 End Sub End Class</Code> Dim expected = <Code>Class C Sub Method(Optional ByVal i As Integer = 1) ' Test ' Test2 ' Test 3 Dim a = 1 End Sub End Class</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function Trivia2() As Task Dim code = <Code>Class C Sub Method(Optional ByVal i As Integer = 1) ''' Test ''' Test2 ''' Test 3 Dim a = 1 End Sub End Class</Code> Dim expected = <Code>Class C Sub Method(Optional ByVal i As Integer = 1) ''' Test ''' Test2 ''' Test 3 Dim a = 1 End Sub End Class</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Theory, Trait(Traits.Feature, Traits.Features.Formatting)> <InlineData("_")> <InlineData("_ ' Comment")> Public Async Function Trivia3(continuation As String) As Task Dim code = $"Class C Sub Method(Optional ByVal i As Integer = 1) Dim a = {continuation} {continuation} {continuation} 1 End Sub End Class" Dim expected = $"Class C Sub Method(Optional ByVal i As Integer = 1) Dim a = {continuation} {continuation} {continuation} 1 End Sub End Class" Await AssertFormatAsync(code, expected) End Function <WorkItem(538354, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538354")> <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix3939() As Task Dim code = <Code> Imports System. Collections. Generic </Code> Dim expected = <Code> Imports System. Collections. Generic</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <WorkItem(538579, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538579")> <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix4235() As Task Dim code = <Code> #If False Then #End If </Code> Dim expected = <Code> #If False Then #End If </Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function XmlLiterals1() As Task Dim code = "Dim xml = < XML > </ XML > " Dim expected = " Dim xml = <XML></XML>" Await AssertFormatAsync(CreateMethod(code), CreateMethod(expected)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function XmlLiterals2() As Task Dim code = "Dim xml = < XML > <%= a %> </ XML > " Dim expected = " Dim xml = <XML><%= a %></XML>" Await AssertFormatAsync(CreateMethod(code), CreateMethod(expected)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function XmlLiterals3() As Task Dim code = "Dim xml = < local : XML > </ local : XML > " Dim expected = " Dim xml = <local:XML></local:XML>" Await AssertFormatAsync(CreateMethod(code), CreateMethod(expected)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function XmlLiterals4() As Task Dim code = "Dim xml = < local :<%= hello %> > </ > " Dim expected = " Dim xml = <local:<%= hello %>></>" Await AssertFormatAsync(CreateMethod(code), CreateMethod(expected)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function XmlLiterals5() As Task Dim code = "Dim xml = < <%= hello %> > </ > " Dim expected = " Dim xml = <<%= hello %>></>" Await AssertFormatAsync(CreateMethod(code), CreateMethod(expected)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function XmlLiterals6() As Task Dim code = "Dim xml = < <%= hello %> /> " Dim expected = " Dim xml = <<%= hello %>/>" Await AssertFormatAsync(CreateMethod(code), CreateMethod(expected)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function XmlLiterals7() As Task Dim code = "Dim xml = < xml attr = ""1"" /> " Dim expected = " Dim xml = <xml attr=""1""/>" Await AssertFormatAsync(CreateMethod(code), CreateMethod(expected)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function XmlLiterals8() As Task Dim code = "Dim xml = < xml attr = '1' /> " Dim expected = " Dim xml = <xml attr='1'/>" Await AssertFormatAsync(CreateMethod(code), CreateMethod(expected)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function XmlLiterals9() As Task Dim code = "Dim xml = < xml attr = '1' attr2 = ""2"" attr3 = <%= hello %> /> " Dim expected = " Dim xml = <xml attr='1' attr2=""2"" attr3=<%= hello %>/>" Await AssertFormatAsync(CreateMethod(code), CreateMethod(expected)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function XmlLiterals10() As Task Dim code = "Dim xml = < xml local:attr = '1' attr2 = ""2"" attr3 = <%= hello %> /> " Dim expected = " Dim xml = <xml local:attr='1' attr2=""2"" attr3=<%= hello %>/>" Await AssertFormatAsync(CreateMethod(code), CreateMethod(expected)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function XmlLiterals11() As Task Dim code = "Dim xml = < xml local:attr = '1' <%= attr2 %> = ""2"" local:<%= attr3 %> = <%= hello %> /> " Dim expected = " Dim xml = <xml local:attr='1' <%= attr2 %>=""2"" local:<%= attr3 %>=<%= hello %>/>" Await AssertFormatAsync(CreateMethod(code), CreateMethod(expected)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function XmlLiterals12() As Task Dim code = "Dim xml = < xml> test </xml > " Dim expected = " Dim xml = <xml> test </xml>" Await AssertFormatAsync(CreateMethod(code), CreateMethod(expected)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function XmlLiterals13() As Task Dim code = "Dim xml = < xml> test <%= test %> </xml > " Dim expected = " Dim xml = <xml> test <%= test %></xml>" Await AssertFormatAsync(CreateMethod(code), CreateMethod(expected)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function XmlLiterals14() As Task Dim code = "Dim xml = < xml> test <%= test %> <%= test2 %> </xml > " Dim expected = " Dim xml = <xml> test <%= test %><%= test2 %></xml>" Await AssertFormatAsync(CreateMethod(code), CreateMethod(expected)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function XmlLiterals15() As Task Dim code = "Dim xml = < xml> <%= test1 %> test <%= test %> <%= test2 %> </xml > " Dim expected = " Dim xml = <xml><%= test1 %> test <%= test %><%= test2 %></xml>" Await AssertFormatAsync(CreateMethod(code), CreateMethod(expected)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function XmlLiterals16() As Task Dim code = "Dim xml = < xml> <!-- test --> </xml > " Dim expected = " Dim xml = <xml><!-- test --></xml>" Await AssertFormatAsync(CreateMethod(code), CreateMethod(expected)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function XmlLiterals17() As Task Dim code = "Dim xml = <xml> <test/> <!-- test --> test <!-- test --> </xml> " Dim expected = " Dim xml = <xml><test/><!-- test --> test <!-- test --></xml>" Await AssertFormatAsync(CreateMethod(code), CreateMethod(expected)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function XmlLiterals18() As Task Dim code = "Dim xml = <!-- test -->" Dim expected = " Dim xml = <!-- test -->" Await AssertFormatAsync(CreateMethod(code), CreateMethod(expected)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function XmlLiterals19() As Task Dim code = "Dim xml = <?xml-stylesheet type = ""text/xsl"" href = ""show_book.xsl""?>" Dim expected = " Dim xml = <?xml-stylesheet type = ""text/xsl"" href = ""show_book.xsl""?>" Await AssertFormatAsync(CreateMethod(code), CreateMethod(expected)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function XmlLiterals20() As Task Dim code = "Dim xml = <xml> <test/> <!-- test --> test <!-- test --> <?xml-stylesheet type = 'text/xsl' href = show_book.xsl?> </xml> " Dim expected = " Dim xml = <xml><test/><!-- test --> test <!-- test --><?xml-stylesheet type = 'text/xsl' href = show_book.xsl?></xml>" Await AssertFormatAsync(CreateMethod(code), CreateMethod(expected)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function XmlLiterals21() As Task Dim code = "Dim xml = <xml> <test/> <!-- test --> test <!-- test --> test 2 <?xml-stylesheet type = 'text/xsl' href = show_book.xsl?> </xml> " Dim expected = " Dim xml = <xml><test/><!-- test --> test <!-- test --> test 2 <?xml-stylesheet type = 'text/xsl' href = show_book.xsl?></xml>" Await AssertFormatAsync(CreateMethod(code), CreateMethod(expected)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function XmlLiterals22() As Task Dim code = "Dim xml = <![CDATA[ Can contain literal <XML> tags ]]> " Dim expected = " Dim xml = <![CDATA[ Can contain literal <XML> tags ]]>" Await AssertFormatAsync(CreateMethod(code), CreateMethod(expected)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function XmlLiterals23() As Task Dim code = "Dim xml = <xml> <test/> <!-- test --> test <![CDATA[ Can contain literal <XML> tags ]]> <!-- test --> test 2 <?xml-stylesheet type = 'text/xsl' href = show_book.xsl?> </xml> " Dim expected = " Dim xml = <xml><test/><!-- test --> test <![CDATA[ Can contain literal <XML> tags ]]><!-- test --> test 2 <?xml-stylesheet type = 'text/xsl' href = show_book.xsl?></xml>" Await AssertFormatAsync(CreateMethod(code), CreateMethod(expected)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function XmlLiterals24() As Task Dim code = "Dim xml = <xml> <test> <%= <xml> <test id=""42""><%=42 %> <%= ""hello""%> </test> </xml> %> </test> </xml>" Dim expected = " Dim xml = <xml><test><%= <xml><test id=""42""><%= 42 %><%= ""hello"" %></test></xml> %></test></xml>" Await AssertFormatAsync(CreateMethod(code), CreateMethod(expected)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function XmlLiterals25() As Task Dim code = "Dim xml = <xml attr=""1""> </xml> " Dim expected = " Dim xml = <xml attr=""1""></xml>" Await AssertFormatAsync(CreateMethod(code), CreateMethod(expected)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function XmlLiterals26() As Task Dim code = " Class C Sub Method(Optional ByVal i As Integer = 1) Dim q = <xml> <hello> </hello> </xml> End Sub End Class" Dim expected = " Class C Sub Method(Optional ByVal i As Integer = 1) Dim q = <xml> <hello> </hello> </xml> End Sub End Class" Await AssertFormatAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function XmlLiterals27() As Task Dim code = " Class C Sub Method(Optional ByVal i As Integer = 1) Dim q = <xml> <!-- Test --> <hello> Test <![CDATA[ ???? ]]> </hello> <!-- Test --> </xml> End Sub End Class" Dim expected = " Class C Sub Method(Optional ByVal i As Integer = 1) Dim q = <xml> <!-- Test --> <hello> Test <![CDATA[ ???? ]]> </hello> <!-- Test --></xml> End Sub End Class" Await AssertFormatAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function XmlLiterals28() As Task Dim code = " Class C Sub Method(Optional ByVal i As Integer = 1) Dim q = <xml> <!-- Test --> <hello> Test <![CDATA[ ???? ]]> </hello> <!-- Test --></xml> End Sub End Class" Dim expected = " Class C Sub Method(Optional ByVal i As Integer = 1) Dim q = <xml><!-- Test --><hello> Test <![CDATA[ ???? ]]> </hello> <!-- Test --></xml> End Sub End Class" Await AssertFormatAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function AttributeOnClass1() As Task Dim code = <Code><![CDATA[Namespace SomeNamespace <SomeAttribute()> Class Goo End Class End Namespace]]></Code> Dim expected = <Code><![CDATA[Namespace SomeNamespace <SomeAttribute()> Class Goo End Class End Namespace]]></Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <WorkItem(1087167, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1087167")> <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function MultipleAttributesOnClass() As Task Dim code = <Code><![CDATA[Namespace SomeNamespace <SomeAttribute()> <SomeAttribute2()> Class Goo End Class End Namespace]]></Code> Dim expected = <Code><![CDATA[Namespace SomeNamespace <SomeAttribute()> <SomeAttribute2()> Class Goo End Class End Namespace]]></Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <WorkItem(1087167, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1087167")> <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function MultipleAttributesOnParameter_1() As Task Dim code = <Code><![CDATA[Class Program Sub P( <Goo> <Goo> som As Integer) End Sub End Class Public Class Goo Inherits Attribute End Class]]></Code> Await AssertFormatLf2CrLfAsync(code.Value, code.Value) End Function <WorkItem(1087167, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1087167")> <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function MultipleAttributesOnParameter_2() As Task Dim code = <Code><![CDATA[Class Program Sub P( <Goo> som As Integer) End Sub End Class Public Class Goo Inherits Attribute End Class]]></Code> Await AssertFormatLf2CrLfAsync(code.Value, code.Value) End Function <WorkItem(1087167, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1087167")> <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function MultipleAttributesOnParameter_3() As Task Dim code = <Code><![CDATA[Class Program Sub P( <Goo> <Goo> som As Integer) End Sub End Class Public Class Goo Inherits Attribute End Class]]></Code> Dim expected = <Code><![CDATA[Class Program Sub P(<Goo> <Goo> som As Integer) End Sub End Class Public Class Goo Inherits Attribute End Class]]></Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function InheritsImplementsOnClass() As Task Dim code = <Code><![CDATA[Class SomeClass Inherits BaseClass Implements IGoo End Class]]></Code> Dim expected = <Code><![CDATA[Class SomeClass Inherits BaseClass Implements IGoo End Class]]></Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function InheritsImplementsWithGenericsOnClass() As Task Dim code = <Code><![CDATA[Class SomeClass(Of T) Inherits BaseClass (Of T) Implements IGoo ( Of String, T) End Class]]></Code> Dim expected = <Code><![CDATA[Class SomeClass(Of T) Inherits BaseClass(Of T) Implements IGoo(Of String, T) End Class]]></Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function InheritsOnInterface() As Task Dim code = <Code>Interface I Inherits J End Interface Interface J End Interface</Code> Dim expected = <Code>Interface I Inherits J End Interface Interface J End Interface</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function WhitespaceMethodParens() As Task Dim code = <Code>Class SomeClass Sub Goo ( x As Integer ) Goo ( 42 ) End Sub End Class</Code> Dim expected = <Code>Class SomeClass Sub Goo(x As Integer) Goo(42) End Sub End Class</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function WhitespaceKeywordParens() As Task Dim code = <Code>Class SomeClass Sub Goo If(x And(y Or(z)) Then Stop End Sub End Class</Code> Dim expected = <Code>Class SomeClass Sub Goo If (x And (y Or (z)) Then Stop End Sub End Class</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function WhitespaceLiteralAndTypeCharacters() As Task Dim code = <Code><![CDATA[Class SomeClass Sub Method() Dim someHex = &HFF Dim someOct = &O33 Dim someShort = 42S+42S Dim someInteger% = 42%+42% Dim someOtherInteger = 42I+42I Dim someLong& = 42&+42& Dim someOtherLong = 42L+42L Dim someDecimal@ = 42.42@+42.42@ Dim someOtherDecimal = 42.42D + 42.42D Dim someSingle! = 42.42!+42.42! Dim someOtherSingle = 42.42F+42.42F Dim someDouble# = 42.4242#+42.4242# Dim someOtherDouble = 42.42R+42.42R Dim unsignedShort = 42US+42US Dim unsignedLong = 42UL+42UL Dim someDate = #3/3/2011 12:42:00 AM#+#2/2/2011# Dim someChar = "x"c Dim someString$ = "42"+"42" Dim r = Goo&() Dim s = GooString$() End Sub End Class]]></Code> Dim expected = <Code><![CDATA[Class SomeClass Sub Method() Dim someHex = &HFF Dim someOct = &O33 Dim someShort = 42S + 42S Dim someInteger% = 42% + 42% Dim someOtherInteger = 42I + 42I Dim someLong& = 42& + 42& Dim someOtherLong = 42L + 42L Dim someDecimal@ = 42.42@ + 42.42@ Dim someOtherDecimal = 42.42D + 42.42D Dim someSingle! = 42.42! + 42.42! Dim someOtherSingle = 42.42F + 42.42F Dim someDouble# = 42.4242# + 42.4242# Dim someOtherDouble = 42.42R + 42.42R Dim unsignedShort = 42US + 42US Dim unsignedLong = 42UL + 42UL Dim someDate = #3/3/2011 12:42:00 AM# + #2/2/2011# Dim someChar = "x"c Dim someString$ = "42" + "42" Dim r = Goo&() Dim s = GooString$() End Sub End Class]]></Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function WhitespaceNullable() As Task Dim code = <Code>Class Goo Property someprop As Integer ? Function Method(arg1 ? As Integer) As Integer ? Dim someVariable ? As Integer End Function End Class</Code> Dim expected = <Code>Class Goo Property someprop As Integer? Function Method(arg1? As Integer) As Integer? Dim someVariable? As Integer End Function End Class</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function WhitespaceArrayBraces() As Task Dim code = <Code>Class Goo Sub Method() Dim arr() ={ 1, 2, 3 } End Sub End Class</Code> Dim expected = <Code>Class Goo Sub Method() Dim arr() = {1, 2, 3} End Sub End Class</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function WhitespaceStatementSeparator() As Task Dim code = <Code>Class Goo Sub Method() Dim x=2:Dim y=3:Dim z=4 End Sub End Class</Code> Dim expected = <Code>Class Goo Sub Method() Dim x = 2 : Dim y = 3 : Dim z = 4 End Sub End Class</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function WhitespaceRemovedBeforeComment() As Task Dim code = <Code>Class Goo Sub Method() Dim a = 4 ' This is a comment that doesn't move ' This is a comment that will have some preceding whitespace removed Dim y = 4 End Sub End Class</Code> Dim expected = <Code>Class Goo Sub Method() Dim a = 4 ' This is a comment that doesn't move ' This is a comment that will have some preceding whitespace removed Dim y = 4 End Sub End Class</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function ReFormatWithTabsEnabled1() As Task Dim code = "Class SomeClass" + vbCrLf + " Sub Goo()" + vbCrLf + " Goo()" + vbCrLf + " End Sub" + vbCrLf + "End Class" Dim expected = "Class SomeClass" + vbCrLf + vbTab + "Sub Goo()" + vbCrLf + vbTab + vbTab + "Goo()" + vbCrLf + vbTab + "End Sub" + vbCrLf + "End Class" Dim optionSet = New OptionsCollection(LanguageNames.VisualBasic) From { {FormattingOptions2.UseTabs, True}, {FormattingOptions2.TabSize, 4}, {FormattingOptions2.IndentationSize, 4} } Await AssertFormatAsync(code, expected, changedOptionSet:=optionSet) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function ReFormatWithTabsEnabled2() As Task ' tabs after the first token on a line should be converted to spaces Dim code = "Class SomeClass" + vbCrLf + vbTab + "Sub Goo()" + vbCrLf + vbTab + vbTab + "Goo()" + vbTab + vbTab + "'comment" + vbCrLf + vbTab + "End Sub" + vbCrLf + "End Class" Dim expected = "Class SomeClass" + vbCrLf + vbTab + "Sub Goo()" + vbCrLf + vbTab + vbTab + "Goo() 'comment" + vbCrLf + vbTab + "End Sub" + vbCrLf + "End Class" Dim optionSet = New OptionsCollection(LanguageNames.VisualBasic) From { {FormattingOptions2.UseTabs, True}, {FormattingOptions2.TabSize, 4}, {FormattingOptions2.IndentationSize, 4} } Await AssertFormatAsync(code, expected, changedOptionSet:=optionSet) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function ReFormatWithTabsEnabled3() As Task ' This is a regression test for the assert: it may still not pass after the assert is fixed. Dim code = "Class SomeClass" + vbCrLf + " Sub Goo() ' Comment" + vbCrLf + " Goo() " + vbCrLf + " End Sub" + vbCrLf + "End Class" Dim expected = "Class SomeClass" + vbCrLf + vbTab + "Sub Goo() ' Comment" + vbCrLf + vbTab + vbTab + "Goo()" + vbCrLf + vbTab + "End Sub" + vbCrLf + "End Class" Dim optionSet = New OptionsCollection(LanguageNames.VisualBasic) From { {FormattingOptions2.UseTabs, True}, {FormattingOptions2.TabSize, 4}, {FormattingOptions2.IndentationSize, 4} } Await AssertFormatAsync(code, expected, changedOptionSet:=optionSet) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function ReFormatWithTabsEnabled4() As Task Dim code = "Class SomeClass" + vbCrLf + " Sub Goo()" + vbCrLf + " Dim abc = Sub()" + vbCrLf + " Console.WriteLine(42)" + vbCrLf + " End Sub" + vbCrLf + " End Sub" + vbCrLf + "End Class" Dim expected = "Class SomeClass" + vbCrLf + vbTab + "Sub Goo()" + vbCrLf + vbTab + vbTab + "Dim abc = Sub()" + vbCrLf + vbTab + vbTab + vbTab + vbTab + vbTab + " Console.WriteLine(42)" + vbCrLf + vbTab + vbTab + vbTab + vbTab + " End Sub" + vbCrLf + vbTab + "End Sub" + vbCrLf + "End Class" Dim optionSet = New OptionsCollection(LanguageNames.VisualBasic) From { {FormattingOptions2.UseTabs, True}, {FormattingOptions2.TabSize, 4}, {FormattingOptions2.IndentationSize, 4} } Await AssertFormatAsync(code, expected, changedOptionSet:=optionSet) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function ReFormatWithTabsEnabled5() As Task Dim code = "Class SomeClass" + vbCrLf + " Sub Goo()" + vbCrLf + " Dim abc = 2 + " + vbCrLf + " 3 + " + vbCrLf + " 4 " + vbCrLf + " End Sub" + vbCrLf + "End Class" Dim expected = "Class SomeClass" + vbCrLf + vbTab + "Sub Goo()" + vbCrLf + vbTab + vbTab + "Dim abc = 2 +" + vbCrLf + vbTab + vbTab + vbTab + vbTab + vbTab + "3 +" + vbCrLf + vbTab + vbTab + vbTab + vbTab + " 4" + vbCrLf + vbTab + "End Sub" + vbCrLf + "End Class" Dim optionSet = New OptionsCollection(LanguageNames.VisualBasic) From { {FormattingOptions2.UseTabs, True}, {FormattingOptions2.TabSize, 4}, {FormattingOptions2.IndentationSize, 4} } Await AssertFormatAsync(code, expected, changedOptionSet:=optionSet) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> <WorkItem(10742, "https://github.com/dotnet/roslyn/issues/10742")> Public Async Function ReFormatWithTabsEnabled6() As Task Dim code = "Class SomeClass" + vbCrLf + " Sub Goo() ' Comment" + vbCrLf + " Goo()" + vbCrLf + " End Sub" + vbCrLf + "End Class" Dim expected = "Class SomeClass" + vbCrLf + vbTab + "Sub Goo() ' Comment" + vbCrLf + vbTab + vbTab + "Goo()" + vbCrLf + vbTab + "End Sub" + vbCrLf + "End Class" Dim optionSet = New OptionsCollection(LanguageNames.VisualBasic) From { {FormattingOptions2.UseTabs, True}, {FormattingOptions2.TabSize, 4}, {FormattingOptions2.IndentationSize, 4} } Await AssertFormatAsync(code, expected, changedOptionSet:=optionSet) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function ReFormatWithTabsDisabled() As Task Dim code = "Class SomeClass" + vbCrLf + vbTab + "Sub Goo()" + vbCrLf + vbTab + vbTab + "Goo()" + vbCrLf + vbTab + "End Sub" + vbCrLf + "End Class" Dim expected = "Class SomeClass" + vbCrLf + " Sub Goo()" + vbCrLf + " Goo()" + vbCrLf + " End Sub" + vbCrLf + "End Class" Dim optionSet = New OptionsCollection(LanguageNames.VisualBasic) From { {FormattingOptions2.UseTabs, False}, {FormattingOptions2.TabSize, 4}, {FormattingOptions2.IndentationSize, 4} } Await AssertFormatAsync(code, expected, changedOptionSet:=optionSet) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function ReFormatWithDifferentIndent1() As Task Dim code = "Class SomeClass" + vbCrLf + " Sub Goo()" + vbCrLf + " Goo()" + vbCrLf + " End Sub" + vbCrLf + "End Class" Dim expected = "Class SomeClass" + vbCrLf + " Sub Goo()" + vbCrLf + " Goo()" + vbCrLf + " End Sub" + vbCrLf + "End Class" Dim optionSet = New OptionsCollection(LanguageNames.VisualBasic) From { {FormattingOptions2.UseTabs, False}, {FormattingOptions2.TabSize, 4}, {FormattingOptions2.IndentationSize, 2} } Await AssertFormatAsync(code, expected, changedOptionSet:=optionSet) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function ReFormatWithDifferentIndent2() As Task Dim code = "Class SomeClass" + vbCrLf + " Sub Goo()" + vbCrLf + " Goo()" + vbCrLf + " End Sub" + vbCrLf + "End Class" Dim expected = "Class SomeClass" + vbCrLf + " Sub Goo()" + vbCrLf + " Goo()" + vbCrLf + " End Sub" + vbCrLf + "End Class" Dim optionSet = New OptionsCollection(LanguageNames.VisualBasic) From { {FormattingOptions2.UseTabs, False}, {FormattingOptions2.TabSize, 4}, {FormattingOptions2.IndentationSize, 6} } Await AssertFormatAsync(code, expected, changedOptionSet:=optionSet) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function ReFormatWithTabsEnabledSmallIndentAndLargeTab() As Task Dim code = "Class SomeClass" + vbCrLf + " Sub Goo()" + vbCrLf + " Goo()" + vbCrLf + " End Sub" + vbCrLf + "End Class" Dim expected = "Class SomeClass" + vbCrLf + " Sub Goo()" + vbCrLf + vbTab + " Goo()" + vbCrLf + " End Sub" + vbCrLf + "End Class" Dim optionSet = New OptionsCollection(LanguageNames.VisualBasic) From { {FormattingOptions2.UseTabs, True}, {FormattingOptions2.TabSize, 3}, {FormattingOptions2.IndentationSize, 2} } Await AssertFormatAsync(code, expected, changedOptionSet:=optionSet) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function RegressionCommentFollowsSubsequentIndent4173() As Task Dim code = "Class SomeClass" + vbCrLf + " Sub Goo()" + vbCrLf + " 'comment" + vbCrLf + " End Sub" + vbCrLf + "End Class" Dim expected = "Class SomeClass" + vbCrLf + " Sub Goo()" + vbCrLf + " 'comment" + vbCrLf + " End Sub" + vbCrLf + "End Class" Await AssertFormatAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function FormatUsingOverloads() As Task Dim code = "Class SomeClass" + vbCrLf + " Sub Goo()" + vbCrLf + "Goo() " + vbCrLf + " End Sub" + vbCrLf + "End Class" Dim expected = "Class SomeClass" + vbCrLf + " Sub Goo()" + vbCrLf + " Goo()" + vbCrLf + " End Sub" + vbCrLf + "End Class" Await AssertFormatUsingAllEntryPointsAsync(code, expected) End Function <WorkItem(538533, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538533")> <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix4173_1() As Task Dim code = "Dim a = <xml> <%=<xml></xml>%> </xml>" Dim expected = " Dim a = <xml><%= <xml></xml> %></xml>" Await AssertFormatAsync(CreateMethod(code), CreateMethod(expected)) End Function <WorkItem(538533, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538533")> <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix4173_2() As Task Dim code = <Code>Class Goo Sub Goo() ' Comment Goo() End Sub End Class</Code> Dim expected = <Code>Class Goo Sub Goo() ' Comment Goo() End Sub End Class</Code> Dim optionSet = New OptionsCollection(LanguageNames.VisualBasic) From { {FormattingOptions2.UseTabs, True} } Await AssertFormatLf2CrLfAsync(code.Value, expected.Value, optionSet) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function FormatUsingAutoGeneratedCodeOperationProvider() As Task Dim code = "Class SomeClass" + vbCrLf + " Sub Goo()" + vbCrLf + "Goo() " + vbCrLf + " End Sub" + vbCrLf + "End Class" Dim expected = "Class SomeClass" + vbCrLf + " Sub Goo()" + vbCrLf + " Goo()" + vbCrLf + " End Sub" + vbCrLf + "End Class" Await AssertFormatAsync(code, expected) End Function <WorkItem(538533, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538533")> <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix4173_3() As Task Dim code = " Class C Sub Goo() Dim xml = <xml><code><node></node></code></xml> Dim j = From node In xml.<code> Select node.@att End Sub End Class" Dim expected = " Class C Sub Goo() Dim xml = <xml><code><node></node></code></xml> Dim j = From node In xml.<code> Select node.@att End Sub End Class" Await AssertFormatAsync(code, expected) End Function <WorkItem(538533, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538533")> <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix4173_4() As Task Dim code = <code>Class C Sub Main(args As String()) Dim r = 2 'goo End Sub End Class</code> Dim expected = <code>Class C Sub Main(args As String()) Dim r = 2 'goo End Sub End Class</code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <WorkItem(538533, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538533")> <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix4173_5() As Task Dim code = <code>Module Module1 Public Sub goo () End Sub End Module</code> Await AssertFormatLf2CrLfAsync(code.Value, code.Value) End Function <WorkItem(538533, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538533")> <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix4173_6() As Task Dim code = <code>Module module1 #If True Then #End If: goo() End Module</code> Await AssertFormatLf2CrLfAsync(code.Value, code.Value) End Function <WorkItem(538533, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538533")> <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix4173_7() As Task Dim code = <code>Module Module1 Sub Main() Dim x = Sub() End Sub : Dim y = Sub() End Sub ' Incorrect indent End Sub End Module</code> Dim expected = <code>Module Module1 Sub Main() Dim x = Sub() End Sub : Dim y = Sub() End Sub ' Incorrect indent End Sub End Module</code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <WorkItem(538533, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538533")> <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix4173_8() As Task Dim code = <code>Module Module1 Sub Main() ' ' End Sub End Module</code> Dim expected = <code>Module Module1 Sub Main() ' ' End Sub End Module</code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <WorkItem(538533, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538533")> <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix4173_9() As Task Dim code = <code>Module Module1 Sub Main() #If True Then Dim goo as Integer #End If End Sub End Module</code> Dim expected = <code>Module Module1 Sub Main() #If True Then Dim goo as Integer #End If End Sub End Module</code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <WorkItem(538772, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538772")> <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix4482() As Task Dim code = <code>_' Public Function GroupBy(Of K, R)( _ _' ByVal key As KeyFunc(Of K), _ _' ByVal selector As SelectorFunc(Of K, QueryableCollection(Of T), R)) _ ' As QueryableCollection(Of R)</code> Await AssertFormatLf2CrLfAsync(code.Value, code.Value) End Function <WorkItem(538754, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538754")> <Fact> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix4459() As Task Dim code = <Code>Option Strict Off Module Module1 Sub Main() End Sub Dim x As New List(Of Action(Of Integer)) From {Sub(a As Integer) Dim z As Integer = New Integer End Sub, Sub() IsNothing(Nothing), Function() As Integer Dim z As Integer = New Integer End Function} End Module </Code> Dim expected = <Code>Option Strict Off Module Module1 Sub Main() End Sub Dim x As New List(Of Action(Of Integer)) From {Sub(a As Integer) Dim z As Integer = New Integer End Sub, Sub() IsNothing(Nothing), Function() As Integer Dim z As Integer = New Integer End Function} End Module </Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <WorkItem(538675, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538675")> <Fact> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix4352() As Task Dim code = <Code>Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) 0: End End Sub End Module</Code> Dim expected = <Code>Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) 0: End End Sub End Module</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <WorkItem(538703, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538703")> <Fact> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix4394() As Task Await AssertFormatAsync(" ''' <summary> ''' ''' </summary> Module Program Sub Main(args As String()) End Sub End Module", " ''' <summary> ''' ''' </summary> Module Program Sub Main(args As String()) End Sub End Module") End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function GetTypeTest() As Task Dim code = "Dim a = GetType ( Object )" Dim expected = " Dim a = GetType(Object)" Await AssertFormatAsync(CreateMethod(code), CreateMethod(expected)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function NewObjectTest() As Task Dim code = "Dim a = New Object ( )" Dim expected = " Dim a = New Object()" Await AssertFormatAsync(CreateMethod(code), CreateMethod(expected), debugMode:=True) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function CTypeTest() As Task Dim code = "Dim a = CType ( args , String ( ) ) " Dim expected = " Dim a = CType(args, String())" Await AssertFormatAsync(CreateMethod(code), CreateMethod(expected)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function TernaryConditionTest() As Task Dim code = "Dim a = If ( True , 1, 2)" Dim expected = " Dim a = If(True, 1, 2)" Await AssertFormatAsync(CreateMethod(code), CreateMethod(expected)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function TryCastTest() As Task Dim code = "Dim a = TryCast ( args , String())" Dim expected = " Dim a = TryCast(args, String())" Await AssertFormatAsync(CreateMethod(code), CreateMethod(expected)) End Function <WorkItem(538703, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538703")> <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix4394_1() As Task Dim code = " Class C '''<summary> ''' Test Method '''</summary> Sub Method() End Sub End Class" Dim expected = " Class C '''<summary> ''' Test Method '''</summary> Sub Method() End Sub End Class" Await AssertFormatAsync(code, expected) End Function <WorkItem(538889, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538889")> <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix4639() As Task Dim code = "Imports <xmlns=""http://DefaultNamespace"" > " Dim expected = "Imports <xmlns=""http://DefaultNamespace"">" Await AssertFormatAsync(code, expected) End Function <WorkItem(538891, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538891")> <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix4641() As Task Dim code = <Code>Module module1 Structure C End Structure Sub goo() Dim cc As C ? = New C ? ( ) End Sub End Module</Code> Dim expected = <Code>Module module1 Structure C End Structure Sub goo() Dim cc As C? = New C?() End Sub End Module</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <WorkItem(538892, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538892")> <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix4642() As Task Dim code = <Code>_ </Code> Dim expected = <Code> _ </Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <WorkItem(538894, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538894")> <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix4644() As Task Dim code = <Code>Option Explicit Off Module Module1 Sub Main() Dim mmm = Sub(ByRef x As String, _ y As Integer) Console.WriteLine(x &amp; y) End Sub, zzz = Sub(y, _ x) mmm(y, _ x) End Sub lll = Sub(x _ ) Console.WriteLine(x) End Sub End Sub End Module</Code> Dim expected = <Code>Option Explicit Off Module Module1 Sub Main() Dim mmm = Sub(ByRef x As String, _ y As Integer) Console.WriteLine(x &amp; y) End Sub, zzz = Sub(y, _ x) mmm(y, _ x) End Sub lll = Sub(x _ ) Console.WriteLine(x) End Sub End Sub End Module</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <WorkItem(538897, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538897")> <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix4647() As Task Dim code = <Code>Option Explicit Off Module Module1 Sub Main() Dim mmm = Sub(ByRef x As String, _ y As Integer) Console.WriteLine(x &amp; y) End Sub, zzz = Sub(y, _ x) mmm(y, _ x) End Sub : Dim _ lll = Sub(x _ ) Console.WriteLine(x) End Sub End Sub End Module </Code> Dim expected = <Code>Option Explicit Off Module Module1 Sub Main() Dim mmm = Sub(ByRef x As String, _ y As Integer) Console.WriteLine(x &amp; y) End Sub, zzz = Sub(y, _ x) mmm(y, _ x) End Sub : Dim _ lll = Sub(x _ ) Console.WriteLine(x) End Sub End Sub End Module </Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <WorkItem(538962, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538962")> <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function WorkItem4737() As Task Dim code = "Dim x = <?xml version =""1.0""?><code></code>" Dim expected = " Dim x = <?xml version=""1.0""?><code></code>" Await AssertFormatAsync(CreateMethod(code), CreateMethod(expected)) End Function <WorkItem(539031, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539031")> <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix4826() As Task Dim code = <Code>Imports &lt;xmlns:a=""&gt; Module Program Sub Main() Dim x As New Dictionary(Of String, XElement) From {{"Root", &lt;x/&gt;}} x!Root%.&lt;nodes&gt;...&lt;a:subnodes&gt;.@a:b.ToString$ With x !Root.@a:b.EndsWith("").ToString$() With !Root .&lt;b&gt;.Value.StartsWith("") ...&lt;c&gt;(0).Value.ToString$() .ToString() Call .ToString() End With End With Dim buffer As New Byte(1023) {} End Sub End Module </Code> Await AssertFormatLf2CrLfAsync(code.Value, code.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function Parentheses() As Task Dim code = <Code>Class GenericMethod Sub Method(Of T)(t1 As T) NewMethod(Of T)(t1) End Sub Private Shared Sub NewMethod(Of T)(t1 As T) Dim a As T a = t1 End Sub End Class </Code> Await AssertFormatLf2CrLfAsync(code.Value, code.Value) End Function <WorkItem(539170, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539170")> <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix5022() As Task Dim code = <Code>Class A : _ Dim x End Class</Code> Dim expected = <Code>Class A : _ Dim x End Class</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <WorkItem(539324, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539324")> <Fact> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix5232() As Task Dim code = <Code>Imports System Module M Sub Main() If False Then If True Then Else Else Console.WriteLine(1) End Sub End Module</Code> Dim expected = <Code>Imports System Module M Sub Main() If False Then If True Then Else Else Console.WriteLine(1) End Sub End Module</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <WorkItem(539353, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539353")> <Fact> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix5270() As Task Dim code = <Code>Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Dim q = 2 + REM 3 End Sub End Module</Code> Dim expected = <Code>Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Dim q = 2 + REM 3 End Sub End Module</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <WorkItem(539358, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539358")> <Fact> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix5277() As Task Dim code = <Code> #If True Then #End If </Code> Dim expected = <Code> #If True Then #End If </Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <WorkItem(539455, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539455")> <Fact> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix5432() As Task Dim code = <Code>Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) dim q = 2 + _ 'comment End Sub End Module</Code> Dim expected = <Code>Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) dim q = 2 + _ 'comment End Sub End Module</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <WorkItem(539351, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539351")> <Fact> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix5268() As Task Dim code = <Code> #If True _ </Code> Await AssertFormatLf2CrLfAsync(code.Value, code.Value) End Function <WorkItem(539351, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539351")> <Fact> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix5268_1() As Task Dim code = <Code>Imports System Imports System.Collections.Generic Imports System.Linq Module Program #If True _ End Module</Code> Await AssertFormatLf2CrLfAsync(code.Value, code.Value) End Function <WorkItem(539473, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539473")> <Fact> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix5456() As Task Dim code = <Code>Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main() Dim goo = New With {.goo = "goo",.bar = "bar"} End Sub End Module</Code> Dim expected = <Code>Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main() Dim goo = New With {.goo = "goo", .bar = "bar"} End Sub End Module</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <WorkItem(539474, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539474")> <Fact> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix5457() As Task Dim code = <Code>Module module1 Sub main() Dim var1 As New Class1 [|var1.goofoo = 42 End Sub Sub something() something() End Sub End Module Public Class Class1 Public goofoo As String|] End Class</Code> Dim expected = <Code>Module module1 Sub main() Dim var1 As New Class1 var1.goofoo = 42 End Sub Sub something() something() End Sub End Module Public Class Class1 Public goofoo As String End Class</Code> Await AssertFormatSpanAsync(code.Value.Replace(vbLf, vbCrLf), expected.Value.Replace(vbLf, vbCrLf)) End Function <WorkItem(539503, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539503")> <Fact> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix5492() As Task Dim code = <Code>Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Dim classNum As Integer 'comment : classNum += 1 : Dim i As Integer End Sub End Module </Code> Dim expected = <Code>Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Dim classNum As Integer 'comment : classNum += 1 : Dim i As Integer End Sub End Module </Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <WorkItem(539508, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539508")> <Fact> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix5497() As Task Dim code = <Code>Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) : 'comment End Sub End Module</Code> Dim expected = <Code>Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) : 'comment End Sub End Module</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <WorkItem(539581, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539581")> <Fact> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix5594() As Task Dim code = <Code> &lt;Assembly : MyAttr()&gt; &lt;Module : MyAttr()&gt; Module Module1 Class MyAttr Inherits Attribute End Class Sub main() End Sub End Module </Code> Dim expected = <Code> &lt;Assembly: MyAttr()&gt; &lt;Module: MyAttr()&gt; Module Module1 Class MyAttr Inherits Attribute End Class Sub main() End Sub End Module </Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <WorkItem(539582, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539582")> <Fact> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix5595() As Task Dim code = <Code> Imports System.Xml &lt;SomeAttr()&gt; Module Module1 Sub Main() End Sub End Module </Code> Dim expected = <Code> Imports System.Xml &lt;SomeAttr()&gt; Module Module1 Sub Main() End Sub End Module </Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <WorkItem(539616, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539616")> <Fact> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix5637() As Task Dim code = <Code>Public Class Class1 'this line is comment line Sub sub1(ByVal aa As Integer) End Sub End Class</Code> Dim expected = <Code>Public Class Class1 'this line is comment line Sub sub1(ByVal aa As Integer) End Sub End Class</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function XmlTest() As Task Await AssertFormatAsync(" Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main() Dim book = </book > GetXml( </book >) End Sub End Module", " Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main() Dim book = </book> GetXml( </book>) End Sub End Module") End Function <Fact> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function XmlDocument() As Task Await AssertFormatAsync(" Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main() Dim book = <?xml version=""1.0""?> <?fff fff?> <!-- ffff --> <book/> <!-- last comment! yeah :) --> End Sub End Module", " Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main() Dim book = <?xml version=""1.0""?> <?fff fff?> <!-- ffff --> <book/> <!-- last comment! yeah :) --> End Sub End Module") End Function <Fact> <WorkItem(539458, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539458")> <WorkItem(539459, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539459")> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function XmlProcessingInstruction() As Task Await AssertFormatAsync(" Module Program Sub Main() Dim x = <?xml version=""1.0""?> <?blah?> <xml></xml> End Sub End Module", " Module Program Sub Main() Dim x = <?xml version=""1.0""?> <?blah?> <xml></xml> End Sub End Module") End Function <WorkItem(539463, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539463")> <WorkItem(530597, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530597")> <Fact> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function XmlTest5442() As Task Using workspace = New AdhocWorkspace() Dim inputOutput = " Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Dim goo = _ <LongBook> <%= _ From i In <were><a><b><c></c></b></a></were> _ Where i IsNot Nothing _ Select _ <f> <g> <f> </f> </g> </f> _ %> </LongBook> End Sub End Module" Dim project = workspace.CurrentSolution.AddProject("Project", "Project.dll", LanguageNames.VisualBasic) Dim document = project.AddDocument("Document", SourceText.From(inputOutput)) Dim root = Await document.GetSyntaxRootAsync() ' format first time Dim result = Formatter.GetFormattedTextChanges(root, workspace) AssertResult(inputOutput, Await document.GetTextAsync(), result) Dim document2 = document.WithText((Await document.GetTextAsync()).WithChanges(result)) Dim root2 = Await document2.GetSyntaxRootAsync() ' format second time Dim result2 = Formatter.GetFormattedTextChanges(root, workspace) AssertResult(inputOutput, Await document2.GetTextAsync(), result2) End Using End Function <WorkItem(539687, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539687")> <Fact> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix5731() As Task Dim code = <Code>Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) If True Then : 'comment End If End Sub End Module</Code> Dim expected = <Code>Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) If True Then : 'comment End If End Sub End Module</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <WorkItem(539545, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539545")> <Fact> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix5547() As Task Dim code = <Code>Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Select Case True Case True 'comment End Select End Sub End Module</Code> Dim expected = <Code>Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Select Case True Case True 'comment End Select End Sub End Module</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <WorkItem(539453, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539453")> <Fact> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix5430() As Task Dim code = " Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Dim abc = <xml> <video>video1</video> </xml> Dim r = From q In abc...<video> _ End Sub End Module" Await AssertFormatAsync(code, code) End Function <WorkItem(539889, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539889")> <Fact> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix5989() As Task Dim code = <Code>Imports System Module Program Sub Main(args As String()) Console.WriteLine(CInt (42)) End Sub End Module </Code> Dim expected = <Code>Imports System Module Program Sub Main(args As String()) Console.WriteLine(CInt(42)) End Sub End Module </Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <WorkItem(539409, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539409")> <Fact> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix6367() As Task Dim code = <Code>Module Program Sub Main(args As String()) Dim a As Integer = 1'Test End Sub End Module </Code> Dim expected = <Code>Module Program Sub Main(args As String()) Dim a As Integer = 1 'Test End Sub End Module </Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <WorkItem(539409, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539409")> <Fact> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix6367_1() As Task Dim code = <Code>Module Program Sub Main(args As String()) Dim a As Integer = 1 'Test End Sub End Module </Code> Await AssertFormatLf2CrLfAsync(code.Value, code.Value) End Function <WorkItem(540678, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540678")> <Fact> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix7023_1() As Task Dim code = <Code>Module Program Public Operator +(x As Integer, y As Integer) Console.WriteLine("GOO") End Operator End Module </Code> Await AssertFormatLf2CrLfAsync(code.Value, code.Value) End Function <Fact> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function XmlTextWithEmbededExpression1() As Task Await AssertFormatAsync(" Class C Sub Method() Dim q = <xml> test <xml2><%= <xml3><xml4> </xml4></xml3> %></xml2> </xml> End Sub End Class", " Class C Sub Method() Dim q = <xml> test <xml2><%= <xml3><xml4> </xml4></xml3> %></xml2> </xml> End Sub End Class") End Function <Fact> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function XmlTextWithEmbededExpression2() As Task Await AssertFormatAsync(" Class C2 Sub Method() Dim q = <xml> tst <%= <xml2><xml3><xml4> </xml4></xml3> </xml2> %> </xml> End Sub End Class", " Class C2 Sub Method() Dim q = <xml> tst <%= <xml2><xml3><xml4> </xml4></xml3> </xml2> %> </xml> End Sub End Class") End Function <Fact> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function XmlText() As Task Await AssertFormatAsync(" Class C22 Sub Method() Dim q = <xml> tst <xml2><xml3><xml4> </xml4></xml3> </xml2> </xml> End Sub End Class", " Class C22 Sub Method() Dim q = <xml> tst <xml2><xml3><xml4> </xml4></xml3> </xml2> </xml> End Sub End Class") End Function <Fact> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function XmlTextWithComment() As Task Await AssertFormatAsync(" Class C223 Sub Method() Dim q = <xml> <!-- --> t st <xml2><xml3><xml4> </xml4></xml3> </xml2> </xml> End Sub End Class", " Class C223 Sub Method() Dim q = <xml> <!-- --> t st <xml2><xml3><xml4> </xml4></xml3> </xml2> </xml> End Sub End Class") End Function <WorkItem(541628, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541628")> <Fact> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function MultipleControlVariables() As Task Dim code = <Code>Module Program Sub Main(args As String()) Dim i, j As Integer For i = 0 To 1 For j = 0 To 1 Next j, i End Sub End Module</Code> Dim expected = <Code>Module Program Sub Main(args As String()) Dim i, j As Integer For i = 0 To 1 For j = 0 To 1 Next j, i End Sub End Module</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <WorkItem(541561, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541561")> <Fact> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function ColonTrivia() As Task Dim code = <Code>Module Program Sub Goo3() : End Sub Sub Main() End Sub End Module</Code> Dim expected = <Code>Module Program Sub Goo3() : End Sub Sub Main() End Sub End Module</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function MemberAccessInObjectMemberInitializer() As Task Dim code = <Code>Module Program Sub Main() Dim aw = New With {.a = 1, .b = 2+.a} End Sub End Module</Code> Dim expected = <Code>Module Program Sub Main() Dim aw = New With {.a = 1, .b = 2 + .a} End Sub End Module</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BinaryConditionalExpression() As Task Dim code = <Code>Module Program Sub Main() Dim x = If(Nothing, "") ' Inline x.ToString End Sub End Module</Code> Dim expected = <Code>Module Program Sub Main() Dim x = If(Nothing, "") ' Inline x.ToString End Sub End Module</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact> <WorkItem(539574, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539574")> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function Preprocessors() As Task Dim code = <Code>Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) #Const [PUBLIC] = 3 #Const goo = 23 #Const goo2=23 #Const goo3 = 23 #Const goo4 = 23 #Const goo5 = 23 End Sub End Module</Code> Dim expected = <Code>Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) #Const [PUBLIC] = 3 #Const goo = 23 #Const goo2 = 23 #Const goo3 = 23 #Const goo4 = 23 #Const goo5 = 23 End Sub End Module</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact> <WorkItem(10027, "DevDiv_Projects/Roslyn")> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function RandomCode1() As Task Dim code = <Code>'Imports alias 'goo' conflicts with 'goo' declared in the root namespace'</Code> Dim expected = <Code>'Imports alias 'goo' conflicts with 'goo' declared in the root namespace'</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact> <WorkItem(10027, "DevDiv_Projects/Roslyn")> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function RandomCode2() As Task Dim code = <Code>'Imports alias 'goo' conflicts with 'goo' declared in the root namespace'</Code> Dim expected = <Code>'Imports alias 'goo' conflicts with 'goo' declared in the root namespace'</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact> <WorkItem(542698, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542698")> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function ColonTrivia1() As Task Dim code = <Code>Imports _ System.Collections.Generic _ : : Imports _ System Imports System.Linq Module Program Sub Main(args As String()) Console.WriteLine("TEST") End Sub End Module </Code> Dim expected = <Code>Imports _ System.Collections.Generic _ : : Imports _ System Imports System.Linq Module Program Sub Main(args As String()) Console.WriteLine("TEST") End Sub End Module </Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact> <WorkItem(542698, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542698")> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function ColonTrivia2() As Task Dim code = <Code>Imports _ System.Collections.Generic _ : : Imports _ System Imports System.Linq Module Program Sub Main(args As String()) Console.WriteLine("TEST") End Sub End Module </Code> Await AssertFormatLf2CrLfAsync(code.Value, code.Value) End Function <Fact> <WorkItem(543197, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543197")> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function KeyInAnonymousType() As Task Dim code = <Code>Class C Sub S() Dim product = New With {Key.Name = "goo"} End Sub End Class </Code> Dim expected = <Code>Class C Sub S() Dim product = New With {Key .Name = "goo"} End Sub End Class </Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact> <WorkItem(544008, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544008")> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function TestGetXmlNamespace() As Task Dim code = <Code>Class C Sub S() Dim x = GetXmlNamespace(asdf) End Sub End Class </Code> Dim expected = <Code>Class C Sub S() Dim x = GetXmlNamespace(asdf) End Sub End Class </Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact> <WorkItem(539409, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539409")> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function StructuredTrivia() As Task Dim code = <Code>#const goo=2.0d</Code> Dim expected = <Code>#const goo = 2.0d</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function FormatComment1() As Task Dim code = <Code>Class A Sub Test() Console.WriteLine() : ' test Console.WriteLine() End Sub End Class</Code> Dim expected = <Code>Class A Sub Test() Console.WriteLine() : ' test Console.WriteLine() End Sub End Class</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function FormatComment2() As Task Dim code = <Code>Class A Sub Test() Console.WriteLine() ' test Console.WriteLine() End Sub End Class</Code> Dim expected = <Code>Class A Sub Test() Console.WriteLine() ' test Console.WriteLine() End Sub End Class</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact> <WorkItem(543248, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543248")> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function FormatBadCode() As Task Dim code = <Code>Imports System Class Program Shared Sub Main(args As String()) SyncLock From y As Char i, j As Char In String.Empty End SyncLock End Sub End Class</Code> Await AssertFormatLf2CrLfAsync(code.Value, code.Value) End Function <Fact> <WorkItem(544496, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544496")> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function AttributeInParameterList() As Task Dim code = <Code>Module Program Sub Main( &lt;Description&gt; args As String()) End Sub End Module</Code> Dim expected = <Code>Module Program Sub Main(&lt;Description&gt; args As String()) End Sub End Module</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact> <WorkItem(544980, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544980")> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function XmlElement_Expression() As Task Dim code = <Code>Module Program Dim x = &lt;x &lt;%= "" %&gt; /&gt; End Module</Code> Dim expected = <Code>Module Program Dim x = &lt;x &lt;%= "" %&gt;/&gt; End Module</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact> <WorkItem(542976, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542976")> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function XmlElementStartTag() As Task Dim code = <Code>Module Program Dim x = &lt;code &gt; &lt;/code&gt; End Module</Code> Dim expected = <Code>Module Program Dim x = &lt;code &gt; &lt;/code&gt; End Module</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact> <WorkItem(545088, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545088")> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function ForNext_MultipleVariables() As Task Dim code = <Code>Module Program Sub Method() For a = 0 To 1 For b = 0 To 1 For c = 0 To 1 Next c, b, a End Sub End Module</Code> Dim expected = <Code>Module Program Sub Method() For a = 0 To 1 For b = 0 To 1 For c = 0 To 1 Next c, b, a End Sub End Module</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact> <WorkItem(545088, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545088")> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function ForNext_MultipleVariables2() As Task Dim code = <Code>Module Program Sub Method() For z = 0 To 1 For a = 0 To 1 For b = 0 To 1 For c = 0 To 1 Next c, b, a Next z End Sub End Module</Code> Dim expected = <Code>Module Program Sub Method() For z = 0 To 1 For a = 0 To 1 For b = 0 To 1 For c = 0 To 1 Next c, b, a Next z End Sub End Module</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact> <WorkItem(544459, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544459")> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function DictionaryAccessOperator() As Task Dim code = <Code>Class S Default Property Def(s As String) As String Get Return Nothing End Get Set(value As String) End Set End Property Property Y As String End Class Module Program Sub Main(args As String()) Dim c As New S With {.Y =!Hello} End Sub End Module</Code> Dim expected = <Code>Class S Default Property Def(s As String) As String Get Return Nothing End Get Set(value As String) End Set End Property Property Y As String End Class Module Program Sub Main(args As String()) Dim c As New S With {.Y = !Hello} End Sub End Module</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact> <WorkItem(542976, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542976")> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function XmlElementStartTag1() As Task Await AssertFormatAsync(" Class C Sub Method() Dim book = <book version=""goo"" > </book> End Sub End Class", " Class C Sub Method() Dim book = <book version=""goo"" > </book> End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Sub ElasticNewlines() Dim text = <text>Class C Implements INotifyPropertyChanged Dim _p As Integer Property P As Integer Get Return 0 End Get Set(value As Integer) SetProperty(_p, value, "P") End Set End Property Sub SetProperty(Of T)(ByRef field As T, value As T, name As String) If Not EqualityComparer(Of T).Default.Equals(field, value) Then field = value RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(name)) End If End Sub End Class</text>.Value.Replace(vbLf, vbCrLf) Dim expected = <text>Class C Implements INotifyPropertyChanged Dim _p As Integer Property P As Integer Get Return 0 End Get Set(value As Integer) SetProperty(_p, value, "P") End Set End Property Sub SetProperty(Of T)(ByRef field As T, value As T, name As String) If Not EqualityComparer(Of T).Default.Equals(field, value) Then field = value RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(name)) End If End Sub End Class</text>.Value.Replace(vbLf, vbCrLf) Dim root = SyntaxFactory.ParseCompilationUnit(text) Dim goo As New SyntaxAnnotation() Dim implementsStatement = DirectCast(root.Members(0), ClassBlockSyntax).Implements.First() root = root.ReplaceNode(implementsStatement, implementsStatement.NormalizeWhitespace(elasticTrivia:=True).WithAdditionalAnnotations(goo)) Dim field = DirectCast(root.Members(0), ClassBlockSyntax).Members(0) root = root.ReplaceNode(field, field.NormalizeWhitespace(elasticTrivia:=True).WithAdditionalAnnotations(goo)) Dim prop = DirectCast(root.Members(0), ClassBlockSyntax).Members(1) root = root.ReplaceNode(prop, prop.NormalizeWhitespace(elasticTrivia:=True).WithAdditionalAnnotations(goo)) Dim method = DirectCast(root.Members(0), ClassBlockSyntax).Members(2) root = root.ReplaceNode(method, method.NormalizeWhitespace(elasticTrivia:=True).WithAdditionalAnnotations(goo)) Using workspace = New AdhocWorkspace() Dim result = Formatter.Format(root, goo, workspace).ToString() Assert.Equal(expected, result) End Using End Sub <Fact> <WorkItem(545630, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545630")> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function SpacesInXmlStrings() As Task Dim text = "Imports <xmlns:x='&#70;'>" Await AssertFormatAsync(text, text) End Function <Fact> <WorkItem(545680, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545680")> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function SpaceBetweenPercentGreaterThanAndXmlName() As Task Dim text = <code>Module Program Sub Main(args As String()) End Sub Public Function GetXml() As XElement Return &lt;field name=&lt;%= 1 %&gt; type=&lt;%= 2 %&gt;&gt;&lt;/field&gt; End Function End Module</code> Await AssertFormatLf2CrLfAsync(text.Value, text.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function SpacingAroundXmlEntityLiterals() As Task Dim code = <Code><![CDATA[Class C Sub Bar() Dim goo = <Code>&lt;&gt;</Code> End Sub End Class ]]></Code> Await AssertFormatLf2CrLfAsync(code.Value, code.Value) End Function <WorkItem(547005, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547005")> <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BadDirectivesAreValidRanges() As Task Dim code = <Code> #If False Then #end Region #End If #If False Then #end #End If </Code> Dim expected = <Code> #If False Then #end Region #End If #If False Then #end #End If </Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> <WorkItem(17313, "DevDiv_Projects/Roslyn")> Public Async Function TestElseIfFormatting_Directive() As Task Dim code = <Code><![CDATA[ #If True Then #Else If False Then #End If ]]></Code> Dim expected = <Code><![CDATA[ #If True Then #ElseIf False Then #End If ]]></Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> <WorkItem(529899, "DevDiv_Projects/Roslyn")> Public Async Function IndentContinuedLineOfSingleLineLambdaToFunctionKeyword() As Task Dim code = <Code><![CDATA[ Module Program Sub Main(ByVal args As String()) Dim a1 = Function() args(0) _ + 1 End Sub End Module ]]></Code> Dim expected = <Code><![CDATA[ Module Program Sub Main(ByVal args As String()) Dim a1 = Function() args(0) _ + 1 End Sub End Module ]]></Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> <WorkItem(604032, "DevDiv_Projects/Roslyn")> Public Async Function TestSpaceBetweenEqualsAndDotOfXml() As Task Dim code = <Code><![CDATA[ Module Program Sub Main(args As String()) Dim xml = <Order id="1"> <Customer> <Name>Bob</Name> </Customer> <Contents> <Item productId="1" quantity="2"/> <Item productId="2" quantity="1"/> </Contents> </Order> With xml Dim customerName =.<Customer>.<Name>.Value Dim itemCount =...<Item>.Count Dim orderId =.@id End With End Sub End Module ]]></Code> Dim expected = <Code><![CDATA[ Module Program Sub Main(args As String()) Dim xml = <Order id="1"> <Customer> <Name>Bob</Name> </Customer> <Contents> <Item productId="1" quantity="2"/> <Item productId="2" quantity="1"/> </Contents> </Order> With xml Dim customerName = .<Customer>.<Name>.Value Dim itemCount = ...<Item>.Count Dim orderId = .@id End With End Sub End Module ]]></Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> <WorkItem(604092, "DevDiv_Projects/Roslyn")> Public Async Function AnchorIndentToTheFirstTokenOfXmlBlock() As Task Dim code = <Code><![CDATA[ Module Program Sub Main(args As String()) With <a> </a> Dim s = 1 End With SyncLock <b> </b> Return End SyncLock Using <c> </c> Return End Using For Each reallyReallyReallyLongIdentifierNameHere In <d> </d> Return Next End Sub End Module ]]></Code> Dim expected = <Code><![CDATA[ Module Program Sub Main(args As String()) With <a> </a> Dim s = 1 End With SyncLock <b> </b> Return End SyncLock Using <c> </c> Return End Using For Each reallyReallyReallyLongIdentifierNameHere In <d> </d> Return Next End Sub End Module ]]></Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> <WorkItem(530366, "DevDiv_Projects/Roslyn")> Public Async Function ForcedSpaceBetweenXmlNameTokenAndPercentGreaterThanToken() As Task Dim code = <Code><![CDATA[ Module Module1 Sub Main() Dim e As XElement Dim y = <root><%= e.@test %></root> End Sub End Module ]]></Code> Dim expected = <Code><![CDATA[ Module Module1 Sub Main() Dim e As XElement Dim y = <root><%= e.@test %></root> End Sub End Module ]]></Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> <WorkItem(531444, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531444")> Public Async Function TestElseIfFormattingForNestedSingleLineIf() As Task Dim code = <Code><![CDATA[ If True Then Console.WriteLine(1) Else If True Then Return ]]></Code> Dim actual = CreateMethod(code.Value) ' Verify "Else If" doesn't get formatted to "ElseIf" Await AssertFormatLf2CrLfAsync(actual, actual) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function TestDontCrashOnMissingTokenWithComment() As Task Dim code = <Code><![CDATA[ Namespace NS Class CL Sub Method() Dim goo = Sub(x) 'Comment ]]></Code> Await AssertFormatLf2CrLfAsync(code.Value, code.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function TestBang() As Task Dim code = <Code><![CDATA[ Imports System.Collections Module Program Sub Main() Dim x As New Hashtable Dim y = x ! _ Goo End Sub End Module ]]></Code> Dim expected = <Code><![CDATA[ Imports System.Collections Module Program Sub Main() Dim x As New Hashtable Dim y = x ! _ Goo End Sub End Module ]]></Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> <WorkItem(679864, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/679864")> Public Async Function InsertSpaceBetweenXMLMemberAttributeAccessAndEqualsToken() As Task Dim expected = <Code><![CDATA[ Imports System Imports System.Collections Module Program Sub Main(args As String()) Dim element = <element></element> Dim goo = element.Single(Function(e) e.@Id = 1) End Sub End Module ]]></Code> Dim code = <Code><![CDATA[ Imports System Imports System.Collections Module Program Sub Main(args As String()) Dim element = <element></element> Dim goo = element.Single(Function(e) e.@Id = 1) End Sub End Module ]]></Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> <WorkItem(923172, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/923172")> Public Async Function TestMemberAccessAfterOpenParen() As Task Dim expected = <Code><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) With args If .IsNew = True Then Return Nothing Else Return CTypeDynamic(Of T)(.Value, .Hello) End If End With End Sub End Module ]]></Code> Dim code = <Code><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) With args If .IsNew = True Then Return Nothing Else Return CTypeDynamic(Of T)( .Value, .Hello) End If End With End Sub End Module ]]></Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> <WorkItem(923180, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/923180")> Public Async Function TestXmlMemberAccessDot() As Task Dim expected = <Code><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) With x.<Service>.First If .<WorkerServiceType>.Count > 0 Then Main(.<A>.Value, .<B>.Value) Dim i = .<A>.Value + .<B>.Value End If End With End Sub End Module ]]></Code> Dim code = <Code><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) With x.<Service>.First If.<WorkerServiceType>.Count > 0 Then Main(.<A>.Value,.<B>.Value) Dim i = .<A>.Value +.<B>.Value End If End With End Sub End Module ]]></Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> <WorkItem(530601, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530601")> Public Async Function TestElasticFormattingPropertySetter() As Task Dim parameterList = SyntaxFactory.ParseParameterList(String.Format("(value As {0})", "Integer")) Dim setter = SyntaxFactory.AccessorBlock(SyntaxKind.SetAccessorBlock, SyntaxFactory.AccessorStatement(SyntaxKind.SetAccessorStatement, SyntaxFactory.Token(SyntaxKind.SetKeyword)). WithParameterList(parameterList), SyntaxFactory.EndBlockStatement(SyntaxKind.EndSetStatement, SyntaxFactory.Token(SyntaxKind.SetKeyword))) Dim setPropertyStatement = SyntaxFactory.ParseExecutableStatement(String.Format("SetProperty({0}, value, ""{1}"")", "field", "Property")).WithLeadingTrivia(SyntaxFactory.ElasticMarker) setter = setter.WithStatements(SyntaxFactory.SingletonList(setPropertyStatement)) Dim solution = New AdhocWorkspace().CurrentSolution Dim project = solution.AddProject("proj", "proj", LanguageNames.VisualBasic) Dim document = project.AddDocument("goo.vb", <text>Class C WriteOnly Property Prop As Integer End Property End Class</text>.Value) Dim propertyBlock = (Await document.GetSyntaxRootAsync()).DescendantNodes().OfType(Of PropertyBlockSyntax).Single() document = Await Formatter.FormatAsync(document.WithSyntaxRoot( (Await document.GetSyntaxRootAsync()).ReplaceNode(propertyBlock, propertyBlock.WithAccessors(SyntaxFactory.SingletonList(setter))))) Dim actual = (Await document.GetTextAsync()).ToString() Assert.Equal(actual, actual) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function TestWarningDirectives() As Task Dim text = <Code> # enable warning[BC000],bc123, ap456,_789' comment Module Program # disable warning 'Comment Sub Main() #disable warning bc123, bC456,someId789 End Sub End Module # enable warning </Code> Dim expected = <Code> #enable warning [BC000], bc123, ap456, _789' comment Module Program #disable warning 'Comment Sub Main() #disable warning bc123, bC456, someId789 End Sub End Module #enable warning </Code> Await AssertFormatLf2CrLfAsync(text.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function TestIncompleteWarningDirectives() As Task Dim text = <Code> # disable Module M1 # enable warning[bc123], ' Comment End Module </Code> Dim expected = <Code> #disable Module M1 #enable warning [bc123], ' Comment End Module </Code> Await AssertFormatLf2CrLfAsync(text.Value, expected.Value) End Function <WorkItem(796562, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/796562")> <WorkItem(3293, "https://github.com/dotnet/roslyn/issues/3293")> <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function TriviaAtEndOfCaseBelongsToNextCase() As Task Dim text = <Code> Class X Function F(x As Integer) As Integer Select Case x Case 1 Return 2 ' This comment describes case 1 ' This comment describes case 2 Case 2, Return 3 End Select Return 5 End Function End Class </Code> Dim expected = <Code> Class X Function F(x As Integer) As Integer Select Case x Case 1 Return 2 ' This comment describes case 1 ' This comment describes case 2 Case 2, Return 3 End Select Return 5 End Function End Class </Code> Await AssertFormatLf2CrLfAsync(text.Value, expected.Value) End Function <WorkItem(938188, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/938188")> <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function XelementAttributeSpacing() As Task Dim text = <Code> Class X Function F(x As Integer) As Integer Dim x As XElement x.@Goo= "Hello" End Function End Class </Code> Dim expected = <Code> Class X Function F(x As Integer) As Integer Dim x As XElement x.@Goo = "Hello" End Function End Class </Code> Await AssertFormatLf2CrLfAsync(text.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function ConditionalAccessFormatting() As Task Const code = " Module Module1 Class G Public t As String End Class Sub Main() Dim x = New G() Dim q = x ? . t ? ( 0 ) Dim me = Me ? . ToString() Dim mb = MyBase ? . ToString() Dim mc = MyClass ? . ToString() Dim i = New With {.a = 3} ? . ToString() Dim s = ""Test"" ? . ToString() Dim s2 = $""Test"" ? . ToString() Dim x1 = <a></a> ? . <b> Dim x2 = <a/> ? . <b> End Sub End Module " Const expected = " Module Module1 Class G Public t As String End Class Sub Main() Dim x = New G() Dim q = x?.t?(0) Dim me = Me?.ToString() Dim mb = MyBase?.ToString() Dim mc = MyClass?.ToString() Dim i = New With {.a = 3}?.ToString() Dim s = ""Test""?.ToString() Dim s2 = $""Test""?.ToString() Dim x1 = <a></a>?.<b> Dim x2 = <a/>?.<b> End Sub End Module " Await AssertFormatAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function ChainedConditionalAccessFormatting() As Task Const code = " Module Module1 Class G Public t As String End Class Sub Main() Dim x = New G() Dim q = x ? . t ? . ToString() ? . ToString ( 0 ) Dim me = Me ? . ToString() ? . Length Dim mb = MyBase ? . ToString() ? . Length Dim mc = MyClass ? . ToString() ? . Length Dim i = New With {.a = 3} ? . ToString() ? . Length Dim s = ""Test"" ? . ToString() ? . Length Dim s2 = $""Test"" ? . ToString() ? . Length Dim x1 = <a></a> ? . <b> ? . <c> Dim x2 = <a/> ? . <b> ? . <c> End Sub End Module " Const expected = " Module Module1 Class G Public t As String End Class Sub Main() Dim x = New G() Dim q = x?.t?.ToString()?.ToString(0) Dim me = Me?.ToString()?.Length Dim mb = MyBase?.ToString()?.Length Dim mc = MyClass?.ToString()?.Length Dim i = New With {.a = 3}?.ToString()?.Length Dim s = ""Test""?.ToString()?.Length Dim s2 = $""Test""?.ToString()?.Length Dim x1 = <a></a>?.<b>?.<c> Dim x2 = <a/>?.<b>?.<c> End Sub End Module " Await AssertFormatAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function NameOfFormatting() As Task Dim text = <Code> Module M Dim s = NameOf ( M ) End Module </Code> Dim expected = <Code> Module M Dim s = NameOf(M) End Module </Code> Await AssertFormatLf2CrLfAsync(text.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function InterpolatedString1() As Task Dim text = <Code> Class C Sub M() Dim a = "World" Dim b =$"Hello, {a}" End Sub End Class </Code> Dim expected = <Code> Class C Sub M() Dim a = "World" Dim b = $"Hello, {a}" End Sub End Class </Code> Await AssertFormatLf2CrLfAsync(text.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function InterpolatedString2() As Task Dim text = <Code> Class C Sub M() Dim a = "Hello" Dim b = "World" Dim c = $"{a}, {b}" End Sub End Class </Code> Dim expected = <Code> Class C Sub M() Dim a = "Hello" Dim b = "World" Dim c = $"{a}, {b}" End Sub End Class </Code> Await AssertFormatLf2CrLfAsync(text.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function InterpolatedString3() As Task Dim text = <Code> Class C Sub M() Dim a = "World" Dim b = $"Hello, { a }" End Sub End Class </Code> Dim expected = <Code> Class C Sub M() Dim a = "World" Dim b = $"Hello, { a }" End Sub End Class </Code> Await AssertFormatLf2CrLfAsync(text.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function InterpolatedString4() As Task Dim text = <Code> Class C Sub M() Dim a = "Hello" Dim b = "World" Dim c = $"{ a }, { b }" End Sub End Class </Code> Dim expected = <Code> Class C Sub M() Dim a = "Hello" Dim b = "World" Dim c = $"{ a }, { b }" End Sub End Class </Code> Await AssertFormatLf2CrLfAsync(text.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function InterpolatedString5() As Task Dim text = <Code> Class C Sub M() Dim s = $"{42 , -4 :x}" End Sub End Class </Code> Dim expected = <Code> Class C Sub M() Dim s = $"{42,-4:x}" End Sub End Class </Code> Await AssertFormatLf2CrLfAsync(text.Value, expected.Value) End Function <WorkItem(3293, "https://github.com/dotnet/roslyn/issues/3293")> <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function CaseCommentsRemainsUndisturbed() As Task Dim text = <Code> Class Program Sub Main(args As String()) Dim s = 0 Select Case s Case 0 ' Comment should not be indented Case 2 ' comment Console.WriteLine(s) Case 4 End Select End Sub End Class </Code> Dim expected = <Code> Class Program Sub Main(args As String()) Dim s = 0 Select Case s Case 0 ' Comment should not be indented Case 2 ' comment Console.WriteLine(s) Case 4 End Select End Sub End Class </Code> Await AssertFormatLf2CrLfAsync(text.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Sub NewLineOption_LineFeedOnly() Dim tree = SyntaxFactory.ParseCompilationUnit("Class C" & vbCrLf & "End Class") ' replace all EOL trivia with elastic markers to force the formatter to add EOL back tree = tree.ReplaceTrivia(tree.DescendantTrivia().Where(Function(tr) tr.IsKind(SyntaxKind.EndOfLineTrivia)), Function(o, r) SyntaxFactory.ElasticMarker) Dim formatted = Formatter.Format(tree, DefaultWorkspace, DefaultWorkspace.Options.WithChangedOption(FormattingOptions.NewLine, LanguageNames.VisualBasic, vbLf)) Dim actual = formatted.ToFullString() Dim expected = "Class C" & vbLf & "End Class" Assert.Equal(expected, actual) End Sub <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> <WorkItem(2822, "https://github.com/dotnet/roslyn/issues/2822")> Public Async Function FormatLabelFollowedByDotExpression() As Task Dim code = <Code> Module Module1 Sub Main() With New List(Of Integer) lab: .Capacity = 15 End With End Sub End Module </Code> Dim expected = <Code> Module Module1 Sub Main() With New List(Of Integer) lab: .Capacity = 15 End With End Sub End Module </Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> <WorkItem(21923, "https://github.com/dotnet/roslyn/issues/21923")> Public Async Function FormatNullableTuple() As Task Dim code = <Code> Class C Dim x As (Integer, Integer) ? End Class </Code> Dim expected = <Code> Class C Dim x As (Integer, Integer)? End Class </Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> <WorkItem(2822, "https://github.com/dotnet/roslyn/issues/2822")> Public Async Function FormatOmittedArgument() As Task Dim code = <Code> Class C Sub M() Call M( a, , a ) End Sub End Class</Code> Await AssertFormatLf2CrLfAsync(code.Value, code.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> <WorkItem(8258, "https://github.com/dotnet/roslyn/issues/8258")> Public Async Function FormatDictionaryOperatorProperly() As Task Dim code = " Class C Public Shared Sub AutoFormatSample() ' Automatic Code Formatting in VB.NET ' Problem with ! dictionary access operator Dim dict As New Dictionary(Of String, String) dict.Add(""Apple"", ""Green"") dict.Add(""Orange"", ""Orange"") dict.Add(""Banana"", ""Yellow"") Dim x As String = (New Dictionary(Of String, String)(dict)) !Banana 'added space in front of ""!"" With dict !Apple = ""Red"" Dim multiColors = !Apple &!Orange &!Banana 'missing space between ""&"" and ""!"" If!Banana = ""Yellow"" Then 'missing space between ""If"" and ""!"" !Banana = ""Green"" End If End With End Sub End Class" Dim expected = " Class C Public Shared Sub AutoFormatSample() ' Automatic Code Formatting in VB.NET ' Problem with ! dictionary access operator Dim dict As New Dictionary(Of String, String) dict.Add(""Apple"", ""Green"") dict.Add(""Orange"", ""Orange"") dict.Add(""Banana"", ""Yellow"") Dim x As String = (New Dictionary(Of String, String)(dict))!Banana 'added space in front of ""!"" With dict !Apple = ""Red"" Dim multiColors = !Apple & !Orange & !Banana 'missing space between ""&"" and ""!"" If !Banana = ""Yellow"" Then 'missing space between ""If"" and ""!"" !Banana = ""Green"" End If End With End Sub End Class" Await AssertFormatAsync(code, expected) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions Imports Microsoft.CodeAnalysis.Formatting Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Formatting Public Class FormattingTest Inherits VisualBasicFormattingTestBase <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function Format1() As Task Dim code = <Code> Namespace A End Namespace </Code> Dim expected = <Code> Namespace A End Namespace</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function NamespaceBlock() As Task Dim code = <Code> Namespace A Class C End Class End Namespace </Code> Dim expected = <Code>Namespace A Class C End Class End Namespace</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function TypeBlock() As Task Dim code = <Code> Class C Sub Method ( ) End Sub End Class </Code> Dim expected = <Code>Class C Sub Method() End Sub End Class </Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function MethodBlock() As Task Dim code = <Code> Class C Sub Method ( ) Dim a As Integer = 1 End Sub End Class </Code> Dim expected = <Code>Class C Sub Method() Dim a As Integer = 1 End Sub End Class </Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function StructBlock() As Task Dim code = <Code> Structure C Sub Method ( ) Dim a As Integer = 1 End Sub Dim field As Integer End Structure </Code> Dim expected = <Code>Structure C Sub Method() Dim a As Integer = 1 End Sub Dim field As Integer End Structure </Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function EnumBlock() As Task Dim code = <Code> Enum C A B X Z End Enum </Code> Dim expected = <Code>Enum C A B X Z End Enum</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function ModuleBlock() As Task Dim code = <Code> Module module1 Sub goo() End Sub End Module </Code> Dim expected = <Code>Module module1 Sub goo() End Sub End Module</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function InterfaceBlock() As Task Dim code = <Code> Interface IGoo Sub goo() End Interface </Code> Dim expected = <Code>Interface IGoo Sub goo() End Interface </Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function PropertyBlock() As Task Dim code = <Code> Class C Property P ( ) As Integer Get Return 1 End Get Set ( ByVal value As Integer ) End Set End Property End Class </Code> Dim expected = <Code>Class C Property P() As Integer Get Return 1 End Get Set(ByVal value As Integer) End Set End Property End Class</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function EventBlock() As Task Dim code = <Code> Class C Public Custom Event MouseDown As EventHandler AddHandler ( ByVal Value As EventHandler ) Dim i As Integer = 1 End AddHandler RemoveHandler ( ByVal Value As EventHandler ) Dim i As Integer = 1 End RemoveHandler RaiseEvent ( ByVal sender As Object, ByVal e As Object ) Dim i As Integer = 1 End RaiseEvent End Event End Class </Code> Dim expected = <Code>Class C Public Custom Event MouseDown As EventHandler AddHandler(ByVal Value As EventHandler) Dim i As Integer = 1 End AddHandler RemoveHandler(ByVal Value As EventHandler) Dim i As Integer = 1 End RemoveHandler RaiseEvent(ByVal sender As Object, ByVal e As Object) Dim i As Integer = 1 End RaiseEvent End Event End Class</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function WhileBlockNode() As Task Dim code = <Code>Class C Sub Method ( ) While True Dim i As Integer = 1 End While End Sub End Class</Code> Dim expected = <Code>Class C Sub Method() While True Dim i As Integer = 1 End While End Sub End Class</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function UsingBlockNode() As Task Dim code = <Code>Class C Sub Method() Using TraceSource Dim i = 1 End Using End Sub End Class</Code> Dim expected = <Code>Class C Sub Method() Using TraceSource Dim i = 1 End Using End Sub End Class</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function SyncLockBlockNode() As Task Dim code = <Code>Class C Sub Method() SyncLock New Object Dim i = 10 End SyncLock End Sub End Class</Code> Dim expected = <Code>Class C Sub Method() SyncLock New Object Dim i = 10 End SyncLock End Sub End Class</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function WithBlockNode() As Task Dim code = <Code>Class C Sub Method() With New Object Dim i As Integer = 1 End With End Sub End Class</Code> Dim expected = <Code>Class C Sub Method() With New Object Dim i As Integer = 1 End With End Sub End Class</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function IfBlockNode() As Task Dim code = <Code>Class C Sub Method() If True Then Dim i As Integer = 1 ElseIf True Then Dim i As Integer = 1 Else Dim i As Integer = 1 End If End Sub End Class</Code> Dim expected = <Code>Class C Sub Method() If True Then Dim i As Integer = 1 ElseIf True Then Dim i As Integer = 1 Else Dim i As Integer = 1 End If End Sub End Class</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function TryCatchBlockNode() As Task Dim code = <Code>Class C Sub Method() Try Dim i As Integer = 1 Catch e As Exception When TypeOf e Is ArgumentNullException Try Dim i As Integer = 1 Catch ex As ArgumentNullException End Try Catch e As Exception When TypeOf e Is ArgumentNullException Dim i As Integer = 1 Finally goo() End Try End Sub End Class</Code> Dim expected = <Code>Class C Sub Method() Try Dim i As Integer = 1 Catch e As Exception When TypeOf e Is ArgumentNullException Try Dim i As Integer = 1 Catch ex As ArgumentNullException End Try Catch e As Exception When TypeOf e Is ArgumentNullException Dim i As Integer = 1 Finally goo() End Try End Sub End Class</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function SelectBlockNode() As Task Dim code = <Code>Class C Sub Method() Dim i = 1 Select Case i Case 1 , 2 , 3 Dim i2 = 1 Case 1 To 3 Dim i2 = 1 Case Else Dim i2 = 1 End Select End Sub End Class</Code> Dim expected = <Code>Class C Sub Method() Dim i = 1 Select Case i Case 1, 2, 3 Dim i2 = 1 Case 1 To 3 Dim i2 = 1 Case Else Dim i2 = 1 End Select End Sub End Class</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function DoLoopBlockNode() As Task Dim code = <Code>Class C Sub Method() Do Dim i = 1 Loop End Sub End Class</Code> Dim expected = <Code>Class C Sub Method() Do Dim i = 1 Loop End Sub End Class</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function DoUntilBlockNode() As Task Dim code = <Code>Class C Sub Method() Do Until False goo() Loop End Sub End Class</Code> Dim expected = <Code>Class C Sub Method() Do Until False goo() Loop End Sub End Class</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function ForBlockNode() As Task Dim code = <Code>Class C Sub Method() For i = 1 To 10 Step 1 Dim a = 1 Next End Sub End Class</Code> Dim expected = <Code>Class C Sub Method() For i = 1 To 10 Step 1 Dim a = 1 Next End Sub End Class</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function AnchorStatement() As Task Dim code = <Code>Imports System Imports System. Collections. Generic</Code> Dim expected = <Code>Imports System Imports System. Collections. Generic</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function AnchorQueryStatement() As Task Dim code = <Code>Class C Sub Method() Dim a = From q In {1, 3, 5} Where q > 10 Select q End Sub End Class</Code> Dim expected = <Code>Class C Sub Method() Dim a = From q In {1, 3, 5} Where q > 10 Select q End Sub End Class</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function AlignQueryStatement() As Task Dim code = <Code>Class C Sub Method() Dim a = From q In {1, 3, 5} Where q > 10 Select q End Sub End Class</Code> Dim expected = <Code>Class C Sub Method() Dim a = From q In {1, 3, 5} Where q > 10 Select q End Sub End Class</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function Operators1() As Task Dim code = <Code>Class C Sub Method() Dim a = - 1 Dim a2 = 1-1 Dim a3 = + 1 Dim a4 = 1+1 Dim a5 = 2+(3*-2) Goo(2,(3)) End Sub End Class </Code> Dim expected = <Code>Class C Sub Method() Dim a = -1 Dim a2 = 1 - 1 Dim a3 = +1 Dim a4 = 1 + 1 Dim a5 = 2 + (3 * -2) Goo(2, (3)) End Sub End Class </Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function Operators2() As Task Dim code = <Code>Class C Sub Method() Dim myStr As String myStr = "Hello" &amp; " World" End Sub End Class</Code> Dim expected = <Code>Class C Sub Method() Dim myStr As String myStr = "Hello" &amp; " World" End Sub End Class</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function Operators3() As Task Dim code = <Code>Class C Sub Method() Dim a1 = 1 &lt;= 2 Dim a2 = 2 &gt;= 3 Dim a3 = 4 &lt;&gt; 5 Dim a4 = 5 ^ 4 Dim a5 = 0 a5 +=1 a5 -=1 a5 *=1 a5 /=1 a5 \=1 a5 ^=1 a5&lt;&lt;= 1 a5&gt;&gt;= 1 a5 &amp;= 1 a5 = a5&lt;&lt; 1 a5 = a5&gt;&gt; 1 End Sub End Class</Code> Dim expected = <Code>Class C Sub Method() Dim a1 = 1 &lt;= 2 Dim a2 = 2 &gt;= 3 Dim a3 = 4 &lt;&gt; 5 Dim a4 = 5 ^ 4 Dim a5 = 0 a5 += 1 a5 -= 1 a5 *= 1 a5 /= 1 a5 \= 1 a5 ^= 1 a5 &lt;&lt;= 1 a5 &gt;&gt;= 1 a5 &amp;= 1 a5 = a5 &lt;&lt; 1 a5 = a5 &gt;&gt; 1 End Sub End Class</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function Punctuation() As Task Dim code = <Code> &lt; Fact ( ) , Trait ( Traits . Feature , Traits . Features . Formatting ) &gt; Class A End Class</Code> Dim expected = <Code>&lt;Fact(), Trait(Traits.Feature, Traits.Features.Formatting)&gt; Class A End Class</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function Punctuation2() As Task Dim code = <Code>Class C Sub Method(Optional ByVal i As Integer = 1) Method(i := 1) End Sub End Class</Code> Dim expected = <Code>Class C Sub Method(Optional ByVal i As Integer = 1) Method(i:=1) End Sub End Class</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function Punctuation3() As Task Dim code = <Code><![CDATA[Class C <Attribute(goo := "value")> Sub Method() End Sub End Class]]></Code> Dim expected = <Code><![CDATA[Class C <Attribute(goo:="value")> Sub Method() End Sub End Class]]></Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function Lambda1() As Task Dim code = <Code>Class C Sub Method(Optional ByVal i As Integer = 1) Dim q = Function ( t ) 1 Dim q2=Sub ( t )Console . WriteLine ( t ) End Sub End Class</Code> Dim expected = <Code>Class C Sub Method(Optional ByVal i As Integer = 1) Dim q = Function(t) 1 Dim q2 = Sub(t) Console.WriteLine(t) End Sub End Class</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function Lambda2() As Task Dim code = <Code>Class C Sub Method(Optional ByVal i As Integer = 1) Dim q = Function ( t ) Return 1 End Function Dim q2 = Sub ( t ) Dim a = t End Sub End Sub End Class</Code> Dim expected = <Code>Class C Sub Method(Optional ByVal i As Integer = 1) Dim q = Function(t) Return 1 End Function Dim q2 = Sub(t) Dim a = t End Sub End Sub End Class</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function Lambda3() As Task Dim code = <Code>Class C Sub Method(Optional ByVal i As Integer = 1) Dim q = Function ( t ) Return 1 End Function Dim q2 = Sub ( t ) Dim a = t End Sub End Sub End Class</Code> Dim expected = <Code>Class C Sub Method(Optional ByVal i As Integer = 1) Dim q = Function(t) Return 1 End Function Dim q2 = Sub(t) Dim a = t End Sub End Sub End Class</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function Lambda4() As Task Dim code = <Code>Class C Sub Method(Optional ByVal i As Integer = 1) Dim q = Function ( t ) Return 1 End Function Dim q2 = Sub ( t ) Dim a = t Dim bbb = Function(r) Return r End Function End Sub End Sub End Class</Code> Dim expected = <Code>Class C Sub Method(Optional ByVal i As Integer = 1) Dim q = Function(t) Return 1 End Function Dim q2 = Sub(t) Dim a = t Dim bbb = Function(r) Return r End Function End Sub End Sub End Class</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Theory, Trait(Traits.Feature, Traits.Features.Formatting)> <InlineData("_")> <InlineData("_ ' Comment")> Public Async Function LineContinuation1(continuation As String) As Task Dim code = $"Class C Sub Method(Optional ByVal i As Integer = 1) Dim a = 1 + {continuation} 2 + {continuation} 3 End Sub End Class" Dim expected = $"Class C Sub Method(Optional ByVal i As Integer = 1) Dim a = 1 + {continuation} 2 + {continuation} 3 End Sub End Class" Await AssertFormatAsync(code, expected) End Function <Theory, Trait(Traits.Feature, Traits.Features.Formatting)> <InlineData("_")> <InlineData("_ ' Comment")> Public Async Function LineContinuation2(continuation As String) As Task Dim code = $"Class C Sub Method(Optional ByVal i As Integer = 1) Dim aa = 1 + {continuation} 2 + {continuation} 3 End Sub End Class" Dim expected = $"Class C Sub Method(Optional ByVal i As Integer = 1) Dim aa = 1 + {continuation} 2 + {continuation} 3 End Sub End Class" Await AssertFormatAsync(code, expected) End Function <Theory, Trait(Traits.Feature, Traits.Features.Formatting)> <InlineData("_")> <InlineData("_ ' Comment")> Public Async Function LineContinuation3(continuation As String) As Task Dim code = $"Class C Sub Method(Optional ByVal i As Integer = 1) Dim aa = 1 + {continuation} 2 + {continuation} 3 End Sub End Class" Dim expected = $"Class C Sub Method(Optional ByVal i As Integer = 1) Dim aa = 1 + {continuation} 2 + {continuation} 3 End Sub End Class" Await AssertFormatAsync(code, expected) End Function <Theory, Trait(Traits.Feature, Traits.Features.Formatting)> <InlineData("_")> <InlineData("_ ' Comment")> Public Async Function LineContinuation4(continuation As String) As Task Dim code = $"Class C Sub Method(Optional ByVal i As Integer = 1) Dim aa = 1 + {continuation} {continuation} {continuation} {continuation} {continuation} {continuation} 2 + {continuation} 3 End Sub End Class" Dim expected = $"Class C Sub Method(Optional ByVal i As Integer = 1) Dim aa = 1 + {continuation} {continuation} {continuation} {continuation} {continuation} {continuation} 2 + {continuation} 3 End Sub End Class" Await AssertFormatAsync(code, expected) End Function <Theory, Trait(Traits.Feature, Traits.Features.Formatting)> <InlineData("_")> <InlineData("_ ' Comment")> Public Async Function LineContinuation5(continuation As String) As Task Dim code = $"Class C Sub Method(Optional ByVal i As Integer = 1) Dim aa = 1 + {continuation} {continuation} {continuation} {continuation} {continuation} {continuation} 2 + {continuation} 3 End Sub End Class" Dim expected = $"Class C Sub Method(Optional ByVal i As Integer = 1) Dim aa = 1 + {continuation} {continuation} {continuation} {continuation} {continuation} {continuation} 2 + {continuation} 3 End Sub End Class" Await AssertFormatAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function AnonType() As Task Dim code = <Code>Class Goo Sub GooMethod() Dim SomeAnonType = New With { .goo = "goo", .answer = 42 } End Sub End Class</Code> Dim expected = <Code>Class Goo Sub GooMethod() Dim SomeAnonType = New With { .goo = "goo", .answer = 42 } End Sub End Class</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function CollectionInitializer() As Task Dim code = <Code>Class Goo Sub GooMethod() Dim somelist = New List(Of Integer) From { 1, 2, 3 } End Sub End Class</Code> Dim expected = <Code>Class Goo Sub GooMethod() Dim somelist = New List(Of Integer) From { 1, 2, 3 } End Sub End Class</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function Label1() As Task Dim code = <Code>Class C Sub Method() GoTo l l: Stop End Sub End Class</Code> Dim expected = <Code>Class C Sub Method() GoTo l l: Stop End Sub End Class</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function Label2() As Task Dim code = <Code>Class C Sub Method() GoTo goofoofoofoofoo goofoofoofoofoo: Stop End Sub End Class</Code> Dim expected = <Code>Class C Sub Method() GoTo goofoofoofoofoo goofoofoofoofoo: Stop End Sub End Class</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function Label3() As Task Dim code = <Code>Class C Sub Goo() goo() x : goo() y : goo() End Sub End Class</Code> Dim expected = <Code>Class C Sub Goo() goo() x: goo() y: goo() End Sub End Class</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function Trivia1() As Task Dim code = <Code>Class C Sub Method(Optional ByVal i As Integer = 1) ' Test ' Test2 ' Test 3 Dim a = 1 End Sub End Class</Code> Dim expected = <Code>Class C Sub Method(Optional ByVal i As Integer = 1) ' Test ' Test2 ' Test 3 Dim a = 1 End Sub End Class</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function Trivia2() As Task Dim code = <Code>Class C Sub Method(Optional ByVal i As Integer = 1) ''' Test ''' Test2 ''' Test 3 Dim a = 1 End Sub End Class</Code> Dim expected = <Code>Class C Sub Method(Optional ByVal i As Integer = 1) ''' Test ''' Test2 ''' Test 3 Dim a = 1 End Sub End Class</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Theory, Trait(Traits.Feature, Traits.Features.Formatting)> <InlineData("_")> <InlineData("_ ' Comment")> Public Async Function Trivia3(continuation As String) As Task Dim code = $"Class C Sub Method(Optional ByVal i As Integer = 1) Dim a = {continuation} {continuation} {continuation} 1 End Sub End Class" Dim expected = $"Class C Sub Method(Optional ByVal i As Integer = 1) Dim a = {continuation} {continuation} {continuation} 1 End Sub End Class" Await AssertFormatAsync(code, expected) End Function <WorkItem(538354, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538354")> <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix3939() As Task Dim code = <Code> Imports System. Collections. Generic </Code> Dim expected = <Code> Imports System. Collections. Generic</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <WorkItem(538579, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538579")> <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix4235() As Task Dim code = <Code> #If False Then #End If </Code> Dim expected = <Code> #If False Then #End If </Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function XmlLiterals1() As Task Dim code = "Dim xml = < XML > </ XML > " Dim expected = " Dim xml = <XML></XML>" Await AssertFormatAsync(CreateMethod(code), CreateMethod(expected)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function XmlLiterals2() As Task Dim code = "Dim xml = < XML > <%= a %> </ XML > " Dim expected = " Dim xml = <XML><%= a %></XML>" Await AssertFormatAsync(CreateMethod(code), CreateMethod(expected)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function XmlLiterals3() As Task Dim code = "Dim xml = < local : XML > </ local : XML > " Dim expected = " Dim xml = <local:XML></local:XML>" Await AssertFormatAsync(CreateMethod(code), CreateMethod(expected)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function XmlLiterals4() As Task Dim code = "Dim xml = < local :<%= hello %> > </ > " Dim expected = " Dim xml = <local:<%= hello %>></>" Await AssertFormatAsync(CreateMethod(code), CreateMethod(expected)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function XmlLiterals5() As Task Dim code = "Dim xml = < <%= hello %> > </ > " Dim expected = " Dim xml = <<%= hello %>></>" Await AssertFormatAsync(CreateMethod(code), CreateMethod(expected)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function XmlLiterals6() As Task Dim code = "Dim xml = < <%= hello %> /> " Dim expected = " Dim xml = <<%= hello %>/>" Await AssertFormatAsync(CreateMethod(code), CreateMethod(expected)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function XmlLiterals7() As Task Dim code = "Dim xml = < xml attr = ""1"" /> " Dim expected = " Dim xml = <xml attr=""1""/>" Await AssertFormatAsync(CreateMethod(code), CreateMethod(expected)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function XmlLiterals8() As Task Dim code = "Dim xml = < xml attr = '1' /> " Dim expected = " Dim xml = <xml attr='1'/>" Await AssertFormatAsync(CreateMethod(code), CreateMethod(expected)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function XmlLiterals9() As Task Dim code = "Dim xml = < xml attr = '1' attr2 = ""2"" attr3 = <%= hello %> /> " Dim expected = " Dim xml = <xml attr='1' attr2=""2"" attr3=<%= hello %>/>" Await AssertFormatAsync(CreateMethod(code), CreateMethod(expected)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function XmlLiterals10() As Task Dim code = "Dim xml = < xml local:attr = '1' attr2 = ""2"" attr3 = <%= hello %> /> " Dim expected = " Dim xml = <xml local:attr='1' attr2=""2"" attr3=<%= hello %>/>" Await AssertFormatAsync(CreateMethod(code), CreateMethod(expected)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function XmlLiterals11() As Task Dim code = "Dim xml = < xml local:attr = '1' <%= attr2 %> = ""2"" local:<%= attr3 %> = <%= hello %> /> " Dim expected = " Dim xml = <xml local:attr='1' <%= attr2 %>=""2"" local:<%= attr3 %>=<%= hello %>/>" Await AssertFormatAsync(CreateMethod(code), CreateMethod(expected)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function XmlLiterals12() As Task Dim code = "Dim xml = < xml> test </xml > " Dim expected = " Dim xml = <xml> test </xml>" Await AssertFormatAsync(CreateMethod(code), CreateMethod(expected)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function XmlLiterals13() As Task Dim code = "Dim xml = < xml> test <%= test %> </xml > " Dim expected = " Dim xml = <xml> test <%= test %></xml>" Await AssertFormatAsync(CreateMethod(code), CreateMethod(expected)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function XmlLiterals14() As Task Dim code = "Dim xml = < xml> test <%= test %> <%= test2 %> </xml > " Dim expected = " Dim xml = <xml> test <%= test %><%= test2 %></xml>" Await AssertFormatAsync(CreateMethod(code), CreateMethod(expected)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function XmlLiterals15() As Task Dim code = "Dim xml = < xml> <%= test1 %> test <%= test %> <%= test2 %> </xml > " Dim expected = " Dim xml = <xml><%= test1 %> test <%= test %><%= test2 %></xml>" Await AssertFormatAsync(CreateMethod(code), CreateMethod(expected)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function XmlLiterals16() As Task Dim code = "Dim xml = < xml> <!-- test --> </xml > " Dim expected = " Dim xml = <xml><!-- test --></xml>" Await AssertFormatAsync(CreateMethod(code), CreateMethod(expected)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function XmlLiterals17() As Task Dim code = "Dim xml = <xml> <test/> <!-- test --> test <!-- test --> </xml> " Dim expected = " Dim xml = <xml><test/><!-- test --> test <!-- test --></xml>" Await AssertFormatAsync(CreateMethod(code), CreateMethod(expected)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function XmlLiterals18() As Task Dim code = "Dim xml = <!-- test -->" Dim expected = " Dim xml = <!-- test -->" Await AssertFormatAsync(CreateMethod(code), CreateMethod(expected)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function XmlLiterals19() As Task Dim code = "Dim xml = <?xml-stylesheet type = ""text/xsl"" href = ""show_book.xsl""?>" Dim expected = " Dim xml = <?xml-stylesheet type = ""text/xsl"" href = ""show_book.xsl""?>" Await AssertFormatAsync(CreateMethod(code), CreateMethod(expected)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function XmlLiterals20() As Task Dim code = "Dim xml = <xml> <test/> <!-- test --> test <!-- test --> <?xml-stylesheet type = 'text/xsl' href = show_book.xsl?> </xml> " Dim expected = " Dim xml = <xml><test/><!-- test --> test <!-- test --><?xml-stylesheet type = 'text/xsl' href = show_book.xsl?></xml>" Await AssertFormatAsync(CreateMethod(code), CreateMethod(expected)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function XmlLiterals21() As Task Dim code = "Dim xml = <xml> <test/> <!-- test --> test <!-- test --> test 2 <?xml-stylesheet type = 'text/xsl' href = show_book.xsl?> </xml> " Dim expected = " Dim xml = <xml><test/><!-- test --> test <!-- test --> test 2 <?xml-stylesheet type = 'text/xsl' href = show_book.xsl?></xml>" Await AssertFormatAsync(CreateMethod(code), CreateMethod(expected)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function XmlLiterals22() As Task Dim code = "Dim xml = <![CDATA[ Can contain literal <XML> tags ]]> " Dim expected = " Dim xml = <![CDATA[ Can contain literal <XML> tags ]]>" Await AssertFormatAsync(CreateMethod(code), CreateMethod(expected)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function XmlLiterals23() As Task Dim code = "Dim xml = <xml> <test/> <!-- test --> test <![CDATA[ Can contain literal <XML> tags ]]> <!-- test --> test 2 <?xml-stylesheet type = 'text/xsl' href = show_book.xsl?> </xml> " Dim expected = " Dim xml = <xml><test/><!-- test --> test <![CDATA[ Can contain literal <XML> tags ]]><!-- test --> test 2 <?xml-stylesheet type = 'text/xsl' href = show_book.xsl?></xml>" Await AssertFormatAsync(CreateMethod(code), CreateMethod(expected)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function XmlLiterals24() As Task Dim code = "Dim xml = <xml> <test> <%= <xml> <test id=""42""><%=42 %> <%= ""hello""%> </test> </xml> %> </test> </xml>" Dim expected = " Dim xml = <xml><test><%= <xml><test id=""42""><%= 42 %><%= ""hello"" %></test></xml> %></test></xml>" Await AssertFormatAsync(CreateMethod(code), CreateMethod(expected)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function XmlLiterals25() As Task Dim code = "Dim xml = <xml attr=""1""> </xml> " Dim expected = " Dim xml = <xml attr=""1""></xml>" Await AssertFormatAsync(CreateMethod(code), CreateMethod(expected)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function XmlLiterals26() As Task Dim code = " Class C Sub Method(Optional ByVal i As Integer = 1) Dim q = <xml> <hello> </hello> </xml> End Sub End Class" Dim expected = " Class C Sub Method(Optional ByVal i As Integer = 1) Dim q = <xml> <hello> </hello> </xml> End Sub End Class" Await AssertFormatAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function XmlLiterals27() As Task Dim code = " Class C Sub Method(Optional ByVal i As Integer = 1) Dim q = <xml> <!-- Test --> <hello> Test <![CDATA[ ???? ]]> </hello> <!-- Test --> </xml> End Sub End Class" Dim expected = " Class C Sub Method(Optional ByVal i As Integer = 1) Dim q = <xml> <!-- Test --> <hello> Test <![CDATA[ ???? ]]> </hello> <!-- Test --></xml> End Sub End Class" Await AssertFormatAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function XmlLiterals28() As Task Dim code = " Class C Sub Method(Optional ByVal i As Integer = 1) Dim q = <xml> <!-- Test --> <hello> Test <![CDATA[ ???? ]]> </hello> <!-- Test --></xml> End Sub End Class" Dim expected = " Class C Sub Method(Optional ByVal i As Integer = 1) Dim q = <xml><!-- Test --><hello> Test <![CDATA[ ???? ]]> </hello> <!-- Test --></xml> End Sub End Class" Await AssertFormatAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function AttributeOnClass1() As Task Dim code = <Code><![CDATA[Namespace SomeNamespace <SomeAttribute()> Class Goo End Class End Namespace]]></Code> Dim expected = <Code><![CDATA[Namespace SomeNamespace <SomeAttribute()> Class Goo End Class End Namespace]]></Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <WorkItem(1087167, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1087167")> <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function MultipleAttributesOnClass() As Task Dim code = <Code><![CDATA[Namespace SomeNamespace <SomeAttribute()> <SomeAttribute2()> Class Goo End Class End Namespace]]></Code> Dim expected = <Code><![CDATA[Namespace SomeNamespace <SomeAttribute()> <SomeAttribute2()> Class Goo End Class End Namespace]]></Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <WorkItem(1087167, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1087167")> <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function MultipleAttributesOnParameter_1() As Task Dim code = <Code><![CDATA[Class Program Sub P( <Goo> <Goo> som As Integer) End Sub End Class Public Class Goo Inherits Attribute End Class]]></Code> Await AssertFormatLf2CrLfAsync(code.Value, code.Value) End Function <WorkItem(1087167, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1087167")> <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function MultipleAttributesOnParameter_2() As Task Dim code = <Code><![CDATA[Class Program Sub P( <Goo> som As Integer) End Sub End Class Public Class Goo Inherits Attribute End Class]]></Code> Await AssertFormatLf2CrLfAsync(code.Value, code.Value) End Function <WorkItem(1087167, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1087167")> <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function MultipleAttributesOnParameter_3() As Task Dim code = <Code><![CDATA[Class Program Sub P( <Goo> <Goo> som As Integer) End Sub End Class Public Class Goo Inherits Attribute End Class]]></Code> Dim expected = <Code><![CDATA[Class Program Sub P(<Goo> <Goo> som As Integer) End Sub End Class Public Class Goo Inherits Attribute End Class]]></Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function InheritsImplementsOnClass() As Task Dim code = <Code><![CDATA[Class SomeClass Inherits BaseClass Implements IGoo End Class]]></Code> Dim expected = <Code><![CDATA[Class SomeClass Inherits BaseClass Implements IGoo End Class]]></Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function InheritsImplementsWithGenericsOnClass() As Task Dim code = <Code><![CDATA[Class SomeClass(Of T) Inherits BaseClass (Of T) Implements IGoo ( Of String, T) End Class]]></Code> Dim expected = <Code><![CDATA[Class SomeClass(Of T) Inherits BaseClass(Of T) Implements IGoo(Of String, T) End Class]]></Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function InheritsOnInterface() As Task Dim code = <Code>Interface I Inherits J End Interface Interface J End Interface</Code> Dim expected = <Code>Interface I Inherits J End Interface Interface J End Interface</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function WhitespaceMethodParens() As Task Dim code = <Code>Class SomeClass Sub Goo ( x As Integer ) Goo ( 42 ) End Sub End Class</Code> Dim expected = <Code>Class SomeClass Sub Goo(x As Integer) Goo(42) End Sub End Class</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function WhitespaceKeywordParens() As Task Dim code = <Code>Class SomeClass Sub Goo If(x And(y Or(z)) Then Stop End Sub End Class</Code> Dim expected = <Code>Class SomeClass Sub Goo If (x And (y Or (z)) Then Stop End Sub End Class</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function WhitespaceLiteralAndTypeCharacters() As Task Dim code = <Code><![CDATA[Class SomeClass Sub Method() Dim someHex = &HFF Dim someOct = &O33 Dim someShort = 42S+42S Dim someInteger% = 42%+42% Dim someOtherInteger = 42I+42I Dim someLong& = 42&+42& Dim someOtherLong = 42L+42L Dim someDecimal@ = 42.42@+42.42@ Dim someOtherDecimal = 42.42D + 42.42D Dim someSingle! = 42.42!+42.42! Dim someOtherSingle = 42.42F+42.42F Dim someDouble# = 42.4242#+42.4242# Dim someOtherDouble = 42.42R+42.42R Dim unsignedShort = 42US+42US Dim unsignedLong = 42UL+42UL Dim someDate = #3/3/2011 12:42:00 AM#+#2/2/2011# Dim someChar = "x"c Dim someString$ = "42"+"42" Dim r = Goo&() Dim s = GooString$() End Sub End Class]]></Code> Dim expected = <Code><![CDATA[Class SomeClass Sub Method() Dim someHex = &HFF Dim someOct = &O33 Dim someShort = 42S + 42S Dim someInteger% = 42% + 42% Dim someOtherInteger = 42I + 42I Dim someLong& = 42& + 42& Dim someOtherLong = 42L + 42L Dim someDecimal@ = 42.42@ + 42.42@ Dim someOtherDecimal = 42.42D + 42.42D Dim someSingle! = 42.42! + 42.42! Dim someOtherSingle = 42.42F + 42.42F Dim someDouble# = 42.4242# + 42.4242# Dim someOtherDouble = 42.42R + 42.42R Dim unsignedShort = 42US + 42US Dim unsignedLong = 42UL + 42UL Dim someDate = #3/3/2011 12:42:00 AM# + #2/2/2011# Dim someChar = "x"c Dim someString$ = "42" + "42" Dim r = Goo&() Dim s = GooString$() End Sub End Class]]></Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function WhitespaceNullable() As Task Dim code = <Code>Class Goo Property someprop As Integer ? Function Method(arg1 ? As Integer) As Integer ? Dim someVariable ? As Integer End Function End Class</Code> Dim expected = <Code>Class Goo Property someprop As Integer? Function Method(arg1? As Integer) As Integer? Dim someVariable? As Integer End Function End Class</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function WhitespaceArrayBraces() As Task Dim code = <Code>Class Goo Sub Method() Dim arr() ={ 1, 2, 3 } End Sub End Class</Code> Dim expected = <Code>Class Goo Sub Method() Dim arr() = {1, 2, 3} End Sub End Class</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function WhitespaceStatementSeparator() As Task Dim code = <Code>Class Goo Sub Method() Dim x=2:Dim y=3:Dim z=4 End Sub End Class</Code> Dim expected = <Code>Class Goo Sub Method() Dim x = 2 : Dim y = 3 : Dim z = 4 End Sub End Class</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function WhitespaceRemovedBeforeComment() As Task Dim code = <Code>Class Goo Sub Method() Dim a = 4 ' This is a comment that doesn't move ' This is a comment that will have some preceding whitespace removed Dim y = 4 End Sub End Class</Code> Dim expected = <Code>Class Goo Sub Method() Dim a = 4 ' This is a comment that doesn't move ' This is a comment that will have some preceding whitespace removed Dim y = 4 End Sub End Class</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function ReFormatWithTabsEnabled1() As Task Dim code = "Class SomeClass" + vbCrLf + " Sub Goo()" + vbCrLf + " Goo()" + vbCrLf + " End Sub" + vbCrLf + "End Class" Dim expected = "Class SomeClass" + vbCrLf + vbTab + "Sub Goo()" + vbCrLf + vbTab + vbTab + "Goo()" + vbCrLf + vbTab + "End Sub" + vbCrLf + "End Class" Dim optionSet = New OptionsCollection(LanguageNames.VisualBasic) From { {FormattingOptions2.UseTabs, True}, {FormattingOptions2.TabSize, 4}, {FormattingOptions2.IndentationSize, 4} } Await AssertFormatAsync(code, expected, changedOptionSet:=optionSet) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function ReFormatWithTabsEnabled2() As Task ' tabs after the first token on a line should be converted to spaces Dim code = "Class SomeClass" + vbCrLf + vbTab + "Sub Goo()" + vbCrLf + vbTab + vbTab + "Goo()" + vbTab + vbTab + "'comment" + vbCrLf + vbTab + "End Sub" + vbCrLf + "End Class" Dim expected = "Class SomeClass" + vbCrLf + vbTab + "Sub Goo()" + vbCrLf + vbTab + vbTab + "Goo() 'comment" + vbCrLf + vbTab + "End Sub" + vbCrLf + "End Class" Dim optionSet = New OptionsCollection(LanguageNames.VisualBasic) From { {FormattingOptions2.UseTabs, True}, {FormattingOptions2.TabSize, 4}, {FormattingOptions2.IndentationSize, 4} } Await AssertFormatAsync(code, expected, changedOptionSet:=optionSet) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function ReFormatWithTabsEnabled3() As Task ' This is a regression test for the assert: it may still not pass after the assert is fixed. Dim code = "Class SomeClass" + vbCrLf + " Sub Goo() ' Comment" + vbCrLf + " Goo() " + vbCrLf + " End Sub" + vbCrLf + "End Class" Dim expected = "Class SomeClass" + vbCrLf + vbTab + "Sub Goo() ' Comment" + vbCrLf + vbTab + vbTab + "Goo()" + vbCrLf + vbTab + "End Sub" + vbCrLf + "End Class" Dim optionSet = New OptionsCollection(LanguageNames.VisualBasic) From { {FormattingOptions2.UseTabs, True}, {FormattingOptions2.TabSize, 4}, {FormattingOptions2.IndentationSize, 4} } Await AssertFormatAsync(code, expected, changedOptionSet:=optionSet) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function ReFormatWithTabsEnabled4() As Task Dim code = "Class SomeClass" + vbCrLf + " Sub Goo()" + vbCrLf + " Dim abc = Sub()" + vbCrLf + " Console.WriteLine(42)" + vbCrLf + " End Sub" + vbCrLf + " End Sub" + vbCrLf + "End Class" Dim expected = "Class SomeClass" + vbCrLf + vbTab + "Sub Goo()" + vbCrLf + vbTab + vbTab + "Dim abc = Sub()" + vbCrLf + vbTab + vbTab + vbTab + vbTab + vbTab + " Console.WriteLine(42)" + vbCrLf + vbTab + vbTab + vbTab + vbTab + " End Sub" + vbCrLf + vbTab + "End Sub" + vbCrLf + "End Class" Dim optionSet = New OptionsCollection(LanguageNames.VisualBasic) From { {FormattingOptions2.UseTabs, True}, {FormattingOptions2.TabSize, 4}, {FormattingOptions2.IndentationSize, 4} } Await AssertFormatAsync(code, expected, changedOptionSet:=optionSet) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function ReFormatWithTabsEnabled5() As Task Dim code = "Class SomeClass" + vbCrLf + " Sub Goo()" + vbCrLf + " Dim abc = 2 + " + vbCrLf + " 3 + " + vbCrLf + " 4 " + vbCrLf + " End Sub" + vbCrLf + "End Class" Dim expected = "Class SomeClass" + vbCrLf + vbTab + "Sub Goo()" + vbCrLf + vbTab + vbTab + "Dim abc = 2 +" + vbCrLf + vbTab + vbTab + vbTab + vbTab + vbTab + "3 +" + vbCrLf + vbTab + vbTab + vbTab + vbTab + " 4" + vbCrLf + vbTab + "End Sub" + vbCrLf + "End Class" Dim optionSet = New OptionsCollection(LanguageNames.VisualBasic) From { {FormattingOptions2.UseTabs, True}, {FormattingOptions2.TabSize, 4}, {FormattingOptions2.IndentationSize, 4} } Await AssertFormatAsync(code, expected, changedOptionSet:=optionSet) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> <WorkItem(10742, "https://github.com/dotnet/roslyn/issues/10742")> Public Async Function ReFormatWithTabsEnabled6() As Task Dim code = "Class SomeClass" + vbCrLf + " Sub Goo() ' Comment" + vbCrLf + " Goo()" + vbCrLf + " End Sub" + vbCrLf + "End Class" Dim expected = "Class SomeClass" + vbCrLf + vbTab + "Sub Goo() ' Comment" + vbCrLf + vbTab + vbTab + "Goo()" + vbCrLf + vbTab + "End Sub" + vbCrLf + "End Class" Dim optionSet = New OptionsCollection(LanguageNames.VisualBasic) From { {FormattingOptions2.UseTabs, True}, {FormattingOptions2.TabSize, 4}, {FormattingOptions2.IndentationSize, 4} } Await AssertFormatAsync(code, expected, changedOptionSet:=optionSet) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function ReFormatWithTabsDisabled() As Task Dim code = "Class SomeClass" + vbCrLf + vbTab + "Sub Goo()" + vbCrLf + vbTab + vbTab + "Goo()" + vbCrLf + vbTab + "End Sub" + vbCrLf + "End Class" Dim expected = "Class SomeClass" + vbCrLf + " Sub Goo()" + vbCrLf + " Goo()" + vbCrLf + " End Sub" + vbCrLf + "End Class" Dim optionSet = New OptionsCollection(LanguageNames.VisualBasic) From { {FormattingOptions2.UseTabs, False}, {FormattingOptions2.TabSize, 4}, {FormattingOptions2.IndentationSize, 4} } Await AssertFormatAsync(code, expected, changedOptionSet:=optionSet) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function ReFormatWithDifferentIndent1() As Task Dim code = "Class SomeClass" + vbCrLf + " Sub Goo()" + vbCrLf + " Goo()" + vbCrLf + " End Sub" + vbCrLf + "End Class" Dim expected = "Class SomeClass" + vbCrLf + " Sub Goo()" + vbCrLf + " Goo()" + vbCrLf + " End Sub" + vbCrLf + "End Class" Dim optionSet = New OptionsCollection(LanguageNames.VisualBasic) From { {FormattingOptions2.UseTabs, False}, {FormattingOptions2.TabSize, 4}, {FormattingOptions2.IndentationSize, 2} } Await AssertFormatAsync(code, expected, changedOptionSet:=optionSet) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function ReFormatWithDifferentIndent2() As Task Dim code = "Class SomeClass" + vbCrLf + " Sub Goo()" + vbCrLf + " Goo()" + vbCrLf + " End Sub" + vbCrLf + "End Class" Dim expected = "Class SomeClass" + vbCrLf + " Sub Goo()" + vbCrLf + " Goo()" + vbCrLf + " End Sub" + vbCrLf + "End Class" Dim optionSet = New OptionsCollection(LanguageNames.VisualBasic) From { {FormattingOptions2.UseTabs, False}, {FormattingOptions2.TabSize, 4}, {FormattingOptions2.IndentationSize, 6} } Await AssertFormatAsync(code, expected, changedOptionSet:=optionSet) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function ReFormatWithTabsEnabledSmallIndentAndLargeTab() As Task Dim code = "Class SomeClass" + vbCrLf + " Sub Goo()" + vbCrLf + " Goo()" + vbCrLf + " End Sub" + vbCrLf + "End Class" Dim expected = "Class SomeClass" + vbCrLf + " Sub Goo()" + vbCrLf + vbTab + " Goo()" + vbCrLf + " End Sub" + vbCrLf + "End Class" Dim optionSet = New OptionsCollection(LanguageNames.VisualBasic) From { {FormattingOptions2.UseTabs, True}, {FormattingOptions2.TabSize, 3}, {FormattingOptions2.IndentationSize, 2} } Await AssertFormatAsync(code, expected, changedOptionSet:=optionSet) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function RegressionCommentFollowsSubsequentIndent4173() As Task Dim code = "Class SomeClass" + vbCrLf + " Sub Goo()" + vbCrLf + " 'comment" + vbCrLf + " End Sub" + vbCrLf + "End Class" Dim expected = "Class SomeClass" + vbCrLf + " Sub Goo()" + vbCrLf + " 'comment" + vbCrLf + " End Sub" + vbCrLf + "End Class" Await AssertFormatAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function FormatUsingOverloads() As Task Dim code = "Class SomeClass" + vbCrLf + " Sub Goo()" + vbCrLf + "Goo() " + vbCrLf + " End Sub" + vbCrLf + "End Class" Dim expected = "Class SomeClass" + vbCrLf + " Sub Goo()" + vbCrLf + " Goo()" + vbCrLf + " End Sub" + vbCrLf + "End Class" Await AssertFormatUsingAllEntryPointsAsync(code, expected) End Function <WorkItem(538533, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538533")> <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix4173_1() As Task Dim code = "Dim a = <xml> <%=<xml></xml>%> </xml>" Dim expected = " Dim a = <xml><%= <xml></xml> %></xml>" Await AssertFormatAsync(CreateMethod(code), CreateMethod(expected)) End Function <WorkItem(538533, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538533")> <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix4173_2() As Task Dim code = <Code>Class Goo Sub Goo() ' Comment Goo() End Sub End Class</Code> Dim expected = <Code>Class Goo Sub Goo() ' Comment Goo() End Sub End Class</Code> Dim optionSet = New OptionsCollection(LanguageNames.VisualBasic) From { {FormattingOptions2.UseTabs, True} } Await AssertFormatLf2CrLfAsync(code.Value, expected.Value, optionSet) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function FormatUsingAutoGeneratedCodeOperationProvider() As Task Dim code = "Class SomeClass" + vbCrLf + " Sub Goo()" + vbCrLf + "Goo() " + vbCrLf + " End Sub" + vbCrLf + "End Class" Dim expected = "Class SomeClass" + vbCrLf + " Sub Goo()" + vbCrLf + " Goo()" + vbCrLf + " End Sub" + vbCrLf + "End Class" Await AssertFormatAsync(code, expected) End Function <WorkItem(538533, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538533")> <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix4173_3() As Task Dim code = " Class C Sub Goo() Dim xml = <xml><code><node></node></code></xml> Dim j = From node In xml.<code> Select node.@att End Sub End Class" Dim expected = " Class C Sub Goo() Dim xml = <xml><code><node></node></code></xml> Dim j = From node In xml.<code> Select node.@att End Sub End Class" Await AssertFormatAsync(code, expected) End Function <WorkItem(538533, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538533")> <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix4173_4() As Task Dim code = <code>Class C Sub Main(args As String()) Dim r = 2 'goo End Sub End Class</code> Dim expected = <code>Class C Sub Main(args As String()) Dim r = 2 'goo End Sub End Class</code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <WorkItem(538533, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538533")> <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix4173_5() As Task Dim code = <code>Module Module1 Public Sub goo () End Sub End Module</code> Await AssertFormatLf2CrLfAsync(code.Value, code.Value) End Function <WorkItem(538533, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538533")> <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix4173_6() As Task Dim code = <code>Module module1 #If True Then #End If: goo() End Module</code> Await AssertFormatLf2CrLfAsync(code.Value, code.Value) End Function <WorkItem(538533, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538533")> <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix4173_7() As Task Dim code = <code>Module Module1 Sub Main() Dim x = Sub() End Sub : Dim y = Sub() End Sub ' Incorrect indent End Sub End Module</code> Dim expected = <code>Module Module1 Sub Main() Dim x = Sub() End Sub : Dim y = Sub() End Sub ' Incorrect indent End Sub End Module</code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <WorkItem(538533, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538533")> <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix4173_8() As Task Dim code = <code>Module Module1 Sub Main() ' ' End Sub End Module</code> Dim expected = <code>Module Module1 Sub Main() ' ' End Sub End Module</code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <WorkItem(538533, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538533")> <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix4173_9() As Task Dim code = <code>Module Module1 Sub Main() #If True Then Dim goo as Integer #End If End Sub End Module</code> Dim expected = <code>Module Module1 Sub Main() #If True Then Dim goo as Integer #End If End Sub End Module</code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <WorkItem(538772, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538772")> <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix4482() As Task Dim code = <code>_' Public Function GroupBy(Of K, R)( _ _' ByVal key As KeyFunc(Of K), _ _' ByVal selector As SelectorFunc(Of K, QueryableCollection(Of T), R)) _ ' As QueryableCollection(Of R)</code> Await AssertFormatLf2CrLfAsync(code.Value, code.Value) End Function <WorkItem(538754, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538754")> <Fact> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix4459() As Task Dim code = <Code>Option Strict Off Module Module1 Sub Main() End Sub Dim x As New List(Of Action(Of Integer)) From {Sub(a As Integer) Dim z As Integer = New Integer End Sub, Sub() IsNothing(Nothing), Function() As Integer Dim z As Integer = New Integer End Function} End Module </Code> Dim expected = <Code>Option Strict Off Module Module1 Sub Main() End Sub Dim x As New List(Of Action(Of Integer)) From {Sub(a As Integer) Dim z As Integer = New Integer End Sub, Sub() IsNothing(Nothing), Function() As Integer Dim z As Integer = New Integer End Function} End Module </Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <WorkItem(538675, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538675")> <Fact> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix4352() As Task Dim code = <Code>Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) 0: End End Sub End Module</Code> Dim expected = <Code>Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) 0: End End Sub End Module</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <WorkItem(538703, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538703")> <Fact> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix4394() As Task Await AssertFormatAsync(" ''' <summary> ''' ''' </summary> Module Program Sub Main(args As String()) End Sub End Module", " ''' <summary> ''' ''' </summary> Module Program Sub Main(args As String()) End Sub End Module") End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function GetTypeTest() As Task Dim code = "Dim a = GetType ( Object )" Dim expected = " Dim a = GetType(Object)" Await AssertFormatAsync(CreateMethod(code), CreateMethod(expected)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function NewObjectTest() As Task Dim code = "Dim a = New Object ( )" Dim expected = " Dim a = New Object()" Await AssertFormatAsync(CreateMethod(code), CreateMethod(expected), debugMode:=True) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function CTypeTest() As Task Dim code = "Dim a = CType ( args , String ( ) ) " Dim expected = " Dim a = CType(args, String())" Await AssertFormatAsync(CreateMethod(code), CreateMethod(expected)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function TernaryConditionTest() As Task Dim code = "Dim a = If ( True , 1, 2)" Dim expected = " Dim a = If(True, 1, 2)" Await AssertFormatAsync(CreateMethod(code), CreateMethod(expected)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function TryCastTest() As Task Dim code = "Dim a = TryCast ( args , String())" Dim expected = " Dim a = TryCast(args, String())" Await AssertFormatAsync(CreateMethod(code), CreateMethod(expected)) End Function <WorkItem(538703, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538703")> <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix4394_1() As Task Dim code = " Class C '''<summary> ''' Test Method '''</summary> Sub Method() End Sub End Class" Dim expected = " Class C '''<summary> ''' Test Method '''</summary> Sub Method() End Sub End Class" Await AssertFormatAsync(code, expected) End Function <WorkItem(538889, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538889")> <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix4639() As Task Dim code = "Imports <xmlns=""http://DefaultNamespace"" > " Dim expected = "Imports <xmlns=""http://DefaultNamespace"">" Await AssertFormatAsync(code, expected) End Function <WorkItem(538891, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538891")> <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix4641() As Task Dim code = <Code>Module module1 Structure C End Structure Sub goo() Dim cc As C ? = New C ? ( ) End Sub End Module</Code> Dim expected = <Code>Module module1 Structure C End Structure Sub goo() Dim cc As C? = New C?() End Sub End Module</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <WorkItem(538892, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538892")> <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix4642() As Task Dim code = <Code>_ </Code> Dim expected = <Code> _ </Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <WorkItem(538894, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538894")> <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix4644() As Task Dim code = <Code>Option Explicit Off Module Module1 Sub Main() Dim mmm = Sub(ByRef x As String, _ y As Integer) Console.WriteLine(x &amp; y) End Sub, zzz = Sub(y, _ x) mmm(y, _ x) End Sub lll = Sub(x _ ) Console.WriteLine(x) End Sub End Sub End Module</Code> Dim expected = <Code>Option Explicit Off Module Module1 Sub Main() Dim mmm = Sub(ByRef x As String, _ y As Integer) Console.WriteLine(x &amp; y) End Sub, zzz = Sub(y, _ x) mmm(y, _ x) End Sub lll = Sub(x _ ) Console.WriteLine(x) End Sub End Sub End Module</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <WorkItem(538897, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538897")> <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix4647() As Task Dim code = <Code>Option Explicit Off Module Module1 Sub Main() Dim mmm = Sub(ByRef x As String, _ y As Integer) Console.WriteLine(x &amp; y) End Sub, zzz = Sub(y, _ x) mmm(y, _ x) End Sub : Dim _ lll = Sub(x _ ) Console.WriteLine(x) End Sub End Sub End Module </Code> Dim expected = <Code>Option Explicit Off Module Module1 Sub Main() Dim mmm = Sub(ByRef x As String, _ y As Integer) Console.WriteLine(x &amp; y) End Sub, zzz = Sub(y, _ x) mmm(y, _ x) End Sub : Dim _ lll = Sub(x _ ) Console.WriteLine(x) End Sub End Sub End Module </Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <WorkItem(538962, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538962")> <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function WorkItem4737() As Task Dim code = "Dim x = <?xml version =""1.0""?><code></code>" Dim expected = " Dim x = <?xml version=""1.0""?><code></code>" Await AssertFormatAsync(CreateMethod(code), CreateMethod(expected)) End Function <WorkItem(539031, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539031")> <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix4826() As Task Dim code = <Code>Imports &lt;xmlns:a=""&gt; Module Program Sub Main() Dim x As New Dictionary(Of String, XElement) From {{"Root", &lt;x/&gt;}} x!Root%.&lt;nodes&gt;...&lt;a:subnodes&gt;.@a:b.ToString$ With x !Root.@a:b.EndsWith("").ToString$() With !Root .&lt;b&gt;.Value.StartsWith("") ...&lt;c&gt;(0).Value.ToString$() .ToString() Call .ToString() End With End With Dim buffer As New Byte(1023) {} End Sub End Module </Code> Await AssertFormatLf2CrLfAsync(code.Value, code.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function Parentheses() As Task Dim code = <Code>Class GenericMethod Sub Method(Of T)(t1 As T) NewMethod(Of T)(t1) End Sub Private Shared Sub NewMethod(Of T)(t1 As T) Dim a As T a = t1 End Sub End Class </Code> Await AssertFormatLf2CrLfAsync(code.Value, code.Value) End Function <WorkItem(539170, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539170")> <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix5022() As Task Dim code = <Code>Class A : _ Dim x End Class</Code> Dim expected = <Code>Class A : _ Dim x End Class</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <WorkItem(539324, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539324")> <Fact> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix5232() As Task Dim code = <Code>Imports System Module M Sub Main() If False Then If True Then Else Else Console.WriteLine(1) End Sub End Module</Code> Dim expected = <Code>Imports System Module M Sub Main() If False Then If True Then Else Else Console.WriteLine(1) End Sub End Module</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <WorkItem(539353, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539353")> <Fact> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix5270() As Task Dim code = <Code>Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Dim q = 2 + REM 3 End Sub End Module</Code> Dim expected = <Code>Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Dim q = 2 + REM 3 End Sub End Module</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <WorkItem(539358, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539358")> <Fact> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix5277() As Task Dim code = <Code> #If True Then #End If </Code> Dim expected = <Code> #If True Then #End If </Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <WorkItem(539455, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539455")> <Fact> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix5432() As Task Dim code = <Code>Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) dim q = 2 + _ 'comment End Sub End Module</Code> Dim expected = <Code>Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) dim q = 2 + _ 'comment End Sub End Module</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <WorkItem(539351, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539351")> <Fact> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix5268() As Task Dim code = <Code> #If True _ </Code> Await AssertFormatLf2CrLfAsync(code.Value, code.Value) End Function <WorkItem(539351, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539351")> <Fact> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix5268_1() As Task Dim code = <Code>Imports System Imports System.Collections.Generic Imports System.Linq Module Program #If True _ End Module</Code> Await AssertFormatLf2CrLfAsync(code.Value, code.Value) End Function <WorkItem(539473, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539473")> <Fact> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix5456() As Task Dim code = <Code>Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main() Dim goo = New With {.goo = "goo",.bar = "bar"} End Sub End Module</Code> Dim expected = <Code>Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main() Dim goo = New With {.goo = "goo", .bar = "bar"} End Sub End Module</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <WorkItem(539474, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539474")> <Fact> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix5457() As Task Dim code = <Code>Module module1 Sub main() Dim var1 As New Class1 [|var1.goofoo = 42 End Sub Sub something() something() End Sub End Module Public Class Class1 Public goofoo As String|] End Class</Code> Dim expected = <Code>Module module1 Sub main() Dim var1 As New Class1 var1.goofoo = 42 End Sub Sub something() something() End Sub End Module Public Class Class1 Public goofoo As String End Class</Code> Await AssertFormatSpanAsync(code.Value.Replace(vbLf, vbCrLf), expected.Value.Replace(vbLf, vbCrLf)) End Function <WorkItem(539503, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539503")> <Fact> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix5492() As Task Dim code = <Code>Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Dim classNum As Integer 'comment : classNum += 1 : Dim i As Integer End Sub End Module </Code> Dim expected = <Code>Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Dim classNum As Integer 'comment : classNum += 1 : Dim i As Integer End Sub End Module </Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <WorkItem(539508, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539508")> <Fact> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix5497() As Task Dim code = <Code>Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) : 'comment End Sub End Module</Code> Dim expected = <Code>Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) : 'comment End Sub End Module</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <WorkItem(539581, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539581")> <Fact> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix5594() As Task Dim code = <Code> &lt;Assembly : MyAttr()&gt; &lt;Module : MyAttr()&gt; Module Module1 Class MyAttr Inherits Attribute End Class Sub main() End Sub End Module </Code> Dim expected = <Code> &lt;Assembly: MyAttr()&gt; &lt;Module: MyAttr()&gt; Module Module1 Class MyAttr Inherits Attribute End Class Sub main() End Sub End Module </Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <WorkItem(539582, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539582")> <Fact> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix5595() As Task Dim code = <Code> Imports System.Xml &lt;SomeAttr()&gt; Module Module1 Sub Main() End Sub End Module </Code> Dim expected = <Code> Imports System.Xml &lt;SomeAttr()&gt; Module Module1 Sub Main() End Sub End Module </Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <WorkItem(539616, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539616")> <Fact> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix5637() As Task Dim code = <Code>Public Class Class1 'this line is comment line Sub sub1(ByVal aa As Integer) End Sub End Class</Code> Dim expected = <Code>Public Class Class1 'this line is comment line Sub sub1(ByVal aa As Integer) End Sub End Class</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function XmlTest() As Task Await AssertFormatAsync(" Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main() Dim book = </book > GetXml( </book >) End Sub End Module", " Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main() Dim book = </book> GetXml( </book>) End Sub End Module") End Function <Fact> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function XmlDocument() As Task Await AssertFormatAsync(" Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main() Dim book = <?xml version=""1.0""?> <?fff fff?> <!-- ffff --> <book/> <!-- last comment! yeah :) --> End Sub End Module", " Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main() Dim book = <?xml version=""1.0""?> <?fff fff?> <!-- ffff --> <book/> <!-- last comment! yeah :) --> End Sub End Module") End Function <Fact> <WorkItem(539458, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539458")> <WorkItem(539459, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539459")> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function XmlProcessingInstruction() As Task Await AssertFormatAsync(" Module Program Sub Main() Dim x = <?xml version=""1.0""?> <?blah?> <xml></xml> End Sub End Module", " Module Program Sub Main() Dim x = <?xml version=""1.0""?> <?blah?> <xml></xml> End Sub End Module") End Function <WorkItem(539463, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539463")> <WorkItem(530597, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530597")> <Fact> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function XmlTest5442() As Task Using workspace = New AdhocWorkspace() Dim inputOutput = " Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Dim goo = _ <LongBook> <%= _ From i In <were><a><b><c></c></b></a></were> _ Where i IsNot Nothing _ Select _ <f> <g> <f> </f> </g> </f> _ %> </LongBook> End Sub End Module" Dim project = workspace.CurrentSolution.AddProject("Project", "Project.dll", LanguageNames.VisualBasic) Dim document = project.AddDocument("Document", SourceText.From(inputOutput)) Dim root = Await document.GetSyntaxRootAsync() ' format first time Dim result = Formatter.GetFormattedTextChanges(root, workspace) AssertResult(inputOutput, Await document.GetTextAsync(), result) Dim document2 = document.WithText((Await document.GetTextAsync()).WithChanges(result)) Dim root2 = Await document2.GetSyntaxRootAsync() ' format second time Dim result2 = Formatter.GetFormattedTextChanges(root, workspace) AssertResult(inputOutput, Await document2.GetTextAsync(), result2) End Using End Function <WorkItem(539687, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539687")> <Fact> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix5731() As Task Dim code = <Code>Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) If True Then : 'comment End If End Sub End Module</Code> Dim expected = <Code>Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) If True Then : 'comment End If End Sub End Module</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <WorkItem(539545, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539545")> <Fact> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix5547() As Task Dim code = <Code>Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Select Case True Case True 'comment End Select End Sub End Module</Code> Dim expected = <Code>Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Select Case True Case True 'comment End Select End Sub End Module</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <WorkItem(539453, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539453")> <Fact> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix5430() As Task Dim code = " Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Dim abc = <xml> <video>video1</video> </xml> Dim r = From q In abc...<video> _ End Sub End Module" Await AssertFormatAsync(code, code) End Function <WorkItem(539889, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539889")> <Fact> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix5989() As Task Dim code = <Code>Imports System Module Program Sub Main(args As String()) Console.WriteLine(CInt (42)) End Sub End Module </Code> Dim expected = <Code>Imports System Module Program Sub Main(args As String()) Console.WriteLine(CInt(42)) End Sub End Module </Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <WorkItem(539409, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539409")> <Fact> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix6367() As Task Dim code = <Code>Module Program Sub Main(args As String()) Dim a As Integer = 1'Test End Sub End Module </Code> Dim expected = <Code>Module Program Sub Main(args As String()) Dim a As Integer = 1 'Test End Sub End Module </Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <WorkItem(539409, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539409")> <Fact> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix6367_1() As Task Dim code = <Code>Module Program Sub Main(args As String()) Dim a As Integer = 1 'Test End Sub End Module </Code> Await AssertFormatLf2CrLfAsync(code.Value, code.Value) End Function <WorkItem(540678, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540678")> <Fact> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BugFix7023_1() As Task Dim code = <Code>Module Program Public Operator +(x As Integer, y As Integer) Console.WriteLine("GOO") End Operator End Module </Code> Await AssertFormatLf2CrLfAsync(code.Value, code.Value) End Function <Fact> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function XmlTextWithEmbededExpression1() As Task Await AssertFormatAsync(" Class C Sub Method() Dim q = <xml> test <xml2><%= <xml3><xml4> </xml4></xml3> %></xml2> </xml> End Sub End Class", " Class C Sub Method() Dim q = <xml> test <xml2><%= <xml3><xml4> </xml4></xml3> %></xml2> </xml> End Sub End Class") End Function <Fact> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function XmlTextWithEmbededExpression2() As Task Await AssertFormatAsync(" Class C2 Sub Method() Dim q = <xml> tst <%= <xml2><xml3><xml4> </xml4></xml3> </xml2> %> </xml> End Sub End Class", " Class C2 Sub Method() Dim q = <xml> tst <%= <xml2><xml3><xml4> </xml4></xml3> </xml2> %> </xml> End Sub End Class") End Function <Fact> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function XmlText() As Task Await AssertFormatAsync(" Class C22 Sub Method() Dim q = <xml> tst <xml2><xml3><xml4> </xml4></xml3> </xml2> </xml> End Sub End Class", " Class C22 Sub Method() Dim q = <xml> tst <xml2><xml3><xml4> </xml4></xml3> </xml2> </xml> End Sub End Class") End Function <Fact> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function XmlTextWithComment() As Task Await AssertFormatAsync(" Class C223 Sub Method() Dim q = <xml> <!-- --> t st <xml2><xml3><xml4> </xml4></xml3> </xml2> </xml> End Sub End Class", " Class C223 Sub Method() Dim q = <xml> <!-- --> t st <xml2><xml3><xml4> </xml4></xml3> </xml2> </xml> End Sub End Class") End Function <WorkItem(541628, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541628")> <Fact> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function MultipleControlVariables() As Task Dim code = <Code>Module Program Sub Main(args As String()) Dim i, j As Integer For i = 0 To 1 For j = 0 To 1 Next j, i End Sub End Module</Code> Dim expected = <Code>Module Program Sub Main(args As String()) Dim i, j As Integer For i = 0 To 1 For j = 0 To 1 Next j, i End Sub End Module</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <WorkItem(541561, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541561")> <Fact> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function ColonTrivia() As Task Dim code = <Code>Module Program Sub Goo3() : End Sub Sub Main() End Sub End Module</Code> Dim expected = <Code>Module Program Sub Goo3() : End Sub Sub Main() End Sub End Module</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function MemberAccessInObjectMemberInitializer() As Task Dim code = <Code>Module Program Sub Main() Dim aw = New With {.a = 1, .b = 2+.a} End Sub End Module</Code> Dim expected = <Code>Module Program Sub Main() Dim aw = New With {.a = 1, .b = 2 + .a} End Sub End Module</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BinaryConditionalExpression() As Task Dim code = <Code>Module Program Sub Main() Dim x = If(Nothing, "") ' Inline x.ToString End Sub End Module</Code> Dim expected = <Code>Module Program Sub Main() Dim x = If(Nothing, "") ' Inline x.ToString End Sub End Module</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact> <WorkItem(539574, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539574")> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function Preprocessors() As Task Dim code = <Code>Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) #Const [PUBLIC] = 3 #Const goo = 23 #Const goo2=23 #Const goo3 = 23 #Const goo4 = 23 #Const goo5 = 23 End Sub End Module</Code> Dim expected = <Code>Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) #Const [PUBLIC] = 3 #Const goo = 23 #Const goo2 = 23 #Const goo3 = 23 #Const goo4 = 23 #Const goo5 = 23 End Sub End Module</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact> <WorkItem(10027, "DevDiv_Projects/Roslyn")> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function RandomCode1() As Task Dim code = <Code>'Imports alias 'goo' conflicts with 'goo' declared in the root namespace'</Code> Dim expected = <Code>'Imports alias 'goo' conflicts with 'goo' declared in the root namespace'</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact> <WorkItem(10027, "DevDiv_Projects/Roslyn")> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function RandomCode2() As Task Dim code = <Code>'Imports alias 'goo' conflicts with 'goo' declared in the root namespace'</Code> Dim expected = <Code>'Imports alias 'goo' conflicts with 'goo' declared in the root namespace'</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact> <WorkItem(542698, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542698")> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function ColonTrivia1() As Task Dim code = <Code>Imports _ System.Collections.Generic _ : : Imports _ System Imports System.Linq Module Program Sub Main(args As String()) Console.WriteLine("TEST") End Sub End Module </Code> Dim expected = <Code>Imports _ System.Collections.Generic _ : : Imports _ System Imports System.Linq Module Program Sub Main(args As String()) Console.WriteLine("TEST") End Sub End Module </Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact> <WorkItem(542698, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542698")> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function ColonTrivia2() As Task Dim code = <Code>Imports _ System.Collections.Generic _ : : Imports _ System Imports System.Linq Module Program Sub Main(args As String()) Console.WriteLine("TEST") End Sub End Module </Code> Await AssertFormatLf2CrLfAsync(code.Value, code.Value) End Function <Fact> <WorkItem(543197, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543197")> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function KeyInAnonymousType() As Task Dim code = <Code>Class C Sub S() Dim product = New With {Key.Name = "goo"} End Sub End Class </Code> Dim expected = <Code>Class C Sub S() Dim product = New With {Key .Name = "goo"} End Sub End Class </Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact> <WorkItem(544008, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544008")> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function TestGetXmlNamespace() As Task Dim code = <Code>Class C Sub S() Dim x = GetXmlNamespace(asdf) End Sub End Class </Code> Dim expected = <Code>Class C Sub S() Dim x = GetXmlNamespace(asdf) End Sub End Class </Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact> <WorkItem(539409, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539409")> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function StructuredTrivia() As Task Dim code = <Code>#const goo=2.0d</Code> Dim expected = <Code>#const goo = 2.0d</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function FormatComment1() As Task Dim code = <Code>Class A Sub Test() Console.WriteLine() : ' test Console.WriteLine() End Sub End Class</Code> Dim expected = <Code>Class A Sub Test() Console.WriteLine() : ' test Console.WriteLine() End Sub End Class</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function FormatComment2() As Task Dim code = <Code>Class A Sub Test() Console.WriteLine() ' test Console.WriteLine() End Sub End Class</Code> Dim expected = <Code>Class A Sub Test() Console.WriteLine() ' test Console.WriteLine() End Sub End Class</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact> <WorkItem(543248, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543248")> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function FormatBadCode() As Task Dim code = <Code>Imports System Class Program Shared Sub Main(args As String()) SyncLock From y As Char i, j As Char In String.Empty End SyncLock End Sub End Class</Code> Await AssertFormatLf2CrLfAsync(code.Value, code.Value) End Function <Fact> <WorkItem(544496, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544496")> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function AttributeInParameterList() As Task Dim code = <Code>Module Program Sub Main( &lt;Description&gt; args As String()) End Sub End Module</Code> Dim expected = <Code>Module Program Sub Main(&lt;Description&gt; args As String()) End Sub End Module</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact> <WorkItem(544980, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544980")> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function XmlElement_Expression() As Task Dim code = <Code>Module Program Dim x = &lt;x &lt;%= "" %&gt; /&gt; End Module</Code> Dim expected = <Code>Module Program Dim x = &lt;x &lt;%= "" %&gt;/&gt; End Module</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact> <WorkItem(542976, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542976")> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function XmlElementStartTag() As Task Dim code = <Code>Module Program Dim x = &lt;code &gt; &lt;/code&gt; End Module</Code> Dim expected = <Code>Module Program Dim x = &lt;code &gt; &lt;/code&gt; End Module</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact> <WorkItem(545088, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545088")> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function ForNext_MultipleVariables() As Task Dim code = <Code>Module Program Sub Method() For a = 0 To 1 For b = 0 To 1 For c = 0 To 1 Next c, b, a End Sub End Module</Code> Dim expected = <Code>Module Program Sub Method() For a = 0 To 1 For b = 0 To 1 For c = 0 To 1 Next c, b, a End Sub End Module</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact> <WorkItem(545088, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545088")> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function ForNext_MultipleVariables2() As Task Dim code = <Code>Module Program Sub Method() For z = 0 To 1 For a = 0 To 1 For b = 0 To 1 For c = 0 To 1 Next c, b, a Next z End Sub End Module</Code> Dim expected = <Code>Module Program Sub Method() For z = 0 To 1 For a = 0 To 1 For b = 0 To 1 For c = 0 To 1 Next c, b, a Next z End Sub End Module</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact> <WorkItem(544459, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544459")> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function DictionaryAccessOperator() As Task Dim code = <Code>Class S Default Property Def(s As String) As String Get Return Nothing End Get Set(value As String) End Set End Property Property Y As String End Class Module Program Sub Main(args As String()) Dim c As New S With {.Y =!Hello} End Sub End Module</Code> Dim expected = <Code>Class S Default Property Def(s As String) As String Get Return Nothing End Get Set(value As String) End Set End Property Property Y As String End Class Module Program Sub Main(args As String()) Dim c As New S With {.Y = !Hello} End Sub End Module</Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact> <WorkItem(542976, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542976")> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function XmlElementStartTag1() As Task Await AssertFormatAsync(" Class C Sub Method() Dim book = <book version=""goo"" > </book> End Sub End Class", " Class C Sub Method() Dim book = <book version=""goo"" > </book> End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Sub ElasticNewlines() Dim text = <text>Class C Implements INotifyPropertyChanged Dim _p As Integer Property P As Integer Get Return 0 End Get Set(value As Integer) SetProperty(_p, value, "P") End Set End Property Sub SetProperty(Of T)(ByRef field As T, value As T, name As String) If Not EqualityComparer(Of T).Default.Equals(field, value) Then field = value RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(name)) End If End Sub End Class</text>.Value.Replace(vbLf, vbCrLf) Dim expected = <text>Class C Implements INotifyPropertyChanged Dim _p As Integer Property P As Integer Get Return 0 End Get Set(value As Integer) SetProperty(_p, value, "P") End Set End Property Sub SetProperty(Of T)(ByRef field As T, value As T, name As String) If Not EqualityComparer(Of T).Default.Equals(field, value) Then field = value RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(name)) End If End Sub End Class</text>.Value.Replace(vbLf, vbCrLf) Dim root = SyntaxFactory.ParseCompilationUnit(text) Dim goo As New SyntaxAnnotation() Dim implementsStatement = DirectCast(root.Members(0), ClassBlockSyntax).Implements.First() root = root.ReplaceNode(implementsStatement, implementsStatement.NormalizeWhitespace(elasticTrivia:=True).WithAdditionalAnnotations(goo)) Dim field = DirectCast(root.Members(0), ClassBlockSyntax).Members(0) root = root.ReplaceNode(field, field.NormalizeWhitespace(elasticTrivia:=True).WithAdditionalAnnotations(goo)) Dim prop = DirectCast(root.Members(0), ClassBlockSyntax).Members(1) root = root.ReplaceNode(prop, prop.NormalizeWhitespace(elasticTrivia:=True).WithAdditionalAnnotations(goo)) Dim method = DirectCast(root.Members(0), ClassBlockSyntax).Members(2) root = root.ReplaceNode(method, method.NormalizeWhitespace(elasticTrivia:=True).WithAdditionalAnnotations(goo)) Using workspace = New AdhocWorkspace() Dim result = Formatter.Format(root, goo, workspace).ToString() Assert.Equal(expected, result) End Using End Sub <Fact> <WorkItem(545630, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545630")> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function SpacesInXmlStrings() As Task Dim text = "Imports <xmlns:x='&#70;'>" Await AssertFormatAsync(text, text) End Function <Fact> <WorkItem(545680, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545680")> <Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function SpaceBetweenPercentGreaterThanAndXmlName() As Task Dim text = <code>Module Program Sub Main(args As String()) End Sub Public Function GetXml() As XElement Return &lt;field name=&lt;%= 1 %&gt; type=&lt;%= 2 %&gt;&gt;&lt;/field&gt; End Function End Module</code> Await AssertFormatLf2CrLfAsync(text.Value, text.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function SpacingAroundXmlEntityLiterals() As Task Dim code = <Code><![CDATA[Class C Sub Bar() Dim goo = <Code>&lt;&gt;</Code> End Sub End Class ]]></Code> Await AssertFormatLf2CrLfAsync(code.Value, code.Value) End Function <WorkItem(547005, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547005")> <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function BadDirectivesAreValidRanges() As Task Dim code = <Code> #If False Then #end Region #End If #If False Then #end #End If </Code> Dim expected = <Code> #If False Then #end Region #End If #If False Then #end #End If </Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> <WorkItem(17313, "DevDiv_Projects/Roslyn")> Public Async Function TestElseIfFormatting_Directive() As Task Dim code = <Code><![CDATA[ #If True Then #Else If False Then #End If ]]></Code> Dim expected = <Code><![CDATA[ #If True Then #ElseIf False Then #End If ]]></Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> <WorkItem(529899, "DevDiv_Projects/Roslyn")> Public Async Function IndentContinuedLineOfSingleLineLambdaToFunctionKeyword() As Task Dim code = <Code><![CDATA[ Module Program Sub Main(ByVal args As String()) Dim a1 = Function() args(0) _ + 1 End Sub End Module ]]></Code> Dim expected = <Code><![CDATA[ Module Program Sub Main(ByVal args As String()) Dim a1 = Function() args(0) _ + 1 End Sub End Module ]]></Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> <WorkItem(604032, "DevDiv_Projects/Roslyn")> Public Async Function TestSpaceBetweenEqualsAndDotOfXml() As Task Dim code = <Code><![CDATA[ Module Program Sub Main(args As String()) Dim xml = <Order id="1"> <Customer> <Name>Bob</Name> </Customer> <Contents> <Item productId="1" quantity="2"/> <Item productId="2" quantity="1"/> </Contents> </Order> With xml Dim customerName =.<Customer>.<Name>.Value Dim itemCount =...<Item>.Count Dim orderId =.@id End With End Sub End Module ]]></Code> Dim expected = <Code><![CDATA[ Module Program Sub Main(args As String()) Dim xml = <Order id="1"> <Customer> <Name>Bob</Name> </Customer> <Contents> <Item productId="1" quantity="2"/> <Item productId="2" quantity="1"/> </Contents> </Order> With xml Dim customerName = .<Customer>.<Name>.Value Dim itemCount = ...<Item>.Count Dim orderId = .@id End With End Sub End Module ]]></Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> <WorkItem(604092, "DevDiv_Projects/Roslyn")> Public Async Function AnchorIndentToTheFirstTokenOfXmlBlock() As Task Dim code = <Code><![CDATA[ Module Program Sub Main(args As String()) With <a> </a> Dim s = 1 End With SyncLock <b> </b> Return End SyncLock Using <c> </c> Return End Using For Each reallyReallyReallyLongIdentifierNameHere In <d> </d> Return Next End Sub End Module ]]></Code> Dim expected = <Code><![CDATA[ Module Program Sub Main(args As String()) With <a> </a> Dim s = 1 End With SyncLock <b> </b> Return End SyncLock Using <c> </c> Return End Using For Each reallyReallyReallyLongIdentifierNameHere In <d> </d> Return Next End Sub End Module ]]></Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> <WorkItem(530366, "DevDiv_Projects/Roslyn")> Public Async Function ForcedSpaceBetweenXmlNameTokenAndPercentGreaterThanToken() As Task Dim code = <Code><![CDATA[ Module Module1 Sub Main() Dim e As XElement Dim y = <root><%= e.@test %></root> End Sub End Module ]]></Code> Dim expected = <Code><![CDATA[ Module Module1 Sub Main() Dim e As XElement Dim y = <root><%= e.@test %></root> End Sub End Module ]]></Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> <WorkItem(531444, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531444")> Public Async Function TestElseIfFormattingForNestedSingleLineIf() As Task Dim code = <Code><![CDATA[ If True Then Console.WriteLine(1) Else If True Then Return ]]></Code> Dim actual = CreateMethod(code.Value) ' Verify "Else If" doesn't get formatted to "ElseIf" Await AssertFormatLf2CrLfAsync(actual, actual) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function TestDontCrashOnMissingTokenWithComment() As Task Dim code = <Code><![CDATA[ Namespace NS Class CL Sub Method() Dim goo = Sub(x) 'Comment ]]></Code> Await AssertFormatLf2CrLfAsync(code.Value, code.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function TestBang() As Task Dim code = <Code><![CDATA[ Imports System.Collections Module Program Sub Main() Dim x As New Hashtable Dim y = x ! _ Goo End Sub End Module ]]></Code> Dim expected = <Code><![CDATA[ Imports System.Collections Module Program Sub Main() Dim x As New Hashtable Dim y = x ! _ Goo End Sub End Module ]]></Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> <WorkItem(679864, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/679864")> Public Async Function InsertSpaceBetweenXMLMemberAttributeAccessAndEqualsToken() As Task Dim expected = <Code><![CDATA[ Imports System Imports System.Collections Module Program Sub Main(args As String()) Dim element = <element></element> Dim goo = element.Single(Function(e) e.@Id = 1) End Sub End Module ]]></Code> Dim code = <Code><![CDATA[ Imports System Imports System.Collections Module Program Sub Main(args As String()) Dim element = <element></element> Dim goo = element.Single(Function(e) e.@Id = 1) End Sub End Module ]]></Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> <WorkItem(923172, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/923172")> Public Async Function TestMemberAccessAfterOpenParen() As Task Dim expected = <Code><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) With args If .IsNew = True Then Return Nothing Else Return CTypeDynamic(Of T)(.Value, .Hello) End If End With End Sub End Module ]]></Code> Dim code = <Code><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) With args If .IsNew = True Then Return Nothing Else Return CTypeDynamic(Of T)( .Value, .Hello) End If End With End Sub End Module ]]></Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> <WorkItem(923180, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/923180")> Public Async Function TestXmlMemberAccessDot() As Task Dim expected = <Code><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) With x.<Service>.First If .<WorkerServiceType>.Count > 0 Then Main(.<A>.Value, .<B>.Value) Dim i = .<A>.Value + .<B>.Value End If End With End Sub End Module ]]></Code> Dim code = <Code><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) With x.<Service>.First If.<WorkerServiceType>.Count > 0 Then Main(.<A>.Value,.<B>.Value) Dim i = .<A>.Value +.<B>.Value End If End With End Sub End Module ]]></Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> <WorkItem(530601, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530601")> Public Async Function TestElasticFormattingPropertySetter() As Task Dim parameterList = SyntaxFactory.ParseParameterList(String.Format("(value As {0})", "Integer")) Dim setter = SyntaxFactory.AccessorBlock(SyntaxKind.SetAccessorBlock, SyntaxFactory.AccessorStatement(SyntaxKind.SetAccessorStatement, SyntaxFactory.Token(SyntaxKind.SetKeyword)). WithParameterList(parameterList), SyntaxFactory.EndBlockStatement(SyntaxKind.EndSetStatement, SyntaxFactory.Token(SyntaxKind.SetKeyword))) Dim setPropertyStatement = SyntaxFactory.ParseExecutableStatement(String.Format("SetProperty({0}, value, ""{1}"")", "field", "Property")).WithLeadingTrivia(SyntaxFactory.ElasticMarker) setter = setter.WithStatements(SyntaxFactory.SingletonList(setPropertyStatement)) Dim solution = New AdhocWorkspace().CurrentSolution Dim project = solution.AddProject("proj", "proj", LanguageNames.VisualBasic) Dim document = project.AddDocument("goo.vb", <text>Class C WriteOnly Property Prop As Integer End Property End Class</text>.Value) Dim propertyBlock = (Await document.GetSyntaxRootAsync()).DescendantNodes().OfType(Of PropertyBlockSyntax).Single() document = Await Formatter.FormatAsync(document.WithSyntaxRoot( (Await document.GetSyntaxRootAsync()).ReplaceNode(propertyBlock, propertyBlock.WithAccessors(SyntaxFactory.SingletonList(setter))))) Dim actual = (Await document.GetTextAsync()).ToString() Assert.Equal(actual, actual) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function TestWarningDirectives() As Task Dim text = <Code> # enable warning[BC000],bc123, ap456,_789' comment Module Program # disable warning 'Comment Sub Main() #disable warning bc123, bC456,someId789 End Sub End Module # enable warning </Code> Dim expected = <Code> #enable warning [BC000], bc123, ap456, _789' comment Module Program #disable warning 'Comment Sub Main() #disable warning bc123, bC456, someId789 End Sub End Module #enable warning </Code> Await AssertFormatLf2CrLfAsync(text.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function TestIncompleteWarningDirectives() As Task Dim text = <Code> # disable Module M1 # enable warning[bc123], ' Comment End Module </Code> Dim expected = <Code> #disable Module M1 #enable warning [bc123], ' Comment End Module </Code> Await AssertFormatLf2CrLfAsync(text.Value, expected.Value) End Function <WorkItem(796562, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/796562")> <WorkItem(3293, "https://github.com/dotnet/roslyn/issues/3293")> <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function TriviaAtEndOfCaseBelongsToNextCase() As Task Dim text = <Code> Class X Function F(x As Integer) As Integer Select Case x Case 1 Return 2 ' This comment describes case 1 ' This comment describes case 2 Case 2, Return 3 End Select Return 5 End Function End Class </Code> Dim expected = <Code> Class X Function F(x As Integer) As Integer Select Case x Case 1 Return 2 ' This comment describes case 1 ' This comment describes case 2 Case 2, Return 3 End Select Return 5 End Function End Class </Code> Await AssertFormatLf2CrLfAsync(text.Value, expected.Value) End Function <WorkItem(938188, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/938188")> <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function XelementAttributeSpacing() As Task Dim text = <Code> Class X Function F(x As Integer) As Integer Dim x As XElement x.@Goo= "Hello" End Function End Class </Code> Dim expected = <Code> Class X Function F(x As Integer) As Integer Dim x As XElement x.@Goo = "Hello" End Function End Class </Code> Await AssertFormatLf2CrLfAsync(text.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function ConditionalAccessFormatting() As Task Const code = " Module Module1 Class G Public t As String End Class Sub Main() Dim x = New G() Dim q = x ? . t ? ( 0 ) Dim me = Me ? . ToString() Dim mb = MyBase ? . ToString() Dim mc = MyClass ? . ToString() Dim i = New With {.a = 3} ? . ToString() Dim s = ""Test"" ? . ToString() Dim s2 = $""Test"" ? . ToString() Dim x1 = <a></a> ? . <b> Dim x2 = <a/> ? . <b> End Sub End Module " Const expected = " Module Module1 Class G Public t As String End Class Sub Main() Dim x = New G() Dim q = x?.t?(0) Dim me = Me?.ToString() Dim mb = MyBase?.ToString() Dim mc = MyClass?.ToString() Dim i = New With {.a = 3}?.ToString() Dim s = ""Test""?.ToString() Dim s2 = $""Test""?.ToString() Dim x1 = <a></a>?.<b> Dim x2 = <a/>?.<b> End Sub End Module " Await AssertFormatAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function ChainedConditionalAccessFormatting() As Task Const code = " Module Module1 Class G Public t As String End Class Sub Main() Dim x = New G() Dim q = x ? . t ? . ToString() ? . ToString ( 0 ) Dim me = Me ? . ToString() ? . Length Dim mb = MyBase ? . ToString() ? . Length Dim mc = MyClass ? . ToString() ? . Length Dim i = New With {.a = 3} ? . ToString() ? . Length Dim s = ""Test"" ? . ToString() ? . Length Dim s2 = $""Test"" ? . ToString() ? . Length Dim x1 = <a></a> ? . <b> ? . <c> Dim x2 = <a/> ? . <b> ? . <c> End Sub End Module " Const expected = " Module Module1 Class G Public t As String End Class Sub Main() Dim x = New G() Dim q = x?.t?.ToString()?.ToString(0) Dim me = Me?.ToString()?.Length Dim mb = MyBase?.ToString()?.Length Dim mc = MyClass?.ToString()?.Length Dim i = New With {.a = 3}?.ToString()?.Length Dim s = ""Test""?.ToString()?.Length Dim s2 = $""Test""?.ToString()?.Length Dim x1 = <a></a>?.<b>?.<c> Dim x2 = <a/>?.<b>?.<c> End Sub End Module " Await AssertFormatAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function NameOfFormatting() As Task Dim text = <Code> Module M Dim s = NameOf ( M ) End Module </Code> Dim expected = <Code> Module M Dim s = NameOf(M) End Module </Code> Await AssertFormatLf2CrLfAsync(text.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function InterpolatedString1() As Task Dim text = <Code> Class C Sub M() Dim a = "World" Dim b =$"Hello, {a}" End Sub End Class </Code> Dim expected = <Code> Class C Sub M() Dim a = "World" Dim b = $"Hello, {a}" End Sub End Class </Code> Await AssertFormatLf2CrLfAsync(text.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function InterpolatedString2() As Task Dim text = <Code> Class C Sub M() Dim a = "Hello" Dim b = "World" Dim c = $"{a}, {b}" End Sub End Class </Code> Dim expected = <Code> Class C Sub M() Dim a = "Hello" Dim b = "World" Dim c = $"{a}, {b}" End Sub End Class </Code> Await AssertFormatLf2CrLfAsync(text.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function InterpolatedString3() As Task Dim text = <Code> Class C Sub M() Dim a = "World" Dim b = $"Hello, { a }" End Sub End Class </Code> Dim expected = <Code> Class C Sub M() Dim a = "World" Dim b = $"Hello, { a }" End Sub End Class </Code> Await AssertFormatLf2CrLfAsync(text.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function InterpolatedString4() As Task Dim text = <Code> Class C Sub M() Dim a = "Hello" Dim b = "World" Dim c = $"{ a }, { b }" End Sub End Class </Code> Dim expected = <Code> Class C Sub M() Dim a = "Hello" Dim b = "World" Dim c = $"{ a }, { b }" End Sub End Class </Code> Await AssertFormatLf2CrLfAsync(text.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function InterpolatedString5() As Task Dim text = <Code> Class C Sub M() Dim s = $"{42 , -4 :x}" End Sub End Class </Code> Dim expected = <Code> Class C Sub M() Dim s = $"{42,-4:x}" End Sub End Class </Code> Await AssertFormatLf2CrLfAsync(text.Value, expected.Value) End Function <WorkItem(3293, "https://github.com/dotnet/roslyn/issues/3293")> <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Async Function CaseCommentsRemainsUndisturbed() As Task Dim text = <Code> Class Program Sub Main(args As String()) Dim s = 0 Select Case s Case 0 ' Comment should not be indented Case 2 ' comment Console.WriteLine(s) Case 4 End Select End Sub End Class </Code> Dim expected = <Code> Class Program Sub Main(args As String()) Dim s = 0 Select Case s Case 0 ' Comment should not be indented Case 2 ' comment Console.WriteLine(s) Case 4 End Select End Sub End Class </Code> Await AssertFormatLf2CrLfAsync(text.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> Public Sub NewLineOption_LineFeedOnly() Dim tree = SyntaxFactory.ParseCompilationUnit("Class C" & vbCrLf & "End Class") ' replace all EOL trivia with elastic markers to force the formatter to add EOL back tree = tree.ReplaceTrivia(tree.DescendantTrivia().Where(Function(tr) tr.IsKind(SyntaxKind.EndOfLineTrivia)), Function(o, r) SyntaxFactory.ElasticMarker) Dim formatted = Formatter.Format(tree, DefaultWorkspace, DefaultWorkspace.Options.WithChangedOption(FormattingOptions.NewLine, LanguageNames.VisualBasic, vbLf)) Dim actual = formatted.ToFullString() Dim expected = "Class C" & vbLf & "End Class" Assert.Equal(expected, actual) End Sub <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> <WorkItem(2822, "https://github.com/dotnet/roslyn/issues/2822")> Public Async Function FormatLabelFollowedByDotExpression() As Task Dim code = <Code> Module Module1 Sub Main() With New List(Of Integer) lab: .Capacity = 15 End With End Sub End Module </Code> Dim expected = <Code> Module Module1 Sub Main() With New List(Of Integer) lab: .Capacity = 15 End With End Sub End Module </Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> <WorkItem(21923, "https://github.com/dotnet/roslyn/issues/21923")> Public Async Function FormatNullableTuple() As Task Dim code = <Code> Class C Dim x As (Integer, Integer) ? End Class </Code> Dim expected = <Code> Class C Dim x As (Integer, Integer)? End Class </Code> Await AssertFormatLf2CrLfAsync(code.Value, expected.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> <WorkItem(2822, "https://github.com/dotnet/roslyn/issues/2822")> Public Async Function FormatOmittedArgument() As Task Dim code = <Code> Class C Sub M() Call M( a, , a ) End Sub End Class</Code> Await AssertFormatLf2CrLfAsync(code.Value, code.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Formatting)> <WorkItem(8258, "https://github.com/dotnet/roslyn/issues/8258")> Public Async Function FormatDictionaryOperatorProperly() As Task Dim code = " Class C Public Shared Sub AutoFormatSample() ' Automatic Code Formatting in VB.NET ' Problem with ! dictionary access operator Dim dict As New Dictionary(Of String, String) dict.Add(""Apple"", ""Green"") dict.Add(""Orange"", ""Orange"") dict.Add(""Banana"", ""Yellow"") Dim x As String = (New Dictionary(Of String, String)(dict)) !Banana 'added space in front of ""!"" With dict !Apple = ""Red"" Dim multiColors = !Apple &!Orange &!Banana 'missing space between ""&"" and ""!"" If!Banana = ""Yellow"" Then 'missing space between ""If"" and ""!"" !Banana = ""Green"" End If End With End Sub End Class" Dim expected = " Class C Public Shared Sub AutoFormatSample() ' Automatic Code Formatting in VB.NET ' Problem with ! dictionary access operator Dim dict As New Dictionary(Of String, String) dict.Add(""Apple"", ""Green"") dict.Add(""Orange"", ""Orange"") dict.Add(""Banana"", ""Yellow"") Dim x As String = (New Dictionary(Of String, String)(dict))!Banana 'added space in front of ""!"" With dict !Apple = ""Red"" Dim multiColors = !Apple & !Orange & !Banana 'missing space between ""&"" and ""!"" If !Banana = ""Yellow"" Then 'missing space between ""If"" and ""!"" !Banana = ""Green"" End If End With End Sub End Class" Await AssertFormatAsync(code, expected) End Function End Class End Namespace
-1
dotnet/roslyn
56,419
Fix partial method doc comments
Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
RikkiGibson
"2021-09-15T20:47:39Z"
"2021-09-21T23:49:10Z"
0f60b3e9446f5d0fc14a570998c81a5d6c40cc23
8cda7462843d43d9b72039eede2f4cb43126cac2
Fix partial method doc comments. Fixes #54103. The specific rule changes implemented in this PR are laid out in dotnet/csharplang#5193. Have added tests to ensure that the expected documentation is shown in Quick Info.
./src/Workspaces/Remote/Core/ExternalAccess/UnitTesting/Api/UnitTestingRemoteHostClient.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Remote; namespace Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Api { internal readonly struct UnitTestingRemoteHostClient { private readonly ServiceHubRemoteHostClient _client; private readonly UnitTestingServiceDescriptorsWrapper _serviceDescriptors; private readonly UnitTestingRemoteServiceCallbackDispatcherRegistry _callbackDispatchers; internal UnitTestingRemoteHostClient(ServiceHubRemoteHostClient client, UnitTestingServiceDescriptorsWrapper serviceDescriptors, UnitTestingRemoteServiceCallbackDispatcherRegistry callbackDispatchers) { _client = client; _serviceDescriptors = serviceDescriptors; _callbackDispatchers = callbackDispatchers; } public static async Task<UnitTestingRemoteHostClient?> TryGetClientAsync(HostWorkspaceServices services, UnitTestingServiceDescriptorsWrapper serviceDescriptors, UnitTestingRemoteServiceCallbackDispatcherRegistry callbackDispatchers, CancellationToken cancellationToken = default) { var client = await RemoteHostClient.TryGetClientAsync(services, cancellationToken).ConfigureAwait(false); if (client is null) return null; return new UnitTestingRemoteHostClient((ServiceHubRemoteHostClient)client, serviceDescriptors, callbackDispatchers); } public static bool IsServiceHubProcessCoreClr(HostWorkspaceServices services) { var optionServices = services.GetRequiredService<IOptionService>(); return optionServices.GetOption(RemoteHostOptions.OOPCoreClr) || optionServices.GetOption(RemoteHostOptions.OOPCoreClrFeatureFlag); } public UnitTestingRemoteServiceConnectionWrapper<TService> CreateConnection<TService>(object? callbackTarget) where TService : class => new(_client.CreateConnection<TService>(_serviceDescriptors.UnderlyingObject, _callbackDispatchers, callbackTarget)); // no solution, no callback: public async ValueTask<bool> TryInvokeAsync<TService>(Func<TService, CancellationToken, ValueTask> invocation, CancellationToken cancellationToken) where TService : class { using var connection = CreateConnection<TService>(callbackTarget: null); return await connection.TryInvokeAsync(invocation, cancellationToken).ConfigureAwait(false); } public async ValueTask<Optional<TResult>> TryInvokeAsync<TService, TResult>(Func<TService, CancellationToken, ValueTask<TResult>> invocation, CancellationToken cancellationToken) where TService : class { using var connection = CreateConnection<TService>(callbackTarget: null); return await connection.TryInvokeAsync(invocation, cancellationToken).ConfigureAwait(false); } // no solution, callback: public async ValueTask<bool> TryInvokeAsync<TService>(Func<TService, UnitTestingRemoteServiceCallbackIdWrapper, CancellationToken, ValueTask> invocation, object callbackTarget, CancellationToken cancellationToken) where TService : class { using var connection = CreateConnection<TService>(callbackTarget); return await connection.TryInvokeAsync(invocation, cancellationToken).ConfigureAwait(false); } public async ValueTask<Optional<TResult>> TryInvokeAsync<TService, TResult>(Func<TService, UnitTestingRemoteServiceCallbackIdWrapper, CancellationToken, ValueTask<TResult>> invocation, object callbackTarget, CancellationToken cancellationToken) where TService : class { using var connection = CreateConnection<TService>(callbackTarget); return await connection.TryInvokeAsync(invocation, cancellationToken).ConfigureAwait(false); } // solution, no callback: public async ValueTask<bool> TryInvokeAsync<TService>(Solution solution, Func<TService, UnitTestingPinnedSolutionInfoWrapper, CancellationToken, ValueTask> invocation, CancellationToken cancellationToken) where TService : class { using var connection = CreateConnection<TService>(callbackTarget: null); return await connection.TryInvokeAsync(solution, invocation, cancellationToken).ConfigureAwait(false); } public async ValueTask<Optional<TResult>> TryInvokeAsync<TService, TResult>(Solution solution, Func<TService, UnitTestingPinnedSolutionInfoWrapper, CancellationToken, ValueTask<TResult>> invocation, CancellationToken cancellationToken) where TService : class { using var connection = CreateConnection<TService>(callbackTarget: null); return await connection.TryInvokeAsync(solution, invocation, cancellationToken).ConfigureAwait(false); } // solution, callback: public async ValueTask<bool> TryInvokeAsync<TService>(Solution solution, Func<TService, UnitTestingPinnedSolutionInfoWrapper, UnitTestingRemoteServiceCallbackIdWrapper, CancellationToken, ValueTask> invocation, object callbackTarget, CancellationToken cancellationToken) where TService : class { using var connection = CreateConnection<TService>(callbackTarget); return await connection.TryInvokeAsync(solution, invocation, cancellationToken).ConfigureAwait(false); } public async ValueTask<Optional<TResult>> TryInvokeAsync<TService, TResult>(Solution solution, Func<TService, UnitTestingPinnedSolutionInfoWrapper, UnitTestingRemoteServiceCallbackIdWrapper, CancellationToken, ValueTask<TResult>> invocation, object callbackTarget, CancellationToken cancellationToken) where TService : class { using var connection = CreateConnection<TService>(callbackTarget); return await connection.TryInvokeAsync(solution, invocation, cancellationToken).ConfigureAwait(false); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Remote; namespace Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Api { internal readonly struct UnitTestingRemoteHostClient { private readonly ServiceHubRemoteHostClient _client; private readonly UnitTestingServiceDescriptorsWrapper _serviceDescriptors; private readonly UnitTestingRemoteServiceCallbackDispatcherRegistry _callbackDispatchers; internal UnitTestingRemoteHostClient(ServiceHubRemoteHostClient client, UnitTestingServiceDescriptorsWrapper serviceDescriptors, UnitTestingRemoteServiceCallbackDispatcherRegistry callbackDispatchers) { _client = client; _serviceDescriptors = serviceDescriptors; _callbackDispatchers = callbackDispatchers; } public static async Task<UnitTestingRemoteHostClient?> TryGetClientAsync(HostWorkspaceServices services, UnitTestingServiceDescriptorsWrapper serviceDescriptors, UnitTestingRemoteServiceCallbackDispatcherRegistry callbackDispatchers, CancellationToken cancellationToken = default) { var client = await RemoteHostClient.TryGetClientAsync(services, cancellationToken).ConfigureAwait(false); if (client is null) return null; return new UnitTestingRemoteHostClient((ServiceHubRemoteHostClient)client, serviceDescriptors, callbackDispatchers); } public static bool IsServiceHubProcessCoreClr(HostWorkspaceServices services) { var optionServices = services.GetRequiredService<IOptionService>(); return optionServices.GetOption(RemoteHostOptions.OOPCoreClr) || optionServices.GetOption(RemoteHostOptions.OOPCoreClrFeatureFlag); } public UnitTestingRemoteServiceConnectionWrapper<TService> CreateConnection<TService>(object? callbackTarget) where TService : class => new(_client.CreateConnection<TService>(_serviceDescriptors.UnderlyingObject, _callbackDispatchers, callbackTarget)); // no solution, no callback: public async ValueTask<bool> TryInvokeAsync<TService>(Func<TService, CancellationToken, ValueTask> invocation, CancellationToken cancellationToken) where TService : class { using var connection = CreateConnection<TService>(callbackTarget: null); return await connection.TryInvokeAsync(invocation, cancellationToken).ConfigureAwait(false); } public async ValueTask<Optional<TResult>> TryInvokeAsync<TService, TResult>(Func<TService, CancellationToken, ValueTask<TResult>> invocation, CancellationToken cancellationToken) where TService : class { using var connection = CreateConnection<TService>(callbackTarget: null); return await connection.TryInvokeAsync(invocation, cancellationToken).ConfigureAwait(false); } // no solution, callback: public async ValueTask<bool> TryInvokeAsync<TService>(Func<TService, UnitTestingRemoteServiceCallbackIdWrapper, CancellationToken, ValueTask> invocation, object callbackTarget, CancellationToken cancellationToken) where TService : class { using var connection = CreateConnection<TService>(callbackTarget); return await connection.TryInvokeAsync(invocation, cancellationToken).ConfigureAwait(false); } public async ValueTask<Optional<TResult>> TryInvokeAsync<TService, TResult>(Func<TService, UnitTestingRemoteServiceCallbackIdWrapper, CancellationToken, ValueTask<TResult>> invocation, object callbackTarget, CancellationToken cancellationToken) where TService : class { using var connection = CreateConnection<TService>(callbackTarget); return await connection.TryInvokeAsync(invocation, cancellationToken).ConfigureAwait(false); } // solution, no callback: public async ValueTask<bool> TryInvokeAsync<TService>(Solution solution, Func<TService, UnitTestingPinnedSolutionInfoWrapper, CancellationToken, ValueTask> invocation, CancellationToken cancellationToken) where TService : class { using var connection = CreateConnection<TService>(callbackTarget: null); return await connection.TryInvokeAsync(solution, invocation, cancellationToken).ConfigureAwait(false); } public async ValueTask<Optional<TResult>> TryInvokeAsync<TService, TResult>(Solution solution, Func<TService, UnitTestingPinnedSolutionInfoWrapper, CancellationToken, ValueTask<TResult>> invocation, CancellationToken cancellationToken) where TService : class { using var connection = CreateConnection<TService>(callbackTarget: null); return await connection.TryInvokeAsync(solution, invocation, cancellationToken).ConfigureAwait(false); } // solution, callback: public async ValueTask<bool> TryInvokeAsync<TService>(Solution solution, Func<TService, UnitTestingPinnedSolutionInfoWrapper, UnitTestingRemoteServiceCallbackIdWrapper, CancellationToken, ValueTask> invocation, object callbackTarget, CancellationToken cancellationToken) where TService : class { using var connection = CreateConnection<TService>(callbackTarget); return await connection.TryInvokeAsync(solution, invocation, cancellationToken).ConfigureAwait(false); } public async ValueTask<Optional<TResult>> TryInvokeAsync<TService, TResult>(Solution solution, Func<TService, UnitTestingPinnedSolutionInfoWrapper, UnitTestingRemoteServiceCallbackIdWrapper, CancellationToken, ValueTask<TResult>> invocation, object callbackTarget, CancellationToken cancellationToken) where TService : class { using var connection = CreateConnection<TService>(callbackTarget); return await connection.TryInvokeAsync(solution, invocation, cancellationToken).ConfigureAwait(false); } } }
-1
dotnet/roslyn
56,416
Do not include function type conversions in user-defined conversions
Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
cston
"2021-09-15T18:16:38Z"
"2021-09-24T23:24:46Z"
bb99d0bc89bde01650d2a694d720d600dd952dcb
3913f352cf066fa485869d866e4753fa721cbe93
Do not include function type conversions in user-defined conversions. Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
./src/Compilers/CSharp/Portable/Binder/Semantics/BestTypeInferrer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.CSharp { internal static class BestTypeInferrer { public static NullableAnnotation GetNullableAnnotation(ArrayBuilder<TypeWithAnnotations> types) { #if DEBUG var example = types.FirstOrDefault(t => t.HasType); #endif var result = NullableAnnotation.NotAnnotated; foreach (var type in types) { #if DEBUG Debug.Assert(!type.HasType || type.Equals(example, TypeCompareKind.AllIgnoreOptions)); #endif // This uses the covariant merging rules. result = result.Join(type.NullableAnnotation); } return result; } public static NullableFlowState GetNullableState(ArrayBuilder<TypeWithState> types) { NullableFlowState result = NullableFlowState.NotNull; foreach (var type in types) { result = result.Join(type.State); } return result; } /// <remarks> /// This method finds the best common type of a set of expressions as per section 7.5.2.14 of the specification. /// NOTE: If some or all of the expressions have error types, we return error type as the inference result. /// </remarks> public static TypeSymbol? InferBestType( ImmutableArray<BoundExpression> exprs, ConversionsBase conversions, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: 7.5.2.14 Finding the best common type of a set of expressions // SPEC: In some cases, a common type needs to be inferred for a set of expressions. In particular, the element types of implicitly typed arrays and // SPEC: the return types of anonymous functions with block bodies are found in this way. // SPEC: Intuitively, given a set of expressions E1…Em this inference should be equivalent to calling a method: // SPEC: T M<X>(X x1 … X xm) // SPEC: with the Ei as arguments. // SPEC: More precisely, the inference starts out with an unfixed type variable X. Output type inferences are then made from each Ei to X. // SPEC: Finally, X is fixed and, if successful, the resulting type S is the resulting best common type for the expressions. // SPEC: If no such S exists, the expressions have no best common type. // All non-null types are candidates for best type inference. IEqualityComparer<TypeSymbol> comparer = conversions.IncludeNullability ? Symbols.SymbolEqualityComparer.ConsiderEverything : Symbols.SymbolEqualityComparer.IgnoringNullable; HashSet<TypeSymbol> candidateTypes = new HashSet<TypeSymbol>(comparer); foreach (BoundExpression expr in exprs) { TypeSymbol? type = expr.GetTypeOrFunctionType(); if (type is { }) { if (type.IsErrorType()) { return type; } candidateTypes.Add(type); } } // Perform best type inference on candidate types. var builder = ArrayBuilder<TypeSymbol>.GetInstance(candidateTypes.Count); builder.AddRange(candidateTypes); var result = GetBestType(builder, conversions, ref useSiteInfo); builder.Free(); return (result as FunctionTypeSymbol)?.GetInternalDelegateType() ?? result; } /// <remarks> /// This method implements best type inference for the conditional operator ?:. /// NOTE: If either expression is an error type, we return error type as the inference result. /// </remarks> public static TypeSymbol? InferBestTypeForConditionalOperator( BoundExpression expr1, BoundExpression expr2, ConversionsBase conversions, out bool hadMultipleCandidates, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: The second and third operands, x and y, of the ?: operator control the type of the conditional expression. // SPEC: • If x has type X and y has type Y then // SPEC: o If an implicit conversion (§6.1) exists from X to Y, but not from Y to X, then Y is the type of the conditional expression. // SPEC: o If an implicit conversion (§6.1) exists from Y to X, but not from X to Y, then X is the type of the conditional expression. // SPEC: o Otherwise, no expression type can be determined, and a compile-time error occurs. // SPEC: • If only one of x and y has a type, and both x and y, are implicitly convertible to that type, then that is the type of the conditional expression. // SPEC: • Otherwise, no expression type can be determined, and a compile-time error occurs. // A type is a candidate if all expressions are convertible to that type. ArrayBuilder<TypeSymbol> candidateTypes = ArrayBuilder<TypeSymbol>.GetInstance(); try { var conversionsWithoutNullability = conversions.WithNullability(false); TypeSymbol? type1 = expr1.Type; if (type1 is { }) { if (type1.IsErrorType()) { hadMultipleCandidates = false; return type1; } if (conversionsWithoutNullability.ClassifyImplicitConversionFromExpression(expr2, type1, ref useSiteInfo).Exists) { candidateTypes.Add(type1); } } TypeSymbol? type2 = expr2.Type; if (type2 is { }) { if (type2.IsErrorType()) { hadMultipleCandidates = false; return type2; } if (conversionsWithoutNullability.ClassifyImplicitConversionFromExpression(expr1, type2, ref useSiteInfo).Exists) { candidateTypes.Add(type2); } } hadMultipleCandidates = candidateTypes.Count > 1; return GetBestType(candidateTypes, conversions, ref useSiteInfo); } finally { candidateTypes.Free(); } } internal static TypeSymbol? GetBestType( ArrayBuilder<TypeSymbol> types, ConversionsBase conversions, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // This code assumes that the types in the list are unique. // This code answers the famous Mike Montwill interview question: Can you find the // unique best member of a set in O(n) time if the pairwise betterness algorithm // might be intransitive? // Short-circuit some common cases. switch (types.Count) { case 0: return null; case 1: return types[0]; } TypeSymbol? best = null; int bestIndex = -1; for (int i = 0; i < types.Count; i++) { TypeSymbol type = types[i]; if (best is null) { best = type; bestIndex = i; } else { var better = Better(best, type, conversions, ref useSiteInfo); if (better is null) { best = null; } else { best = better; bestIndex = i; } } } if (best is null) { return null; } // We have actually only determined that every type *after* best was worse. Now check // that every type *before* best was also worse. for (int i = 0; i < bestIndex; i++) { TypeSymbol type = types[i]; TypeSymbol? better = Better(best, type, conversions, ref useSiteInfo); if (!best.Equals(better, TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)) { return null; } } return best; } /// <summary> /// Returns the better type amongst the two, with some possible modifications (dynamic/object or tuple names). /// </summary> private static TypeSymbol? Better( TypeSymbol type1, TypeSymbol? type2, ConversionsBase conversions, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // Anything is better than an error sym. if (type1.IsErrorType()) { return type2; } if (type2 is null || type2.IsErrorType()) { return type1; } // Prefer types other than FunctionTypeSymbol. if (type1 is FunctionTypeSymbol) { if (!(type2 is FunctionTypeSymbol)) { return type2; } } else if (type2 is FunctionTypeSymbol) { return type1; } var conversionsWithoutNullability = conversions.WithNullability(false); var t1tot2 = conversionsWithoutNullability.ClassifyImplicitConversionFromType(type1, type2, ref useSiteInfo).Exists; var t2tot1 = conversionsWithoutNullability.ClassifyImplicitConversionFromType(type2, type1, ref useSiteInfo).Exists; if (t1tot2 && t2tot1) { if (type1.Equals(type2, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)) { return type1.MergeEquivalentTypes(type2, VarianceKind.Out); } return null; } if (t1tot2) { return type2; } if (t2tot1) { return type1; } return null; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.CSharp { internal static class BestTypeInferrer { public static NullableAnnotation GetNullableAnnotation(ArrayBuilder<TypeWithAnnotations> types) { #if DEBUG var example = types.FirstOrDefault(t => t.HasType); #endif var result = NullableAnnotation.NotAnnotated; foreach (var type in types) { #if DEBUG Debug.Assert(!type.HasType || type.Equals(example, TypeCompareKind.AllIgnoreOptions)); #endif // This uses the covariant merging rules. result = result.Join(type.NullableAnnotation); } return result; } public static NullableFlowState GetNullableState(ArrayBuilder<TypeWithState> types) { NullableFlowState result = NullableFlowState.NotNull; foreach (var type in types) { result = result.Join(type.State); } return result; } /// <remarks> /// This method finds the best common type of a set of expressions as per section 7.5.2.14 of the specification. /// NOTE: If some or all of the expressions have error types, we return error type as the inference result. /// </remarks> public static TypeSymbol? InferBestType( ImmutableArray<BoundExpression> exprs, ConversionsBase conversions, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: 7.5.2.14 Finding the best common type of a set of expressions // SPEC: In some cases, a common type needs to be inferred for a set of expressions. In particular, the element types of implicitly typed arrays and // SPEC: the return types of anonymous functions with block bodies are found in this way. // SPEC: Intuitively, given a set of expressions E1…Em this inference should be equivalent to calling a method: // SPEC: T M<X>(X x1 … X xm) // SPEC: with the Ei as arguments. // SPEC: More precisely, the inference starts out with an unfixed type variable X. Output type inferences are then made from each Ei to X. // SPEC: Finally, X is fixed and, if successful, the resulting type S is the resulting best common type for the expressions. // SPEC: If no such S exists, the expressions have no best common type. // All non-null types are candidates for best type inference. IEqualityComparer<TypeSymbol> comparer = conversions.IncludeNullability ? Symbols.SymbolEqualityComparer.ConsiderEverything : Symbols.SymbolEqualityComparer.IgnoringNullable; HashSet<TypeSymbol> candidateTypes = new HashSet<TypeSymbol>(comparer); foreach (BoundExpression expr in exprs) { TypeSymbol? type = expr.GetTypeOrFunctionType(); if (type is { }) { if (type.IsErrorType()) { return type; } candidateTypes.Add(type); } } // Perform best type inference on candidate types. var builder = ArrayBuilder<TypeSymbol>.GetInstance(candidateTypes.Count); builder.AddRange(candidateTypes); var result = GetBestType(builder, conversions, ref useSiteInfo); builder.Free(); return (result as FunctionTypeSymbol)?.GetInternalDelegateType() ?? result; } /// <remarks> /// This method implements best type inference for the conditional operator ?:. /// NOTE: If either expression is an error type, we return error type as the inference result. /// </remarks> public static TypeSymbol? InferBestTypeForConditionalOperator( BoundExpression expr1, BoundExpression expr2, ConversionsBase conversions, out bool hadMultipleCandidates, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: The second and third operands, x and y, of the ?: operator control the type of the conditional expression. // SPEC: • If x has type X and y has type Y then // SPEC: o If an implicit conversion (§6.1) exists from X to Y, but not from Y to X, then Y is the type of the conditional expression. // SPEC: o If an implicit conversion (§6.1) exists from Y to X, but not from X to Y, then X is the type of the conditional expression. // SPEC: o Otherwise, no expression type can be determined, and a compile-time error occurs. // SPEC: • If only one of x and y has a type, and both x and y, are implicitly convertible to that type, then that is the type of the conditional expression. // SPEC: • Otherwise, no expression type can be determined, and a compile-time error occurs. // A type is a candidate if all expressions are convertible to that type. ArrayBuilder<TypeSymbol> candidateTypes = ArrayBuilder<TypeSymbol>.GetInstance(); try { var conversionsWithoutNullability = conversions.WithNullability(false); TypeSymbol? type1 = expr1.Type; if (type1 is { }) { if (type1.IsErrorType()) { hadMultipleCandidates = false; return type1; } if (conversionsWithoutNullability.ClassifyImplicitConversionFromExpression(expr2, type1, ref useSiteInfo).Exists) { candidateTypes.Add(type1); } } TypeSymbol? type2 = expr2.Type; if (type2 is { }) { if (type2.IsErrorType()) { hadMultipleCandidates = false; return type2; } if (conversionsWithoutNullability.ClassifyImplicitConversionFromExpression(expr1, type2, ref useSiteInfo).Exists) { candidateTypes.Add(type2); } } hadMultipleCandidates = candidateTypes.Count > 1; return GetBestType(candidateTypes, conversions, ref useSiteInfo); } finally { candidateTypes.Free(); } } internal static TypeSymbol? GetBestType( ArrayBuilder<TypeSymbol> types, ConversionsBase conversions, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // This code assumes that the types in the list are unique. // This code answers the famous Mike Montwill interview question: Can you find the // unique best member of a set in O(n) time if the pairwise betterness algorithm // might be intransitive? // Short-circuit some common cases. switch (types.Count) { case 0: return null; case 1: return types[0]; } TypeSymbol? best = null; int bestIndex = -1; for (int i = 0; i < types.Count; i++) { TypeSymbol type = types[i]; if (best is null) { best = type; bestIndex = i; } else { var better = Better(best, type, conversions, ref useSiteInfo); if (better is null) { best = null; } else { best = better; bestIndex = i; } } } if (best is null) { return null; } // We have actually only determined that every type *after* best was worse. Now check // that every type *before* best was also worse. for (int i = 0; i < bestIndex; i++) { TypeSymbol type = types[i]; TypeSymbol? better = Better(best, type, conversions, ref useSiteInfo); if (!best.Equals(better, TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)) { return null; } } return best; } /// <summary> /// Returns the better type amongst the two, with some possible modifications (dynamic/object or tuple names). /// </summary> private static TypeSymbol? Better( TypeSymbol type1, TypeSymbol? type2, ConversionsBase conversions, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // Anything is better than an error sym. if (type1.IsErrorType()) { return type2; } if (type2 is null || type2.IsErrorType()) { return type1; } // Prefer types other than FunctionTypeSymbol. if (type1 is FunctionTypeSymbol) { if (!(type2 is FunctionTypeSymbol)) { return type2; } } else if (type2 is FunctionTypeSymbol) { return type1; } var conversionsWithoutNullability = conversions.WithNullability(false); var t1tot2 = conversionsWithoutNullability.ClassifyImplicitConversionFromTypeWhenNeitherOrBothFunctionTypes(type1, type2, ref useSiteInfo).Exists; var t2tot1 = conversionsWithoutNullability.ClassifyImplicitConversionFromTypeWhenNeitherOrBothFunctionTypes(type2, type1, ref useSiteInfo).Exists; if (t1tot2 && t2tot1) { if (type1.Equals(type2, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)) { return type1.MergeEquivalentTypes(type2, VarianceKind.Out); } return null; } if (t1tot2) { return type2; } if (t2tot1) { return type1; } return null; } } }
1
dotnet/roslyn
56,416
Do not include function type conversions in user-defined conversions
Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
cston
"2021-09-15T18:16:38Z"
"2021-09-24T23:24:46Z"
bb99d0bc89bde01650d2a694d720d600dd952dcb
3913f352cf066fa485869d866e4753fa721cbe93
Do not include function type conversions in user-defined conversions. Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
./src/Compilers/CSharp/Portable/Binder/Semantics/Conversions/ConversionsBase.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal abstract partial class ConversionsBase { private const int MaximumRecursionDepth = 50; protected readonly AssemblySymbol corLibrary; protected readonly int currentRecursionDepth; internal readonly bool IncludeNullability; /// <summary> /// An optional clone of this instance with distinct IncludeNullability. /// Used to avoid unnecessary allocations when calling WithNullability() repeatedly. /// </summary> private ConversionsBase _lazyOtherNullability; protected ConversionsBase(AssemblySymbol corLibrary, int currentRecursionDepth, bool includeNullability, ConversionsBase otherNullabilityOpt) { Debug.Assert((object)corLibrary != null); Debug.Assert(otherNullabilityOpt == null || includeNullability != otherNullabilityOpt.IncludeNullability); Debug.Assert(otherNullabilityOpt == null || currentRecursionDepth == otherNullabilityOpt.currentRecursionDepth); this.corLibrary = corLibrary; this.currentRecursionDepth = currentRecursionDepth; IncludeNullability = includeNullability; _lazyOtherNullability = otherNullabilityOpt; } /// <summary> /// Returns this instance if includeNullability is correct, and returns a /// cached clone of this instance with distinct IncludeNullability otherwise. /// </summary> internal ConversionsBase WithNullability(bool includeNullability) { if (IncludeNullability == includeNullability) { return this; } if (_lazyOtherNullability == null) { Interlocked.CompareExchange(ref _lazyOtherNullability, WithNullabilityCore(includeNullability), null); } Debug.Assert(_lazyOtherNullability.IncludeNullability == includeNullability); Debug.Assert(_lazyOtherNullability._lazyOtherNullability == this); return _lazyOtherNullability; } protected abstract ConversionsBase WithNullabilityCore(bool includeNullability); public abstract Conversion GetMethodGroupDelegateConversion(BoundMethodGroup source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo); public abstract Conversion GetMethodGroupFunctionPointerConversion(BoundMethodGroup source, FunctionPointerTypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo); public abstract Conversion GetStackAllocConversion(BoundStackAllocArrayCreation sourceExpression, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo); protected abstract ConversionsBase CreateInstance(int currentRecursionDepth); protected abstract Conversion GetInterpolatedStringConversion(BoundExpression source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo); internal AssemblySymbol CorLibrary { get { return corLibrary; } } /// <summary> /// Determines if the source expression is convertible to the destination type via /// any built-in or user-defined implicit conversion. /// </summary> public Conversion ClassifyImplicitConversionFromExpression(BoundExpression sourceExpression, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(sourceExpression != null); Debug.Assert((object)destination != null); var sourceType = sourceExpression.GetTypeOrFunctionType(); //PERF: identity conversion is by far the most common implicit conversion, check for that first if ((object)sourceType != null && HasIdentityConversionInternal(sourceType, destination)) { return Conversion.Identity; } Conversion conversion = ClassifyImplicitBuiltInConversionFromExpression(sourceExpression, sourceType, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } if ((object)sourceType != null) { // Try using the short-circuit "fast-conversion" path. Conversion fastConversion = FastClassifyConversion(sourceType, destination); if (fastConversion.Exists) { if (fastConversion.IsImplicit) { return fastConversion; } } else { conversion = ClassifyImplicitBuiltInConversionSlow(sourceType, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } } } conversion = GetImplicitUserDefinedConversion(sourceExpression, sourceType, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } // The switch expression conversion is "lowest priority", so that if there is a conversion from the expression's // type it will be preferred over the switch expression conversion. Technically, we would want the language // specification to say that the switch expression conversion only "exists" if there is no implicit conversion // from the type, and we accomplish that by making it lowest priority. The same is true for the conditional // expression conversion. conversion = GetSwitchExpressionConversion(sourceExpression, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } return GetConditionalExpressionConversion(sourceExpression, destination, ref useSiteInfo); } /// <summary> /// Determines if the source type is convertible to the destination type via /// any built-in or user-defined implicit conversion. /// </summary> public Conversion ClassifyImplicitConversionFromType(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); //PERF: identity conversions are very common, check for that first. if (HasIdentityConversionInternal(source, destination)) { return Conversion.Identity; } // Try using the short-circuit "fast-conversion" path. Conversion fastConversion = FastClassifyConversion(source, destination); if (fastConversion.Exists) { return fastConversion.IsImplicit ? fastConversion : Conversion.NoConversion; } else { Conversion conversion = ClassifyImplicitBuiltInConversionSlow(source, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } } return GetImplicitUserDefinedConversion(null, source, destination, ref useSiteInfo); } /// <summary> /// Determines if the source expression of given type is convertible to the destination type via /// any built-in or user-defined conversion. /// /// This helper is used in rare cases involving synthesized expressions where we know the type of an expression, but do not have the actual expression. /// The reason for this helper (as opposed to ClassifyConversionFromType) is that conversions from expressions could be different /// from conversions from type. For example expressions of dynamic type are implicitly convertable to any type, while dynamic type itself is not. /// </summary> public Conversion ClassifyConversionFromExpressionType(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // since we are converting from expression, we may have implicit dynamic conversion if (HasImplicitDynamicConversionFromExpression(source, destination)) { return Conversion.ImplicitDynamic; } return ClassifyConversionFromType(source, destination, ref useSiteInfo); } private static bool TryGetVoidConversion(TypeSymbol source, TypeSymbol destination, out Conversion conversion) { var sourceIsVoid = source?.SpecialType == SpecialType.System_Void; var destIsVoid = destination.SpecialType == SpecialType.System_Void; // 'void' is not supposed to be able to convert to or from anything, but in practice, // a lot of code depends on checking whether an expression of type 'void' is convertible to 'void'. // (e.g. for an expression lambda which returns void). // Therefore we allow an identity conversion between 'void' and 'void'. if (sourceIsVoid && destIsVoid) { conversion = Conversion.Identity; return true; } // If exactly one of source or destination is of type 'void' then no conversion may exist. if (sourceIsVoid || destIsVoid) { conversion = Conversion.NoConversion; return true; } conversion = default; return false; } /// <summary> /// Determines if the source expression is convertible to the destination type via /// any conversion: implicit, explicit, user-defined or built-in. /// </summary> /// <remarks> /// It is rare but possible for a source expression to be convertible to a destination type /// by both an implicit user-defined conversion and a built-in explicit conversion. /// In that circumstance, this method classifies the conversion as the implicit conversion or explicit depending on "forCast" /// </remarks> public Conversion ClassifyConversionFromExpression(BoundExpression sourceExpression, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool forCast = false) { Debug.Assert(sourceExpression != null); Debug.Assert((object)destination != null); if (TryGetVoidConversion(sourceExpression.Type, destination, out var conversion)) { return conversion; } if (forCast) { return ClassifyConversionFromExpressionForCast(sourceExpression, destination, ref useSiteInfo); } var result = ClassifyImplicitConversionFromExpression(sourceExpression, destination, ref useSiteInfo); if (result.Exists) { return result; } return ClassifyExplicitOnlyConversionFromExpression(sourceExpression, destination, ref useSiteInfo, forCast: false); } /// <summary> /// Determines if the source type is convertible to the destination type via /// any conversion: implicit, explicit, user-defined or built-in. /// </summary> /// <remarks> /// It is rare but possible for a source type to be convertible to a destination type /// by both an implicit user-defined conversion and a built-in explicit conversion. /// In that circumstance, this method classifies the conversion as the implicit conversion or explicit depending on "forCast" /// </remarks> public Conversion ClassifyConversionFromType(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool forCast = false) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (TryGetVoidConversion(source, destination, out var voidConversion)) { return voidConversion; } if (forCast) { return ClassifyConversionFromTypeForCast(source, destination, ref useSiteInfo); } // Try using the short-circuit "fast-conversion" path. Conversion fastConversion = FastClassifyConversion(source, destination); if (fastConversion.Exists) { return fastConversion; } else { Conversion conversion1 = ClassifyImplicitBuiltInConversionSlow(source, destination, ref useSiteInfo); if (conversion1.Exists) { return conversion1; } } Conversion conversion = GetImplicitUserDefinedConversion(null, source, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } conversion = ClassifyExplicitBuiltInOnlyConversion(source, destination, ref useSiteInfo, forCast: false); if (conversion.Exists) { return conversion; } return GetExplicitUserDefinedConversion(null, source, destination, ref useSiteInfo); } /// <summary> /// Determines if the source expression is convertible to the destination type via /// any conversion: implicit, explicit, user-defined or built-in. /// </summary> /// <remarks> /// It is rare but possible for a source expression to be convertible to a destination type /// by both an implicit user-defined conversion and a built-in explicit conversion. /// In that circumstance, this method classifies the conversion as the built-in conversion. /// /// An implicit conversion exists from an expression of a dynamic type to any type. /// An explicit conversion exists from a dynamic type to any type. /// When casting we prefer the explicit conversion. /// </remarks> private Conversion ClassifyConversionFromExpressionForCast(BoundExpression source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source != null); Debug.Assert((object)destination != null); Conversion implicitConversion = ClassifyImplicitConversionFromExpression(source, destination, ref useSiteInfo); if (implicitConversion.Exists && !ExplicitConversionMayDifferFromImplicit(implicitConversion)) { return implicitConversion; } Conversion explicitConversion = ClassifyExplicitOnlyConversionFromExpression(source, destination, ref useSiteInfo, forCast: true); if (explicitConversion.Exists) { return explicitConversion; } // It is possible for a user-defined conversion to be unambiguous when considered as // an implicit conversion and ambiguous when considered as an explicit conversion. // The native compiler does not check to see if a cast could be successfully bound as // an unambiguous user-defined implicit conversion; it goes right to the ambiguous // user-defined explicit conversion and produces an error. This means that in // C# 5 it is possible to have: // // Y y = new Y(); // Z z1 = y; // // succeed but // // Z z2 = (Z)y; // // fail. // // However, there is another interesting wrinkle. It is possible for both // an implicit user-defined conversion and an explicit user-defined conversion // to exist and be unambiguous. For example, if there is an implicit conversion // double-->C and an explicit conversion from int-->C, and the user casts a short // to C, then both the implicit and explicit conversions are applicable and // unambiguous. The native compiler in this case prefers the explicit conversion, // and for backwards compatibility, we match it. return implicitConversion; } /// <summary> /// Determines if the source type is convertible to the destination type via /// any conversion: implicit, explicit, user-defined or built-in. /// </summary> /// <remarks> /// It is rare but possible for a source type to be convertible to a destination type /// by both an implicit user-defined conversion and a built-in explicit conversion. /// In that circumstance, this method classifies the conversion as the built-in conversion. /// </remarks> private Conversion ClassifyConversionFromTypeForCast(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // Try using the short-circuit "fast-conversion" path. Conversion fastConversion = FastClassifyConversion(source, destination); if (fastConversion.Exists) { return fastConversion; } Conversion implicitBuiltInConversion = ClassifyImplicitBuiltInConversionSlow(source, destination, ref useSiteInfo); if (implicitBuiltInConversion.Exists && !ExplicitConversionMayDifferFromImplicit(implicitBuiltInConversion)) { return implicitBuiltInConversion; } Conversion explicitBuiltInConversion = ClassifyExplicitBuiltInOnlyConversion(source, destination, ref useSiteInfo, forCast: true); if (explicitBuiltInConversion.Exists) { return explicitBuiltInConversion; } if (implicitBuiltInConversion.Exists) { return implicitBuiltInConversion; } // It is possible for a user-defined conversion to be unambiguous when considered as // an implicit conversion and ambiguous when considered as an explicit conversion. // The native compiler does not check to see if a cast could be successfully bound as // an unambiguous user-defined implicit conversion; it goes right to the ambiguous // user-defined explicit conversion and produces an error. This means that in // C# 5 it is possible to have: // // Y y = new Y(); // Z z1 = y; // // succeed but // // Z z2 = (Z)y; // // fail. var conversion = GetExplicitUserDefinedConversion(null, source, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } return GetImplicitUserDefinedConversion(null, source, destination, ref useSiteInfo); } /// <summary> /// Attempt a quick classification of builtin conversions. As result of "no conversion" /// means that there is no built-in conversion, though there still may be a user-defined /// conversion if compiling against a custom mscorlib. /// </summary> public static Conversion FastClassifyConversion(TypeSymbol source, TypeSymbol target) { ConversionKind convKind = ConversionEasyOut.ClassifyConversion(source, target); if (convKind != ConversionKind.ImplicitNullable && convKind != ConversionKind.ExplicitNullable) { return Conversion.GetTrivialConversion(convKind); } return Conversion.MakeNullableConversion(convKind, FastClassifyConversion(source.StrippedType(), target.StrippedType())); } public Conversion ClassifyBuiltInConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // Try using the short-circuit "fast-conversion" path. Conversion fastConversion = FastClassifyConversion(source, destination); if (fastConversion.Exists) { return fastConversion; } else { Conversion conversion = ClassifyImplicitBuiltInConversionSlow(source, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } } return ClassifyExplicitBuiltInOnlyConversion(source, destination, ref useSiteInfo, forCast: false); } /// <summary> /// Determines if the source type is convertible to the destination type via /// any standard implicit or standard explicit conversion. /// </summary> /// <remarks> /// Not all built-in explicit conversions are standard explicit conversions. /// </remarks> public Conversion ClassifyStandardConversion(BoundExpression sourceExpression, TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(sourceExpression != null || (object)source != null); Debug.Assert((object)destination != null); // Note that the definition of explicit standard conversion does not include all explicit // reference conversions! There is a standard implicit reference conversion from // Action<Object> to Action<Exception>, thanks to contravariance. There is a standard // implicit reference conversion from Action<Object> to Action<String> for the same reason. // Therefore there is an explicit reference conversion from Action<Exception> to // Action<String>; a given Action<Exception> might be an Action<Object>, and hence // convertible to Action<String>. However, this is not a *standard* explicit conversion. The // standard explicit conversions are all the standard implicit conversions and their // opposites. Therefore Action<Object>-->Action<String> and Action<String>-->Action<Object> // are both standard conversions. But Action<String>-->Action<Exception> is not a standard // explicit conversion because neither it nor its opposite is a standard implicit // conversion. // // Similarly, there is no standard explicit conversion from double to decimal, because // there is no standard implicit conversion between the two types. // SPEC: The standard explicit conversions are all standard implicit conversions plus // SPEC: the subset of the explicit conversions for which an opposite standard implicit // SPEC: conversion exists. In other words, if a standard implicit conversion exists from // SPEC: a type A to a type B, then a standard explicit conversion exists from type A to // SPEC: type B and from type B to type A. Conversion conversion = ClassifyStandardImplicitConversion(sourceExpression, source, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } if ((object)source != null) { return DeriveStandardExplicitFromOppositeStandardImplicitConversion(source, destination, ref useSiteInfo); } return Conversion.NoConversion; } private Conversion ClassifyStandardImplicitConversion(BoundExpression sourceExpression, TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(sourceExpression != null || (object)source != null); Debug.Assert(sourceExpression == null || (object)sourceExpression.GetTypeOrFunctionType() == (object)source); Debug.Assert((object)destination != null); // SPEC: The following implicit conversions are classified as standard implicit conversions: // SPEC: Identity conversions // SPEC: Implicit numeric conversions // SPEC: Implicit nullable conversions // SPEC: Implicit reference conversions // SPEC: Boxing conversions // SPEC: Implicit constant expression conversions // SPEC: Implicit conversions involving type parameters // // and in unsafe code: // // SPEC: From any pointer type to void* // // SPEC ERROR: // The specification does not say to take into account the conversion from // the *expression*, only its *type*. But the expression may not have a type // (because it is null, a method group, or a lambda), or the expression might // be convertible to the destination type via a constant numeric conversion. // For example, the native compiler allows "C c = 1;" to work if C is a class which // has an implicit conversion from byte to C, despite the fact that there is // obviously no standard implicit conversion from *int* to *byte*. // Similarly, if a struct S has an implicit conversion from string to S, then // "S s = null;" should be allowed. // // We extend the definition of standard implicit conversions to include // all of the implicit conversions that are allowed based on an expression, // with the exception of the switch expression conversion. Conversion conversion = ClassifyImplicitBuiltInConversionFromExpression(sourceExpression, source, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } if ((object)source != null) { return ClassifyStandardImplicitConversion(source, destination, ref useSiteInfo); } return Conversion.NoConversion; } private Conversion ClassifyStandardImplicitConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (HasIdentityConversionInternal(source, destination)) { return Conversion.Identity; } if (HasImplicitNumericConversion(source, destination)) { return Conversion.ImplicitNumeric; } var nullableConversion = ClassifyImplicitNullableConversion(source, destination, ref useSiteInfo); if (nullableConversion.Exists) { return nullableConversion; } if (source is FunctionTypeSymbol functionType) { return HasImplicitFunctionTypeConversion(functionType, destination, ref useSiteInfo) ? Conversion.FunctionType : Conversion.NoConversion; } if (HasImplicitReferenceConversion(source, destination, ref useSiteInfo)) { return Conversion.ImplicitReference; } if (HasBoxingConversion(source, destination, ref useSiteInfo)) { return Conversion.Boxing; } if (HasImplicitPointerToVoidConversion(source, destination)) { return Conversion.PointerToVoid; } if (HasImplicitPointerConversion(source, destination, ref useSiteInfo)) { return Conversion.ImplicitPointer; } var tupleConversion = ClassifyImplicitTupleConversion(source, destination, ref useSiteInfo); if (tupleConversion.Exists) { return tupleConversion; } return Conversion.NoConversion; } private Conversion ClassifyImplicitBuiltInConversionSlow(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (source.IsVoidType() || destination.IsVoidType()) { return Conversion.NoConversion; } Conversion conversion = ClassifyStandardImplicitConversion(source, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } return Conversion.NoConversion; } private Conversion GetImplicitUserDefinedConversion(BoundExpression sourceExpression, TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var conversionResult = AnalyzeImplicitUserDefinedConversions(sourceExpression, source, destination, ref useSiteInfo); return new Conversion(conversionResult, isImplicit: true); } private Conversion ClassifyExplicitBuiltInOnlyConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool forCast) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (source.IsVoidType() || destination.IsVoidType()) { return Conversion.NoConversion; } // The call to HasExplicitNumericConversion isn't necessary, because it is always tested // already by the "FastConversion" code. Debug.Assert(!HasExplicitNumericConversion(source, destination)); //if (HasExplicitNumericConversion(source, specialTypeSource, destination, specialTypeDest)) //{ // return Conversion.ExplicitNumeric; //} if (HasSpecialIntPtrConversion(source, destination)) { return Conversion.IntPtr; } if (HasExplicitEnumerationConversion(source, destination)) { return Conversion.ExplicitEnumeration; } var nullableConversion = ClassifyExplicitNullableConversion(source, destination, ref useSiteInfo, forCast); if (nullableConversion.Exists) { return nullableConversion; } if (HasExplicitReferenceConversion(source, destination, ref useSiteInfo)) { return (source.Kind == SymbolKind.DynamicType) ? Conversion.ExplicitDynamic : Conversion.ExplicitReference; } if (HasUnboxingConversion(source, destination, ref useSiteInfo)) { return Conversion.Unboxing; } var tupleConversion = ClassifyExplicitTupleConversion(source, destination, ref useSiteInfo, forCast); if (tupleConversion.Exists) { return tupleConversion; } if (HasPointerToPointerConversion(source, destination)) { return Conversion.PointerToPointer; } if (HasPointerToIntegerConversion(source, destination)) { return Conversion.PointerToInteger; } if (HasIntegerToPointerConversion(source, destination)) { return Conversion.IntegerToPointer; } if (HasExplicitDynamicConversion(source, destination)) { return Conversion.ExplicitDynamic; } return Conversion.NoConversion; } private Conversion GetExplicitUserDefinedConversion(BoundExpression sourceExpression, TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { UserDefinedConversionResult conversionResult = AnalyzeExplicitUserDefinedConversions(sourceExpression, source, destination, ref useSiteInfo); return new Conversion(conversionResult, isImplicit: false); } private Conversion DeriveStandardExplicitFromOppositeStandardImplicitConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var oppositeConversion = ClassifyStandardImplicitConversion(destination, source, ref useSiteInfo); Conversion impliedExplicitConversion; switch (oppositeConversion.Kind) { case ConversionKind.Identity: impliedExplicitConversion = Conversion.Identity; break; case ConversionKind.ImplicitNumeric: impliedExplicitConversion = Conversion.ExplicitNumeric; break; case ConversionKind.ImplicitReference: impliedExplicitConversion = Conversion.ExplicitReference; break; case ConversionKind.Boxing: impliedExplicitConversion = Conversion.Unboxing; break; case ConversionKind.NoConversion: impliedExplicitConversion = Conversion.NoConversion; break; case ConversionKind.ImplicitPointerToVoid: impliedExplicitConversion = Conversion.PointerToPointer; break; case ConversionKind.ImplicitTuple: // only implicit tuple conversions are standard conversions, // having implicit conversion in the other direction does not help here. impliedExplicitConversion = Conversion.NoConversion; break; case ConversionKind.ImplicitNullable: var strippedSource = source.StrippedType(); var strippedDestination = destination.StrippedType(); var underlyingConversion = DeriveStandardExplicitFromOppositeStandardImplicitConversion(strippedSource, strippedDestination, ref useSiteInfo); // the opposite underlying conversion may not exist // for example if underlying conversion is implicit tuple impliedExplicitConversion = underlyingConversion.Exists ? Conversion.MakeNullableConversion(ConversionKind.ExplicitNullable, underlyingConversion) : Conversion.NoConversion; break; default: throw ExceptionUtilities.UnexpectedValue(oppositeConversion.Kind); } return impliedExplicitConversion; } #nullable enable /// <summary> /// IsBaseInterface returns true if baseType is on the base interface list of derivedType or /// any base class of derivedType. It may be on the base interface list either directly or /// indirectly. /// * baseType must be an interface. /// * type parameters do not have base interfaces. (They have an "effective interface list".) /// * an interface is not a base of itself. /// * this does not check for variance conversions; if a type inherits from /// IEnumerable&lt;string> then IEnumerable&lt;object> is not a base interface. /// </summary> public bool IsBaseInterface(TypeSymbol baseType, TypeSymbol derivedType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)baseType != null); Debug.Assert((object)derivedType != null); if (!baseType.IsInterfaceType()) { return false; } var d = derivedType as NamedTypeSymbol; if (d is null) { return false; } foreach (var iface in d.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { if (HasIdentityConversionInternal(iface, baseType)) { return true; } } return false; } // IsBaseClass returns true if and only if baseType is a base class of derivedType, period. // // * interfaces do not have base classes. (Structs, enums and classes other than object do.) // * a class is not a base class of itself // * type parameters do not have base classes. (They have "effective base classes".) // * all base classes must be classes // * dynamics are removed; if we have class D : B<dynamic> then B<object> is a // base class of D. However, dynamic is never a base class of anything. public bool IsBaseClass(TypeSymbol derivedType, TypeSymbol baseType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)derivedType != null); Debug.Assert((object)baseType != null); // A base class has got to be a class. The derived type might be a struct, enum, or delegate. if (!baseType.IsClassType()) { return false; } for (TypeSymbol b = derivedType.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); (object)b != null; b = b.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { if (HasIdentityConversionInternal(b, baseType)) { return true; } } return false; } /// <summary> /// returns true when implicit conversion is not necessarily the same as explicit conversion /// </summary> private static bool ExplicitConversionMayDifferFromImplicit(Conversion implicitConversion) { switch (implicitConversion.Kind) { case ConversionKind.ImplicitUserDefined: case ConversionKind.ImplicitDynamic: case ConversionKind.ImplicitTuple: case ConversionKind.ImplicitTupleLiteral: case ConversionKind.ImplicitNullable: case ConversionKind.ConditionalExpression: return true; default: return false; } } #nullable disable private Conversion ClassifyImplicitBuiltInConversionFromExpression(BoundExpression sourceExpression, TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(sourceExpression != null || (object)source != null); Debug.Assert(sourceExpression == null || (object)sourceExpression.GetTypeOrFunctionType() == (object)source); Debug.Assert((object)destination != null); if (HasImplicitDynamicConversionFromExpression(source, destination)) { return Conversion.ImplicitDynamic; } // The following conversions only exist for certain form of expressions, // if we have no expression none if them is applicable. if (sourceExpression == null) { return Conversion.NoConversion; } if (HasImplicitEnumerationConversion(sourceExpression, destination)) { return Conversion.ImplicitEnumeration; } var constantConversion = ClassifyImplicitConstantExpressionConversion(sourceExpression, destination); if (constantConversion.Exists) { return constantConversion; } switch (sourceExpression.Kind) { case BoundKind.Literal: var nullLiteralConversion = ClassifyNullLiteralConversion(sourceExpression, destination); if (nullLiteralConversion.Exists) { return nullLiteralConversion; } break; case BoundKind.DefaultLiteral: return Conversion.DefaultLiteral; case BoundKind.ExpressionWithNullability: { var innerExpression = ((BoundExpressionWithNullability)sourceExpression).Expression; var innerConversion = ClassifyImplicitBuiltInConversionFromExpression(innerExpression, innerExpression.Type, destination, ref useSiteInfo); if (innerConversion.Exists) { return innerConversion; } break; } case BoundKind.TupleLiteral: var tupleConversion = ClassifyImplicitTupleLiteralConversion((BoundTupleLiteral)sourceExpression, destination, ref useSiteInfo); if (tupleConversion.Exists) { return tupleConversion; } break; case BoundKind.UnboundLambda: if (HasAnonymousFunctionConversion(sourceExpression, destination)) { return Conversion.AnonymousFunction; } break; case BoundKind.MethodGroup: Conversion methodGroupConversion = GetMethodGroupDelegateConversion((BoundMethodGroup)sourceExpression, destination, ref useSiteInfo); if (methodGroupConversion.Exists) { return methodGroupConversion; } break; case BoundKind.UnconvertedInterpolatedString: case BoundKind.BinaryOperator when ((BoundBinaryOperator)sourceExpression).IsUnconvertedInterpolatedStringAddition: Conversion interpolatedStringConversion = GetInterpolatedStringConversion(sourceExpression, destination, ref useSiteInfo); if (interpolatedStringConversion.Exists) { return interpolatedStringConversion; } break; case BoundKind.StackAllocArrayCreation: var stackAllocConversion = GetStackAllocConversion((BoundStackAllocArrayCreation)sourceExpression, destination, ref useSiteInfo); if (stackAllocConversion.Exists) { return stackAllocConversion; } break; case BoundKind.UnconvertedAddressOfOperator when destination is FunctionPointerTypeSymbol funcPtrType: var addressOfConversion = GetMethodGroupFunctionPointerConversion(((BoundUnconvertedAddressOfOperator)sourceExpression).Operand, funcPtrType, ref useSiteInfo); if (addressOfConversion.Exists) { return addressOfConversion; } break; case BoundKind.ThrowExpression: return Conversion.ImplicitThrow; case BoundKind.UnconvertedObjectCreationExpression: return Conversion.ObjectCreation; } return Conversion.NoConversion; } private Conversion GetSwitchExpressionConversion(BoundExpression source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { switch (source) { case BoundConvertedSwitchExpression _: // It has already been subjected to a switch expression conversion. return Conversion.NoConversion; case BoundUnconvertedSwitchExpression switchExpression: var innerConversions = ArrayBuilder<Conversion>.GetInstance(switchExpression.SwitchArms.Length); foreach (var arm in switchExpression.SwitchArms) { var nestedConversion = this.ClassifyImplicitConversionFromExpression(arm.Value, destination, ref useSiteInfo); if (!nestedConversion.Exists) { innerConversions.Free(); return Conversion.NoConversion; } innerConversions.Add(nestedConversion); } return Conversion.MakeSwitchExpression(innerConversions.ToImmutableAndFree()); default: return Conversion.NoConversion; } } private Conversion GetConditionalExpressionConversion(BoundExpression source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (!(source is BoundUnconvertedConditionalOperator conditionalOperator)) return Conversion.NoConversion; var trueConversion = this.ClassifyImplicitConversionFromExpression(conditionalOperator.Consequence, destination, ref useSiteInfo); if (!trueConversion.Exists) return Conversion.NoConversion; var falseConversion = this.ClassifyImplicitConversionFromExpression(conditionalOperator.Alternative, destination, ref useSiteInfo); if (!falseConversion.Exists) return Conversion.NoConversion; return Conversion.MakeConditionalExpression(ImmutableArray.Create(trueConversion, falseConversion)); } private static Conversion ClassifyNullLiteralConversion(BoundExpression source, TypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (!source.IsLiteralNull()) { return Conversion.NoConversion; } // SPEC: An implicit conversion exists from the null literal to any nullable type. if (destination.IsNullableType()) { // The spec defines a "null literal conversion" specifically as a conversion from // null to nullable type. return Conversion.NullLiteral; } // SPEC: An implicit conversion exists from the null literal to any reference type. // SPEC: An implicit conversion exists from the null literal to type parameter T, // SPEC: provided T is known to be a reference type. [...] The conversion [is] classified // SPEC: as implicit reference conversion. if (destination.IsReferenceType) { return Conversion.ImplicitReference; } // SPEC: The set of implicit conversions is extended to include... // SPEC: ... from the null literal to any pointer type. if (destination.IsPointerOrFunctionPointer()) { return Conversion.NullToPointer; } return Conversion.NoConversion; } private static Conversion ClassifyImplicitConstantExpressionConversion(BoundExpression source, TypeSymbol destination) { if (HasImplicitConstantExpressionConversion(source, destination)) { return Conversion.ImplicitConstant; } // strip nullable from the destination // // the following should work and it is an ImplicitNullable conversion // int? x = 1; if (destination.Kind == SymbolKind.NamedType) { var nt = (NamedTypeSymbol)destination; if (nt.OriginalDefinition.GetSpecialTypeSafe() == SpecialType.System_Nullable_T && HasImplicitConstantExpressionConversion(source, nt.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].Type)) { return new Conversion(ConversionKind.ImplicitNullable, Conversion.ImplicitConstantUnderlying); } } return Conversion.NoConversion; } private Conversion ClassifyImplicitTupleLiteralConversion(BoundTupleLiteral source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var tupleConversion = GetImplicitTupleLiteralConversion(source, destination, ref useSiteInfo); if (tupleConversion.Exists) { return tupleConversion; } // strip nullable from the destination // // the following should work and it is an ImplicitNullable conversion // (int, double)? x = (1,2); if (destination.Kind == SymbolKind.NamedType) { var nt = (NamedTypeSymbol)destination; if (nt.OriginalDefinition.GetSpecialTypeSafe() == SpecialType.System_Nullable_T) { var underlyingTupleConversion = GetImplicitTupleLiteralConversion(source, nt.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].Type, ref useSiteInfo); if (underlyingTupleConversion.Exists) { return new Conversion(ConversionKind.ImplicitNullable, ImmutableArray.Create(underlyingTupleConversion)); } } } return Conversion.NoConversion; } private Conversion ClassifyExplicitTupleLiteralConversion(BoundTupleLiteral source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool forCast) { var tupleConversion = GetExplicitTupleLiteralConversion(source, destination, ref useSiteInfo, forCast); if (tupleConversion.Exists) { return tupleConversion; } // strip nullable from the destination // // the following should work and it is an ExplicitNullable conversion // var x = ((byte, string)?)(1,null); if (destination.Kind == SymbolKind.NamedType) { var nt = (NamedTypeSymbol)destination; if (nt.OriginalDefinition.GetSpecialTypeSafe() == SpecialType.System_Nullable_T) { var underlyingTupleConversion = GetExplicitTupleLiteralConversion(source, nt.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].Type, ref useSiteInfo, forCast); if (underlyingTupleConversion.Exists) { return new Conversion(ConversionKind.ExplicitNullable, ImmutableArray.Create(underlyingTupleConversion)); } } } return Conversion.NoConversion; } internal static bool HasImplicitConstantExpressionConversion(BoundExpression source, TypeSymbol destination) { var constantValue = source.ConstantValue; if (constantValue == null || (object)source.Type == null) { return false; } // An implicit constant expression conversion permits the following conversions: // A constant-expression of type int can be converted to type sbyte, byte, short, // ushort, uint, or ulong, provided the value of the constant-expression is within the // range of the destination type. var specialSource = source.Type.GetSpecialTypeSafe(); if (specialSource == SpecialType.System_Int32) { //if the constant value could not be computed, be generous and assume the conversion will work int value = constantValue.IsBad ? 0 : constantValue.Int32Value; switch (destination.GetSpecialTypeSafe()) { case SpecialType.System_Byte: return byte.MinValue <= value && value <= byte.MaxValue; case SpecialType.System_SByte: return sbyte.MinValue <= value && value <= sbyte.MaxValue; case SpecialType.System_Int16: return short.MinValue <= value && value <= short.MaxValue; case SpecialType.System_IntPtr when destination.IsNativeIntegerType: return true; case SpecialType.System_UInt32: case SpecialType.System_UIntPtr when destination.IsNativeIntegerType: return uint.MinValue <= value; case SpecialType.System_UInt64: return (int)ulong.MinValue <= value; case SpecialType.System_UInt16: return ushort.MinValue <= value && value <= ushort.MaxValue; default: return false; } } else if (specialSource == SpecialType.System_Int64 && destination.GetSpecialTypeSafe() == SpecialType.System_UInt64 && (constantValue.IsBad || 0 <= constantValue.Int64Value)) { // A constant-expression of type long can be converted to type ulong, provided the // value of the constant-expression is not negative. return true; } return false; } private Conversion ClassifyExplicitOnlyConversionFromExpression(BoundExpression sourceExpression, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool forCast) { Debug.Assert(sourceExpression != null); Debug.Assert((object)destination != null); // NB: need to check for explicit tuple literal conversion before checking for explicit conversion from type // The same literal may have both explicit tuple conversion and explicit tuple literal conversion to the target type. // They are, however, observably different conversions via the order of argument evaluations and element-wise conversions if (sourceExpression.Kind == BoundKind.TupleLiteral) { Conversion tupleConversion = ClassifyExplicitTupleLiteralConversion((BoundTupleLiteral)sourceExpression, destination, ref useSiteInfo, forCast); if (tupleConversion.Exists) { return tupleConversion; } } var sourceType = sourceExpression.GetTypeOrFunctionType(); if ((object)sourceType != null) { // Try using the short-circuit "fast-conversion" path. Conversion fastConversion = FastClassifyConversion(sourceType, destination); if (fastConversion.Exists) { return fastConversion; } else { var conversion = ClassifyExplicitBuiltInOnlyConversion(sourceType, destination, ref useSiteInfo, forCast); if (conversion.Exists) { return conversion; } } } return GetExplicitUserDefinedConversion(sourceExpression, sourceType, destination, ref useSiteInfo); } #nullable enable private static bool HasImplicitEnumerationConversion(BoundExpression source, TypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // SPEC: An implicit enumeration conversion permits the decimal-integer-literal 0 to be converted to any enum-type // SPEC: and to any nullable-type whose underlying type is an enum-type. // // For historical reasons we actually allow a conversion from any *numeric constant // zero* to be converted to any enum type, not just the literal integer zero. bool validType = destination.IsEnumType() || destination.IsNullableType() && destination.GetNullableUnderlyingType().IsEnumType(); if (!validType) { return false; } var sourceConstantValue = source.ConstantValue; return sourceConstantValue != null && source.Type is object && IsNumericType(source.Type) && IsConstantNumericZero(sourceConstantValue); } private static LambdaConversionResult IsAnonymousFunctionCompatibleWithDelegate(UnboundLambda anonymousFunction, TypeSymbol type, bool isTargetExpressionTree) { Debug.Assert((object)anonymousFunction != null); Debug.Assert((object)type != null); // SPEC: An anonymous-method-expression or lambda-expression is classified as an anonymous function. // SPEC: The expression does not have a type but can be implicitly converted to a compatible delegate // SPEC: type or expression tree type. Specifically, a delegate type D is compatible with an // SPEC: anonymous function F provided: var delegateType = (NamedTypeSymbol)type; var invokeMethod = delegateType.DelegateInvokeMethod; if (invokeMethod is null || invokeMethod.HasUseSiteError) { return LambdaConversionResult.BadTargetType; } if (anonymousFunction.HasExplicitReturnType(out var refKind, out var returnType)) { if (invokeMethod.RefKind != refKind || !invokeMethod.ReturnType.Equals(returnType.Type, TypeCompareKind.AllIgnoreOptions)) { return LambdaConversionResult.MismatchedReturnType; } } var delegateParameters = invokeMethod.Parameters; // SPEC: If F contains an anonymous-function-signature, then D and F have the same number of parameters. // SPEC: If F does not contain an anonymous-function-signature, then D may have zero or more parameters // SPEC: of any type, as long as no parameter of D has the out parameter modifier. if (anonymousFunction.HasSignature) { if (anonymousFunction.ParameterCount != invokeMethod.ParameterCount) { return LambdaConversionResult.BadParameterCount; } // SPEC: If F has an explicitly typed parameter list, each parameter in D has the same type // SPEC: and modifiers as the corresponding parameter in F. // SPEC: If F has an implicitly typed parameter list, D has no ref or out parameters. if (anonymousFunction.HasExplicitlyTypedParameterList) { for (int p = 0; p < delegateParameters.Length; ++p) { if (delegateParameters[p].RefKind != anonymousFunction.RefKind(p) || !delegateParameters[p].Type.Equals(anonymousFunction.ParameterType(p), TypeCompareKind.AllIgnoreOptions)) { return LambdaConversionResult.MismatchedParameterType; } } } else { for (int p = 0; p < delegateParameters.Length; ++p) { if (delegateParameters[p].RefKind != RefKind.None) { return LambdaConversionResult.RefInImplicitlyTypedLambda; } } // In C# it is not possible to make a delegate type // such that one of its parameter types is a static type. But static types are // in metadata just sealed abstract types; there is nothing stopping someone in // another language from creating a delegate with a static type for a parameter, // though the only argument you could pass for that parameter is null. // // In the native compiler we forbid conversion of an anonymous function that has // an implicitly-typed parameter list to a delegate type that has a static type // for a formal parameter type. However, we do *not* forbid it for an explicitly- // typed lambda (because we already require that the explicitly typed parameter not // be static) and we do not forbid it for an anonymous method with the entire // parameter list missing (because the body cannot possibly have a parameter that // is of static type, even though this means that we will be generating a hidden // method with a parameter of static type.) // // We also allow more exotic situations to work in the native compiler. For example, // though it is not possible to convert x=>{} to Action<GC>, it is possible to convert // it to Action<List<GC>> should there be a language that allows you to construct // a variable of that type. // // We might consider beefing up this rule to disallow a conversion of *any* anonymous // function to *any* delegate that has a static type *anywhere* in the parameter list. for (int p = 0; p < delegateParameters.Length; ++p) { if (delegateParameters[p].TypeWithAnnotations.IsStatic) { return LambdaConversionResult.StaticTypeInImplicitlyTypedLambda; } } } } else { for (int p = 0; p < delegateParameters.Length; ++p) { if (delegateParameters[p].RefKind == RefKind.Out) { return LambdaConversionResult.MissingSignatureWithOutParameter; } } } // Ensure the body can be converted to that delegate type var bound = anonymousFunction.Bind(delegateType, isTargetExpressionTree); if (ErrorFacts.PreventsSuccessfulDelegateConversion(bound.Diagnostics.Diagnostics)) { return LambdaConversionResult.BindingFailed; } return LambdaConversionResult.Success; } private static LambdaConversionResult IsAnonymousFunctionCompatibleWithExpressionTree(UnboundLambda anonymousFunction, NamedTypeSymbol type) { Debug.Assert((object)anonymousFunction != null); Debug.Assert((object)type != null); Debug.Assert(type.IsExpressionTree()); // SPEC OMISSION: // // The C# 3 spec said that anonymous methods and statement lambdas are *convertible* to expression tree // types if the anonymous method/statement lambda is convertible to its delegate type; however, actually // *using* such a conversion is an error. However, that is not what we implemented. In C# 3 we implemented // that an anonymous method is *not convertible* to an expression tree type, period. (Statement lambdas // used the rule described in the spec.) // // This appears to be a spec omission; the intention is to make old-style anonymous methods not // convertible to expression trees. var delegateType = type.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].Type; if (!delegateType.IsDelegateType()) { return LambdaConversionResult.ExpressionTreeMustHaveDelegateTypeArgument; } if (anonymousFunction.Syntax.Kind() == SyntaxKind.AnonymousMethodExpression) { return LambdaConversionResult.ExpressionTreeFromAnonymousMethod; } return IsAnonymousFunctionCompatibleWithDelegate(anonymousFunction, delegateType, isTargetExpressionTree: true); } internal bool IsAssignableFromMulticastDelegate(TypeSymbol type, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var multicastDelegateType = corLibrary.GetSpecialType(SpecialType.System_MulticastDelegate); multicastDelegateType.AddUseSiteInfo(ref useSiteInfo); return ClassifyImplicitConversionFromType(multicastDelegateType, type, ref useSiteInfo).Exists; } public static LambdaConversionResult IsAnonymousFunctionCompatibleWithType(UnboundLambda anonymousFunction, TypeSymbol type) { Debug.Assert((object)anonymousFunction != null); Debug.Assert((object)type != null); if (type.IsDelegateType()) { return IsAnonymousFunctionCompatibleWithDelegate(anonymousFunction, type, isTargetExpressionTree: false); } else if (type.IsExpressionTree()) { return IsAnonymousFunctionCompatibleWithExpressionTree(anonymousFunction, (NamedTypeSymbol)type); } return LambdaConversionResult.BadTargetType; } private static bool HasAnonymousFunctionConversion(BoundExpression source, TypeSymbol destination) { Debug.Assert(source != null); Debug.Assert((object)destination != null); if (source.Kind != BoundKind.UnboundLambda) { return false; } return IsAnonymousFunctionCompatibleWithType((UnboundLambda)source, destination) == LambdaConversionResult.Success; } #nullable disable internal Conversion ClassifyImplicitUserDefinedConversionForV6SwitchGoverningType(TypeSymbol sourceType, out TypeSymbol switchGoverningType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: The governing type of a switch statement is established by the switch expression. // SPEC: 1) If the type of the switch expression is sbyte, byte, short, ushort, int, uint, // SPEC: long, ulong, bool, char, string, or an enum-type, or if it is the nullable type // SPEC: corresponding to one of these types, then that is the governing type of the switch statement. // SPEC: 2) Otherwise, exactly one user-defined implicit conversion (§6.4) must exist from the // SPEC: type of the switch expression to one of the following possible governing types: // SPEC: sbyte, byte, short, ushort, int, uint, long, ulong, char, string, or, a nullable type // SPEC: corresponding to one of those types // NOTE: We should be called only if (1) is false for source type. Debug.Assert((object)sourceType != null); Debug.Assert(!sourceType.IsValidV6SwitchGoverningType()); UserDefinedConversionResult result = AnalyzeImplicitUserDefinedConversionForV6SwitchGoverningType(sourceType, ref useSiteInfo); if (result.Kind == UserDefinedConversionResultKind.Valid) { UserDefinedConversionAnalysis analysis = result.Results[result.Best]; switchGoverningType = analysis.ToType; Debug.Assert(switchGoverningType.IsValidV6SwitchGoverningType(isTargetTypeOfUserDefinedOp: true)); } else { switchGoverningType = null; } return new Conversion(result, isImplicit: true); } internal Conversion GetCallerLineNumberConversion(TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var greenNode = new Syntax.InternalSyntax.LiteralExpressionSyntax(SyntaxKind.NumericLiteralExpression, new Syntax.InternalSyntax.SyntaxToken(SyntaxKind.NumericLiteralToken)); var syntaxNode = new LiteralExpressionSyntax(greenNode, null, 0); TypeSymbol expectedAttributeType = corLibrary.GetSpecialType(SpecialType.System_Int32); BoundLiteral intMaxValueLiteral = new BoundLiteral(syntaxNode, ConstantValue.Create(int.MaxValue), expectedAttributeType); return ClassifyStandardImplicitConversion(intMaxValueLiteral, expectedAttributeType, destination, ref useSiteInfo); } internal bool HasCallerLineNumberConversion(TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { return GetCallerLineNumberConversion(destination, ref useSiteInfo).Exists; } internal bool HasCallerInfoStringConversion(TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { TypeSymbol expectedAttributeType = corLibrary.GetSpecialType(SpecialType.System_String); Conversion conversion = ClassifyStandardImplicitConversion(expectedAttributeType, destination, ref useSiteInfo); return conversion.Exists; } public static bool HasIdentityConversion(TypeSymbol type1, TypeSymbol type2) { return HasIdentityConversionInternal(type1, type2, includeNullability: false); } private static bool HasIdentityConversionInternal(TypeSymbol type1, TypeSymbol type2, bool includeNullability) { // Spec (6.1.1): // An identity conversion converts from any type to the same type. This conversion exists // such that an entity that already has a required type can be said to be convertible to // that type. // // Because object and dynamic are considered equivalent there is an identity conversion // between object and dynamic, and between constructed types that are the same when replacing // all occurrences of dynamic with object. Debug.Assert((object)type1 != null); Debug.Assert((object)type2 != null); // Note, when we are paying attention to nullability, we ignore oblivious mismatch. // See TypeCompareKind.ObliviousNullableModifierMatchesAny var compareKind = includeNullability ? TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.IgnoreNullableModifiersForReferenceTypes : TypeCompareKind.AllIgnoreOptions; return type1.Equals(type2, compareKind); } private bool HasIdentityConversionInternal(TypeSymbol type1, TypeSymbol type2) { return HasIdentityConversionInternal(type1, type2, IncludeNullability); } /// <summary> /// Returns true if: /// - Either type has no nullability information (oblivious). /// - Both types cannot have different nullability at the same time, /// including the case of type parameters that by themselves can represent nullable and not nullable reference types. /// </summary> internal bool HasTopLevelNullabilityIdentityConversion(TypeWithAnnotations source, TypeWithAnnotations destination) { if (!IncludeNullability) { return true; } if (source.NullableAnnotation.IsOblivious() || destination.NullableAnnotation.IsOblivious()) { return true; } var sourceIsPossiblyNullableTypeParameter = IsPossiblyNullableTypeTypeParameter(source); var destinationIsPossiblyNullableTypeParameter = IsPossiblyNullableTypeTypeParameter(destination); if (sourceIsPossiblyNullableTypeParameter && !destinationIsPossiblyNullableTypeParameter) { return destination.NullableAnnotation.IsAnnotated(); } if (destinationIsPossiblyNullableTypeParameter && !sourceIsPossiblyNullableTypeParameter) { return source.NullableAnnotation.IsAnnotated(); } return source.NullableAnnotation.IsAnnotated() == destination.NullableAnnotation.IsAnnotated(); } /// <summary> /// Returns false if source type can be nullable at the same time when destination type can be not nullable, /// including the case of type parameters that by themselves can represent nullable and not nullable reference types. /// When either type has no nullability information (oblivious), this method returns true. /// </summary> internal bool HasTopLevelNullabilityImplicitConversion(TypeWithAnnotations source, TypeWithAnnotations destination) { if (!IncludeNullability) { return true; } if (source.NullableAnnotation.IsOblivious() || destination.NullableAnnotation.IsOblivious() || destination.NullableAnnotation.IsAnnotated()) { return true; } if (IsPossiblyNullableTypeTypeParameter(source) && !IsPossiblyNullableTypeTypeParameter(destination)) { return false; } return !source.NullableAnnotation.IsAnnotated(); } private static bool IsPossiblyNullableTypeTypeParameter(in TypeWithAnnotations typeWithAnnotations) { var type = typeWithAnnotations.Type; return type is object && (type.IsPossiblyNullableReferenceTypeTypeParameter() || type.IsNullableTypeOrTypeParameter()); } /// <summary> /// Returns false if the source does not have an implicit conversion to the destination /// because of either incompatible top level or nested nullability. /// </summary> public bool HasAnyNullabilityImplicitConversion(TypeWithAnnotations source, TypeWithAnnotations destination) { Debug.Assert(IncludeNullability); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; return HasTopLevelNullabilityImplicitConversion(source, destination) && ClassifyImplicitConversionFromType(source.Type, destination.Type, ref discardedUseSiteInfo).Kind != ConversionKind.NoConversion; } public static bool HasIdentityConversionToAny<T>(T type, ArrayBuilder<T> targetTypes) where T : TypeSymbol { foreach (var targetType in targetTypes) { if (HasIdentityConversionInternal(type, targetType, includeNullability: false)) { return true; } } return false; } public Conversion ConvertExtensionMethodThisArg(TypeSymbol parameterType, TypeSymbol thisType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)thisType != null); var conversion = this.ClassifyImplicitExtensionMethodThisArgConversion(null, thisType, parameterType, ref useSiteInfo); return IsValidExtensionMethodThisArgConversion(conversion) ? conversion : Conversion.NoConversion; } // Spec 7.6.5.2: "An extension method ... is eligible if ... [an] implicit identity, reference, // or boxing conversion exists from expr to the type of the first parameter" public Conversion ClassifyImplicitExtensionMethodThisArgConversion(BoundExpression sourceExpressionOpt, TypeSymbol sourceType, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(sourceExpressionOpt == null || (object)sourceExpressionOpt.Type == sourceType); Debug.Assert((object)destination != null); if ((object)sourceType != null) { if (HasIdentityConversionInternal(sourceType, destination)) { return Conversion.Identity; } if (HasBoxingConversion(sourceType, destination, ref useSiteInfo)) { return Conversion.Boxing; } if (HasImplicitReferenceConversion(sourceType, destination, ref useSiteInfo)) { return Conversion.ImplicitReference; } } if (sourceExpressionOpt?.Kind == BoundKind.TupleLiteral) { // GetTupleLiteralConversion is not used with IncludeNullability currently. // If that changes, the delegate below will need to consider top-level nullability. Debug.Assert(!IncludeNullability); var tupleConversion = GetTupleLiteralConversion( (BoundTupleLiteral)sourceExpressionOpt, destination, ref useSiteInfo, ConversionKind.ImplicitTupleLiteral, (ConversionsBase conversions, BoundExpression s, TypeWithAnnotations d, ref CompoundUseSiteInfo<AssemblySymbol> u, bool a) => conversions.ClassifyImplicitExtensionMethodThisArgConversion(s, s.Type, d.Type, ref u), arg: false); if (tupleConversion.Exists) { return tupleConversion; } } if ((object)sourceType != null) { var tupleConversion = ClassifyTupleConversion( sourceType, destination, ref useSiteInfo, ConversionKind.ImplicitTuple, (ConversionsBase conversions, TypeWithAnnotations s, TypeWithAnnotations d, ref CompoundUseSiteInfo<AssemblySymbol> u, bool a) => { if (!conversions.HasTopLevelNullabilityImplicitConversion(s, d)) { return Conversion.NoConversion; } return conversions.ClassifyImplicitExtensionMethodThisArgConversion(null, s.Type, d.Type, ref u); }, arg: false); if (tupleConversion.Exists) { return tupleConversion; } } return Conversion.NoConversion; } // It should be possible to remove IsValidExtensionMethodThisArgConversion // since ClassifyImplicitExtensionMethodThisArgConversion should only // return valid conversions. https://github.com/dotnet/roslyn/issues/19622 // Spec 7.6.5.2: "An extension method ... is eligible if ... [an] implicit identity, reference, // or boxing conversion exists from expr to the type of the first parameter" public static bool IsValidExtensionMethodThisArgConversion(Conversion conversion) { switch (conversion.Kind) { case ConversionKind.Identity: case ConversionKind.Boxing: case ConversionKind.ImplicitReference: return true; case ConversionKind.ImplicitTuple: case ConversionKind.ImplicitTupleLiteral: // check if all element conversions satisfy the requirement foreach (var elementConversion in conversion.UnderlyingConversions) { if (!IsValidExtensionMethodThisArgConversion(elementConversion)) { return false; } } return true; default: // Caller should have not have calculated another conversion. Debug.Assert(conversion.Kind == ConversionKind.NoConversion); return false; } } private const bool F = false; private const bool T = true; // Notice that there is no implicit numeric conversion from a type to itself. That's an // identity conversion. private static readonly bool[,] s_implicitNumericConversions = { // to sb b s us i ui l ul c f d m // from /* sb */ { F, F, T, F, T, F, T, F, F, T, T, T }, /* b */ { F, F, T, T, T, T, T, T, F, T, T, T }, /* s */ { F, F, F, F, T, F, T, F, F, T, T, T }, /* us */ { F, F, F, F, T, T, T, T, F, T, T, T }, /* i */ { F, F, F, F, F, F, T, F, F, T, T, T }, /* ui */ { F, F, F, F, F, F, T, T, F, T, T, T }, /* l */ { F, F, F, F, F, F, F, F, F, T, T, T }, /* ul */ { F, F, F, F, F, F, F, F, F, T, T, T }, /* c */ { F, F, F, T, T, T, T, T, F, T, T, T }, /* f */ { F, F, F, F, F, F, F, F, F, F, T, F }, /* d */ { F, F, F, F, F, F, F, F, F, F, F, F }, /* m */ { F, F, F, F, F, F, F, F, F, F, F, F } }; private static readonly bool[,] s_explicitNumericConversions = { // to sb b s us i ui l ul c f d m // from /* sb */ { F, T, F, T, F, T, F, T, T, F, F, F }, /* b */ { T, F, F, F, F, F, F, F, T, F, F, F }, /* s */ { T, T, F, T, F, T, F, T, T, F, F, F }, /* us */ { T, T, T, F, F, F, F, F, T, F, F, F }, /* i */ { T, T, T, T, F, T, F, T, T, F, F, F }, /* ui */ { T, T, T, T, T, F, F, F, T, F, F, F }, /* l */ { T, T, T, T, T, T, F, T, T, F, F, F }, /* ul */ { T, T, T, T, T, T, T, F, T, F, F, F }, /* c */ { T, T, T, F, F, F, F, F, F, F, F, F }, /* f */ { T, T, T, T, T, T, T, T, T, F, F, T }, /* d */ { T, T, T, T, T, T, T, T, T, T, F, T }, /* m */ { T, T, T, T, T, T, T, T, T, T, T, F } }; private static int GetNumericTypeIndex(SpecialType specialType) { switch (specialType) { case SpecialType.System_SByte: return 0; case SpecialType.System_Byte: return 1; case SpecialType.System_Int16: return 2; case SpecialType.System_UInt16: return 3; case SpecialType.System_Int32: return 4; case SpecialType.System_UInt32: return 5; case SpecialType.System_Int64: return 6; case SpecialType.System_UInt64: return 7; case SpecialType.System_Char: return 8; case SpecialType.System_Single: return 9; case SpecialType.System_Double: return 10; case SpecialType.System_Decimal: return 11; default: return -1; } } #nullable enable private static bool HasImplicitNumericConversion(TypeSymbol source, TypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); int sourceIndex = GetNumericTypeIndex(source.SpecialType); if (sourceIndex < 0) { return false; } int destinationIndex = GetNumericTypeIndex(destination.SpecialType); if (destinationIndex < 0) { return false; } return s_implicitNumericConversions[sourceIndex, destinationIndex]; } private static bool HasExplicitNumericConversion(TypeSymbol source, TypeSymbol destination) { // SPEC: The explicit numeric conversions are the conversions from a numeric-type to another // SPEC: numeric-type for which an implicit numeric conversion does not already exist. Debug.Assert((object)source != null); Debug.Assert((object)destination != null); int sourceIndex = GetNumericTypeIndex(source.SpecialType); if (sourceIndex < 0) { return false; } int destinationIndex = GetNumericTypeIndex(destination.SpecialType); if (destinationIndex < 0) { return false; } return s_explicitNumericConversions[sourceIndex, destinationIndex]; } private static bool IsConstantNumericZero(ConstantValue value) { switch (value.Discriminator) { case ConstantValueTypeDiscriminator.SByte: return value.SByteValue == 0; case ConstantValueTypeDiscriminator.Byte: return value.ByteValue == 0; case ConstantValueTypeDiscriminator.Int16: return value.Int16Value == 0; case ConstantValueTypeDiscriminator.Int32: case ConstantValueTypeDiscriminator.NInt: return value.Int32Value == 0; case ConstantValueTypeDiscriminator.Int64: return value.Int64Value == 0; case ConstantValueTypeDiscriminator.UInt16: return value.UInt16Value == 0; case ConstantValueTypeDiscriminator.UInt32: case ConstantValueTypeDiscriminator.NUInt: return value.UInt32Value == 0; case ConstantValueTypeDiscriminator.UInt64: return value.UInt64Value == 0; case ConstantValueTypeDiscriminator.Single: case ConstantValueTypeDiscriminator.Double: return value.DoubleValue == 0; case ConstantValueTypeDiscriminator.Decimal: return value.DecimalValue == 0; } return false; } private static bool IsNumericType(TypeSymbol type) { switch (type.SpecialType) { case SpecialType.System_Char: case SpecialType.System_SByte: case SpecialType.System_Byte: case SpecialType.System_Int16: case SpecialType.System_UInt16: case SpecialType.System_Int32: case SpecialType.System_UInt32: case SpecialType.System_Int64: case SpecialType.System_UInt64: case SpecialType.System_Single: case SpecialType.System_Double: case SpecialType.System_Decimal: case SpecialType.System_IntPtr when type.IsNativeIntegerType: case SpecialType.System_UIntPtr when type.IsNativeIntegerType: return true; default: return false; } } private static bool HasSpecialIntPtrConversion(TypeSymbol source, TypeSymbol target) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); // There are only a total of twelve user-defined explicit conversions on IntPtr and UIntPtr: // // IntPtr <---> int // IntPtr <---> long // IntPtr <---> void* // UIntPtr <---> uint // UIntPtr <---> ulong // UIntPtr <---> void* // // The specification says that you can put any *standard* implicit or explicit conversion // on "either side" of a user-defined explicit conversion, so the specification allows, say, // UIntPtr --> byte because the conversion UIntPtr --> uint is user-defined and the // conversion uint --> byte is "standard". It is "standard" because the conversion // byte --> uint is an implicit numeric conversion. // This means that certain conversions should be illegal. For example, IntPtr --> ulong // should be illegal because none of int --> ulong, long --> ulong and void* --> ulong // are "standard" conversions. // Similarly, some conversions involving IntPtr should be illegal because they are // ambiguous. byte --> IntPtr?, for example, is ambiguous. (There are four possible // UD operators: int --> IntPtr and long --> IntPtr, and their lifted versions. The // best possible source type is int, the best possible target type is IntPtr?, and // there is an ambiguity between the unlifted int --> IntPtr, and the lifted // int? --> IntPtr? conversions.) // In practice, the native compiler, and hence, the Roslyn compiler, allows all // these conversions. Any conversion from a numeric type to IntPtr, or from an IntPtr // to a numeric type, is allowed. Also, any conversion from a pointer type to IntPtr // or vice versa is allowed. var s0 = source.StrippedType(); var t0 = target.StrippedType(); TypeSymbol otherType; if (isIntPtrOrUIntPtr(s0)) { otherType = t0; } else if (isIntPtrOrUIntPtr(t0)) { otherType = s0; } else { return false; } if (otherType.IsPointerOrFunctionPointer()) { return true; } if (otherType.TypeKind == TypeKind.Enum) { return true; } switch (otherType.SpecialType) { case SpecialType.System_SByte: case SpecialType.System_Byte: case SpecialType.System_Int16: case SpecialType.System_UInt16: case SpecialType.System_Char: case SpecialType.System_Int32: case SpecialType.System_UInt32: case SpecialType.System_Int64: case SpecialType.System_UInt64: case SpecialType.System_Double: case SpecialType.System_Single: case SpecialType.System_Decimal: return true; } return false; static bool isIntPtrOrUIntPtr(TypeSymbol type) => (type.SpecialType == SpecialType.System_IntPtr || type.SpecialType == SpecialType.System_UIntPtr) && !type.IsNativeIntegerType; } private static bool HasExplicitEnumerationConversion(TypeSymbol source, TypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // SPEC: The explicit enumeration conversions are: // SPEC: From sbyte, byte, short, ushort, int, uint, long, ulong, nint, nuint, char, float, double, or decimal to any enum-type. // SPEC: From any enum-type to sbyte, byte, short, ushort, int, uint, long, ulong, nint, nuint, char, float, double, or decimal. // SPEC: From any enum-type to any other enum-type. if (IsNumericType(source) && destination.IsEnumType()) { return true; } if (IsNumericType(destination) && source.IsEnumType()) { return true; } if (source.IsEnumType() && destination.IsEnumType()) { return true; } return false; } #nullable disable private Conversion ClassifyImplicitNullableConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // SPEC: Predefined implicit conversions that operate on non-nullable value types can also be used with // SPEC: nullable forms of those types. For each of the predefined implicit identity, numeric and tuple conversions // SPEC: that convert from a non-nullable value type S to a non-nullable value type T, the following implicit // SPEC: nullable conversions exist: // SPEC: * An implicit conversion from S? to T?. // SPEC: * An implicit conversion from S to T?. if (!destination.IsNullableType()) { return Conversion.NoConversion; } TypeSymbol unwrappedDestination = destination.GetNullableUnderlyingType(); TypeSymbol unwrappedSource = source.StrippedType(); if (!unwrappedSource.IsValueType) { return Conversion.NoConversion; } if (HasIdentityConversionInternal(unwrappedSource, unwrappedDestination)) { return new Conversion(ConversionKind.ImplicitNullable, Conversion.IdentityUnderlying); } if (HasImplicitNumericConversion(unwrappedSource, unwrappedDestination)) { return new Conversion(ConversionKind.ImplicitNullable, Conversion.ImplicitNumericUnderlying); } var tupleConversion = ClassifyImplicitTupleConversion(unwrappedSource, unwrappedDestination, ref useSiteInfo); if (tupleConversion.Exists) { return new Conversion(ConversionKind.ImplicitNullable, ImmutableArray.Create(tupleConversion)); } return Conversion.NoConversion; } private delegate Conversion ClassifyConversionFromExpressionDelegate(ConversionsBase conversions, BoundExpression sourceExpression, TypeWithAnnotations destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool arg); private delegate Conversion ClassifyConversionFromTypeDelegate(ConversionsBase conversions, TypeWithAnnotations source, TypeWithAnnotations destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool arg); private Conversion GetImplicitTupleLiteralConversion(BoundTupleLiteral source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // GetTupleLiteralConversion is not used with IncludeNullability currently. // If that changes, the delegate below will need to consider top-level nullability. Debug.Assert(!IncludeNullability); return GetTupleLiteralConversion( source, destination, ref useSiteInfo, ConversionKind.ImplicitTupleLiteral, (ConversionsBase conversions, BoundExpression s, TypeWithAnnotations d, ref CompoundUseSiteInfo<AssemblySymbol> u, bool a) => conversions.ClassifyImplicitConversionFromExpression(s, d.Type, ref u), arg: false); } private Conversion GetExplicitTupleLiteralConversion(BoundTupleLiteral source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool forCast) { // GetTupleLiteralConversion is not used with IncludeNullability currently. // If that changes, the delegate below will need to consider top-level nullability. Debug.Assert(!IncludeNullability); return GetTupleLiteralConversion( source, destination, ref useSiteInfo, ConversionKind.ExplicitTupleLiteral, (ConversionsBase conversions, BoundExpression s, TypeWithAnnotations d, ref CompoundUseSiteInfo<AssemblySymbol> u, bool a) => conversions.ClassifyConversionFromExpression(s, d.Type, ref u, a), forCast); } private Conversion GetTupleLiteralConversion( BoundTupleLiteral source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, ConversionKind kind, ClassifyConversionFromExpressionDelegate classifyConversion, bool arg) { var arguments = source.Arguments; // check if the type is actually compatible type for a tuple of given cardinality if (!destination.IsTupleTypeOfCardinality(arguments.Length)) { return Conversion.NoConversion; } var targetElementTypes = destination.TupleElementTypesWithAnnotations; Debug.Assert(arguments.Length == targetElementTypes.Length); // check arguments against flattened list of target element types var argumentConversions = ArrayBuilder<Conversion>.GetInstance(arguments.Length); for (int i = 0; i < arguments.Length; i++) { var argument = arguments[i]; var result = classifyConversion(this, argument, targetElementTypes[i], ref useSiteInfo, arg); if (!result.Exists) { argumentConversions.Free(); return Conversion.NoConversion; } argumentConversions.Add(result); } return new Conversion(kind, argumentConversions.ToImmutableAndFree()); } private Conversion ClassifyImplicitTupleConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { return ClassifyTupleConversion( source, destination, ref useSiteInfo, ConversionKind.ImplicitTuple, (ConversionsBase conversions, TypeWithAnnotations s, TypeWithAnnotations d, ref CompoundUseSiteInfo<AssemblySymbol> u, bool a) => { if (!conversions.HasTopLevelNullabilityImplicitConversion(s, d)) { return Conversion.NoConversion; } return conversions.ClassifyImplicitConversionFromType(s.Type, d.Type, ref u); }, arg: false); } private Conversion ClassifyExplicitTupleConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool forCast) { return ClassifyTupleConversion( source, destination, ref useSiteInfo, ConversionKind.ExplicitTuple, (ConversionsBase conversions, TypeWithAnnotations s, TypeWithAnnotations d, ref CompoundUseSiteInfo<AssemblySymbol> u, bool a) => { if (!conversions.HasTopLevelNullabilityImplicitConversion(s, d)) { return Conversion.NoConversion; } return conversions.ClassifyConversionFromType(s.Type, d.Type, ref u, a); }, forCast); } private Conversion ClassifyTupleConversion( TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, ConversionKind kind, ClassifyConversionFromTypeDelegate classifyConversion, bool arg) { ImmutableArray<TypeWithAnnotations> sourceTypes; ImmutableArray<TypeWithAnnotations> destTypes; if (!source.TryGetElementTypesWithAnnotationsIfTupleType(out sourceTypes) || !destination.TryGetElementTypesWithAnnotationsIfTupleType(out destTypes) || sourceTypes.Length != destTypes.Length) { return Conversion.NoConversion; } var nestedConversions = ArrayBuilder<Conversion>.GetInstance(sourceTypes.Length); for (int i = 0; i < sourceTypes.Length; i++) { var conversion = classifyConversion(this, sourceTypes[i], destTypes[i], ref useSiteInfo, arg); if (!conversion.Exists) { nestedConversions.Free(); return Conversion.NoConversion; } nestedConversions.Add(conversion); } return new Conversion(kind, nestedConversions.ToImmutableAndFree()); } private Conversion ClassifyExplicitNullableConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool forCast) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // SPEC: Explicit nullable conversions permit predefined explicit conversions that operate on // SPEC: non-nullable value types to also be used with nullable forms of those types. For // SPEC: each of the predefined explicit conversions that convert from a non-nullable value type // SPEC: S to a non-nullable value type T, the following nullable conversions exist: // SPEC: An explicit conversion from S? to T?. // SPEC: An explicit conversion from S to T?. // SPEC: An explicit conversion from S? to T. if (!source.IsNullableType() && !destination.IsNullableType()) { return Conversion.NoConversion; } TypeSymbol unwrappedSource = source.StrippedType(); TypeSymbol unwrappedDestination = destination.StrippedType(); if (HasIdentityConversionInternal(unwrappedSource, unwrappedDestination)) { return new Conversion(ConversionKind.ExplicitNullable, Conversion.IdentityUnderlying); } if (HasImplicitNumericConversion(unwrappedSource, unwrappedDestination)) { return new Conversion(ConversionKind.ExplicitNullable, Conversion.ImplicitNumericUnderlying); } if (HasExplicitNumericConversion(unwrappedSource, unwrappedDestination)) { return new Conversion(ConversionKind.ExplicitNullable, Conversion.ExplicitNumericUnderlying); } var tupleConversion = ClassifyExplicitTupleConversion(unwrappedSource, unwrappedDestination, ref useSiteInfo, forCast); if (tupleConversion.Exists) { return new Conversion(ConversionKind.ExplicitNullable, ImmutableArray.Create(tupleConversion)); } if (HasExplicitEnumerationConversion(unwrappedSource, unwrappedDestination)) { return new Conversion(ConversionKind.ExplicitNullable, Conversion.ExplicitEnumerationUnderlying); } if (HasPointerToIntegerConversion(unwrappedSource, unwrappedDestination)) { return new Conversion(ConversionKind.ExplicitNullable, Conversion.PointerToIntegerUnderlying); } return Conversion.NoConversion; } private bool HasCovariantArrayConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); var s = source as ArrayTypeSymbol; var d = destination as ArrayTypeSymbol; if ((object)s == null || (object)d == null) { return false; } // * S and T differ only in element type. In other words, S and T have the same number of dimensions. if (!s.HasSameShapeAs(d)) { return false; } // * Both SE and TE are reference types. // * An implicit reference conversion exists from SE to TE. return HasImplicitReferenceConversion(s.ElementTypeWithAnnotations, d.ElementTypeWithAnnotations, ref useSiteInfo); } public bool HasIdentityOrImplicitReferenceConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (HasIdentityConversionInternal(source, destination)) { return true; } return HasImplicitReferenceConversion(source, destination, ref useSiteInfo); } private static bool HasImplicitDynamicConversionFromExpression(TypeSymbol expressionType, TypeSymbol destination) { // Spec (§6.1.8) // An implicit dynamic conversion exists from an expression of type dynamic to any type T. Debug.Assert((object)destination != null); return expressionType?.Kind == SymbolKind.DynamicType && !destination.IsPointerOrFunctionPointer(); } private static bool HasExplicitDynamicConversion(TypeSymbol source, TypeSymbol destination) { // SPEC: An explicit dynamic conversion exists from an expression of [sic] type dynamic to any type T. // ISSUE: The "an expression of" part of the spec is probably an error; see https://github.com/dotnet/csharplang/issues/132 Debug.Assert((object)source != null); Debug.Assert((object)destination != null); return source.Kind == SymbolKind.DynamicType && !destination.IsPointerOrFunctionPointer(); } private bool HasArrayConversionToInterface(ArrayTypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (!source.IsSZArray) { return false; } if (!destination.IsInterfaceType()) { return false; } // The specification says that there is a conversion: // * From a single-dimensional array type S[] to IList<T> and its base // interfaces, provided that there is an implicit identity or reference // conversion from S to T. // // Newer versions of the framework also have arrays be convertible to // IReadOnlyList<T> and IReadOnlyCollection<T>; we honor that as well. // // Therefore we must check for: // // IList<T> // ICollection<T> // IEnumerable<T> // IEnumerable // IReadOnlyList<T> // IReadOnlyCollection<T> if (destination.SpecialType == SpecialType.System_Collections_IEnumerable) { return true; } NamedTypeSymbol destinationAgg = (NamedTypeSymbol)destination; if (destinationAgg.AllTypeArgumentCount() != 1) { return false; } if (!destinationAgg.IsPossibleArrayGenericInterface()) { return false; } TypeWithAnnotations elementType = source.ElementTypeWithAnnotations; TypeWithAnnotations argument0 = destinationAgg.TypeArgumentWithDefinitionUseSiteDiagnostics(0, ref useSiteInfo); if (IncludeNullability && !HasTopLevelNullabilityImplicitConversion(elementType, argument0)) { return false; } return HasIdentityOrImplicitReferenceConversion(elementType.Type, argument0.Type, ref useSiteInfo); } private bool HasImplicitReferenceConversion(TypeWithAnnotations source, TypeWithAnnotations destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (IncludeNullability) { if (!HasTopLevelNullabilityImplicitConversion(source, destination)) { return false; } // Check for identity conversion of underlying types if the top-level nullability is distinct. // (An identity conversion where nullability matches is not considered an implicit reference conversion.) if (source.NullableAnnotation != destination.NullableAnnotation && HasIdentityConversionInternal(source.Type, destination.Type, includeNullability: true)) { return true; } } return HasImplicitReferenceConversion(source.Type, destination.Type, ref useSiteInfo); } #nullable enable internal bool HasImplicitReferenceConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (source.IsErrorType()) { return false; } if (!source.IsReferenceType) { return false; } // SPEC: The implicit reference conversions are: // SPEC: UNDONE: From any reference-type to a reference-type T if it has an implicit identity // SPEC: UNDONE: or reference conversion to a reference-type T0 and T0 has an identity conversion to T. // UNDONE: Is the right thing to do here to strip dynamic off and check for convertibility? // SPEC: From any reference type to object and dynamic. if (destination.SpecialType == SpecialType.System_Object || destination.Kind == SymbolKind.DynamicType) { return true; } switch (source.TypeKind) { case TypeKind.Class: // SPEC: From any class type S to any class type T provided S is derived from T. if (destination.IsClassType() && IsBaseClass(source, destination, ref useSiteInfo)) { return true; } return HasImplicitConversionToInterface(source, destination, ref useSiteInfo); case TypeKind.Interface: // SPEC: From any interface-type S to any interface-type T, provided S is derived from T. // NOTE: This handles variance conversions return HasImplicitConversionToInterface(source, destination, ref useSiteInfo); case TypeKind.Delegate: // SPEC: From any delegate-type to System.Delegate and the interfaces it implements. // NOTE: This handles variance conversions. return HasImplicitConversionFromDelegate(source, destination, ref useSiteInfo); case TypeKind.TypeParameter: return HasImplicitReferenceTypeParameterConversion((TypeParameterSymbol)source, destination, ref useSiteInfo); case TypeKind.Array: // SPEC: From an array-type S ... to an array-type T, provided ... // SPEC: From any array-type to System.Array and the interfaces it implements. // SPEC: From a single-dimensional array type S[] to IList<T>, provided ... return HasImplicitConversionFromArray(source, destination, ref useSiteInfo); } // UNDONE: Implicit conversions involving type parameters that are known to be reference types. return false; } private bool HasImplicitConversionToInterface(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (!destination.IsInterfaceType()) { return false; } // * From any class type S to any interface type T provided S implements an interface // convertible to T. if (source.IsClassType()) { return HasAnyBaseInterfaceConversion(source, destination, ref useSiteInfo); } // * From any interface type S to any interface type T provided S implements an interface // convertible to T. // * From any interface type S to any interface type T provided S is not T and S is // an interface convertible to T. if (source.IsInterfaceType()) { if (HasAnyBaseInterfaceConversion(source, destination, ref useSiteInfo)) { return true; } if (!HasIdentityConversionInternal(source, destination) && HasInterfaceVarianceConversion(source, destination, ref useSiteInfo)) { return true; } } return false; } private bool HasImplicitConversionFromArray(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var s = source as ArrayTypeSymbol; if (s is null) { return false; } // * From an array type S with an element type SE to an array type T with element type TE // provided that all of the following are true: // * S and T differ only in element type. In other words, S and T have the same number of dimensions. // * Both SE and TE are reference types. // * An implicit reference conversion exists from SE to TE. if (HasCovariantArrayConversion(source, destination, ref useSiteInfo)) { return true; } // * From any array type to System.Array or any interface implemented by System.Array. if (destination.GetSpecialTypeSafe() == SpecialType.System_Array) { return true; } if (IsBaseInterface(destination, this.corLibrary.GetDeclaredSpecialType(SpecialType.System_Array), ref useSiteInfo)) { return true; } // * From a single-dimensional array type S[] to IList<T> and its base // interfaces, provided that there is an implicit identity or reference // conversion from S to T. if (HasArrayConversionToInterface(s, destination, ref useSiteInfo)) { return true; } return false; } private bool HasImplicitConversionFromDelegate(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (!source.IsDelegateType()) { return false; } // * From any delegate type to System.Delegate // // SPEC OMISSION: // // The spec should actually say // // * From any delegate type to System.Delegate // * From any delegate type to System.MulticastDelegate // * From any delegate type to any interface implemented by System.MulticastDelegate var specialDestination = destination.GetSpecialTypeSafe(); if (specialDestination == SpecialType.System_MulticastDelegate || specialDestination == SpecialType.System_Delegate || IsBaseInterface(destination, this.corLibrary.GetDeclaredSpecialType(SpecialType.System_MulticastDelegate), ref useSiteInfo)) { return true; } // * From any delegate type S to a delegate type T provided S is not T and // S is a delegate convertible to T if (HasDelegateVarianceConversion(source, destination, ref useSiteInfo)) { return true; } return false; } private bool HasImplicitFunctionTypeConversion(FunctionTypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (destination is FunctionTypeSymbol destinationFunctionType) { return HasImplicitSignatureConversion(source, destinationFunctionType, ref useSiteInfo); } return IsValidFunctionTypeConversionTarget(destination, ref useSiteInfo); } internal bool IsValidFunctionTypeConversionTarget(TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (destination.SpecialType == SpecialType.System_MulticastDelegate) { return true; } if (destination.IsNonGenericExpressionType()) { return true; } var derivedType = this.corLibrary.GetDeclaredSpecialType(SpecialType.System_MulticastDelegate); if (IsBaseClass(derivedType, destination, ref useSiteInfo) || IsBaseInterface(destination, derivedType, ref useSiteInfo)) { return true; } return false; } private bool HasImplicitSignatureConversion(FunctionTypeSymbol sourceType, FunctionTypeSymbol destinationType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var sourceDelegate = sourceType.GetInternalDelegateType(); var destinationDelegate = destinationType.GetInternalDelegateType(); // https://github.com/dotnet/roslyn/issues/55909: We're relying on the variance of // FunctionTypeSymbol.GetInternalDelegateType() which fails for synthesized // delegate types where the type parameters are invariant. return HasDelegateVarianceConversion(sourceDelegate, destinationDelegate, ref useSiteInfo); } #nullable disable public bool HasImplicitTypeParameterConversion(TypeParameterSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (HasImplicitReferenceTypeParameterConversion(source, destination, ref useSiteInfo)) { return true; } if (HasImplicitBoxingTypeParameterConversion(source, destination, ref useSiteInfo)) { return true; } if ((destination.TypeKind == TypeKind.TypeParameter) && source.DependsOn((TypeParameterSymbol)destination)) { return true; } return false; } private bool HasImplicitReferenceTypeParameterConversion(TypeParameterSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (source.IsValueType) { return false; // Not a reference conversion. } // The following implicit conversions exist for a given type parameter T: // // * From T to its effective base class C. // * From T to any base class of C. // * From T to any interface implemented by C (or any interface variance-compatible with such) if (HasImplicitEffectiveBaseConversion(source, destination, ref useSiteInfo)) { return true; } // * From T to any interface type I in T's effective interface set, and // from T to any base interface of I (or any interface variance-compatible with such) if (HasImplicitEffectiveInterfaceSetConversion(source, destination, ref useSiteInfo)) { return true; } // * From T to a type parameter U, provided T depends on U. if ((destination.TypeKind == TypeKind.TypeParameter) && source.DependsOn((TypeParameterSymbol)destination)) { return true; } return false; } // Spec 6.1.10: Implicit conversions involving type parameters private bool HasImplicitEffectiveBaseConversion(TypeParameterSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // * From T to its effective base class C. var effectiveBaseClass = source.EffectiveBaseClass(ref useSiteInfo); if (HasIdentityConversionInternal(effectiveBaseClass, destination)) { return true; } // * From T to any base class of C. if (IsBaseClass(effectiveBaseClass, destination, ref useSiteInfo)) { return true; } // * From T to any interface implemented by C (or any interface variance-compatible with such) if (HasAnyBaseInterfaceConversion(effectiveBaseClass, destination, ref useSiteInfo)) { return true; } return false; } private bool HasImplicitEffectiveInterfaceSetConversion(TypeParameterSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (!destination.IsInterfaceType()) { return false; } // * From T to any interface type I in T's effective interface set, and // from T to any base interface of I (or any interface variance-compatible with such) foreach (var i in source.AllEffectiveInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { if (HasInterfaceVarianceConversion(i, destination, ref useSiteInfo)) { return true; } } return false; } private bool HasAnyBaseInterfaceConversion(TypeSymbol derivedType, TypeSymbol baseType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)derivedType != null); Debug.Assert((object)baseType != null); if (!baseType.IsInterfaceType()) { return false; } var d = derivedType as NamedTypeSymbol; if ((object)d == null) { return false; } foreach (var i in d.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { if (HasInterfaceVarianceConversion(i, baseType, ref useSiteInfo)) { return true; } } return false; } //////////////////////////////////////////////////////////////////////////////// // The rules for variant interface and delegate conversions are the same: // // An interface/delegate type S is convertible to an interface/delegate type T // if and only if T is U<S1, ... Sn> and T is U<T1, ... Tn> such that for all // parameters of U: // // * if the ith parameter of U is invariant then Si is exactly equal to Ti. // * if the ith parameter of U is covariant then either Si is exactly equal // to Ti, or there is an implicit reference conversion from Si to Ti. // * if the ith parameter of U is contravariant then either Si is exactly // equal to Ti, or there is an implicit reference conversion from Ti to Si. private bool HasInterfaceVarianceConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); NamedTypeSymbol s = source as NamedTypeSymbol; NamedTypeSymbol d = destination as NamedTypeSymbol; if ((object)s == null || (object)d == null) { return false; } if (!s.IsInterfaceType() || !d.IsInterfaceType()) { return false; } return HasVariantConversion(s, d, ref useSiteInfo); } private bool HasDelegateVarianceConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); NamedTypeSymbol s = source as NamedTypeSymbol; NamedTypeSymbol d = destination as NamedTypeSymbol; if ((object)s == null || (object)d == null) { return false; } if (!s.IsDelegateType() || !d.IsDelegateType()) { return false; } return HasVariantConversion(s, d, ref useSiteInfo); } private bool HasVariantConversion(NamedTypeSymbol source, NamedTypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // We check for overflows in HasVariantConversion, because they are only an issue // in the presence of contravariant type parameters, which are not involved in // most conversions. // See VarianceTests for examples (e.g. TestVarianceConversionCycle, // TestVarianceConversionInfiniteExpansion). // // CONSIDER: A more rigorous solution would mimic the CLI approach, which uses // a combination of requiring finite instantiation closures (see section 9.2 of // the CLI spec) and records previous conversion steps to check for cycles. if (currentRecursionDepth >= MaximumRecursionDepth) { // NOTE: The spec doesn't really address what happens if there's an overflow // in our conversion check. It's sort of implied that the conversion "proof" // should be finite, so we'll just say that no conversion is possible. return false; } // Do a quick check up front to avoid instantiating a new Conversions object, // if possible. var quickResult = HasVariantConversionQuick(source, destination); if (quickResult.HasValue()) { return quickResult.Value(); } return this.CreateInstance(currentRecursionDepth + 1). HasVariantConversionNoCycleCheck(source, destination, ref useSiteInfo); } private ThreeState HasVariantConversionQuick(NamedTypeSymbol source, NamedTypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (HasIdentityConversionInternal(source, destination)) { return ThreeState.True; } NamedTypeSymbol typeSymbol = source.OriginalDefinition; if (!TypeSymbol.Equals(typeSymbol, destination.OriginalDefinition, TypeCompareKind.ConsiderEverything2)) { return ThreeState.False; } return ThreeState.Unknown; } private bool HasVariantConversionNoCycleCheck(NamedTypeSymbol source, NamedTypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); var typeParameters = ArrayBuilder<TypeWithAnnotations>.GetInstance(); var sourceTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); var destinationTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); try { source.OriginalDefinition.GetAllTypeArguments(typeParameters, ref useSiteInfo); source.GetAllTypeArguments(sourceTypeArguments, ref useSiteInfo); destination.GetAllTypeArguments(destinationTypeArguments, ref useSiteInfo); Debug.Assert(TypeSymbol.Equals(source.OriginalDefinition, destination.OriginalDefinition, TypeCompareKind.AllIgnoreOptions)); Debug.Assert(typeParameters.Count == sourceTypeArguments.Count); Debug.Assert(typeParameters.Count == destinationTypeArguments.Count); for (int paramIndex = 0; paramIndex < typeParameters.Count; ++paramIndex) { var sourceTypeArgument = sourceTypeArguments[paramIndex]; var destinationTypeArgument = destinationTypeArguments[paramIndex]; // If they're identical then this one is automatically good, so skip it. if (HasIdentityConversionInternal(sourceTypeArgument.Type, destinationTypeArgument.Type) && HasTopLevelNullabilityIdentityConversion(sourceTypeArgument, destinationTypeArgument)) { continue; } TypeParameterSymbol typeParameterSymbol = (TypeParameterSymbol)typeParameters[paramIndex].Type; switch (typeParameterSymbol.Variance) { case VarianceKind.None: // System.IEquatable<T> is invariant for back compat reasons (dynamic type checks could start // to succeed where they previously failed, creating different runtime behavior), but the uses // require treatment specifically of nullability as contravariant, so we special case the // behavior here. Normally we use GetWellKnownType for these kinds of checks, but in this // case we don't want just the canonical IEquatable to be special-cased, we want all definitions // to be treated as contravariant, in case there are other definitions in metadata that were // compiled with that expectation. if (isTypeIEquatable(destination.OriginalDefinition) && TypeSymbol.Equals(destinationTypeArgument.Type, sourceTypeArgument.Type, TypeCompareKind.AllNullableIgnoreOptions) && HasAnyNullabilityImplicitConversion(destinationTypeArgument, sourceTypeArgument)) { return true; } return false; case VarianceKind.Out: if (!HasImplicitReferenceConversion(sourceTypeArgument, destinationTypeArgument, ref useSiteInfo)) { return false; } break; case VarianceKind.In: if (!HasImplicitReferenceConversion(destinationTypeArgument, sourceTypeArgument, ref useSiteInfo)) { return false; } break; default: throw ExceptionUtilities.UnexpectedValue(typeParameterSymbol.Variance); } } } finally { typeParameters.Free(); sourceTypeArguments.Free(); destinationTypeArguments.Free(); } return true; static bool isTypeIEquatable(NamedTypeSymbol type) { return type is { IsInterface: true, Name: "IEquatable", ContainingNamespace: { Name: "System", ContainingNamespace: { IsGlobalNamespace: true } }, ContainingSymbol: { Kind: SymbolKind.Namespace }, TypeParameters: { Length: 1 } }; } } // Spec 6.1.10 private bool HasImplicitBoxingTypeParameterConversion(TypeParameterSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (source.IsReferenceType) { return false; // Not a boxing conversion; both source and destination are references. } // The following implicit conversions exist for a given type parameter T: // // * From T to its effective base class C. // * From T to any base class of C. // * From T to any interface implemented by C (or any interface variance-compatible with such) if (HasImplicitEffectiveBaseConversion(source, destination, ref useSiteInfo)) { return true; } // * From T to any interface type I in T's effective interface set, and // from T to any base interface of I (or any interface variance-compatible with such) if (HasImplicitEffectiveInterfaceSetConversion(source, destination, ref useSiteInfo)) { return true; } // SPEC: From T to a type parameter U, provided T depends on U if ((destination.TypeKind == TypeKind.TypeParameter) && source.DependsOn((TypeParameterSymbol)destination)) { return true; } // SPEC: From T to a reference type I if it has an implicit conversion to a reference // SPEC: type S0 and S0 has an identity conversion to S. At run-time the conversion // SPEC: is executed the same way as the conversion to S0. // REVIEW: If T is not known to be a reference type then the only way this clause can // REVIEW: come into effect is if the target type is dynamic. Is that correct? if (destination.Kind == SymbolKind.DynamicType) { return true; } return false; } public bool HasBoxingConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // Certain type parameter conversions are classified as boxing conversions. if ((source.TypeKind == TypeKind.TypeParameter) && HasImplicitBoxingTypeParameterConversion((TypeParameterSymbol)source, destination, ref useSiteInfo)) { return true; } // The rest of the boxing conversions only operate when going from a value type to a // reference type. if (!source.IsValueType || !destination.IsReferenceType) { return false; } // A boxing conversion exists from a nullable type to a reference type if and only if a // boxing conversion exists from the underlying type. if (source.IsNullableType()) { return HasBoxingConversion(source.GetNullableUnderlyingType(), destination, ref useSiteInfo); } // A boxing conversion exists from any non-nullable value type to object and dynamic, to // System.ValueType, and to any interface type variance-compatible with one implemented // by the non-nullable value type. // Furthermore, an enum type can be converted to the type System.Enum. // We set the base class of the structs to System.ValueType, System.Enum, etc, so we can // just check here. // There are a couple of exceptions. The very special types ArgIterator, ArgumentHandle and // TypedReference are not boxable: if (source.IsRestrictedType()) { return false; } if (destination.Kind == SymbolKind.DynamicType) { return !source.IsPointerOrFunctionPointer(); } if (IsBaseClass(source, destination, ref useSiteInfo)) { return true; } if (HasAnyBaseInterfaceConversion(source, destination, ref useSiteInfo)) { return true; } return false; } internal static bool HasImplicitPointerToVoidConversion(TypeSymbol source, TypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // SPEC: The set of implicit conversions is extended to include... // SPEC: ... from any pointer type to the type void*. return source.IsPointerOrFunctionPointer() && destination is PointerTypeSymbol { PointedAtType: { SpecialType: SpecialType.System_Void } }; } #nullable enable internal bool HasImplicitPointerConversion(TypeSymbol? source, TypeSymbol? destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (!(source is FunctionPointerTypeSymbol { Signature: { } sourceSig }) || !(destination is FunctionPointerTypeSymbol { Signature: { } destinationSig })) { return false; } if (sourceSig.ParameterCount != destinationSig.ParameterCount || sourceSig.CallingConvention != destinationSig.CallingConvention) { return false; } if (sourceSig.CallingConvention == Cci.CallingConvention.Unmanaged && !sourceSig.GetCallingConventionModifiers().SetEquals(destinationSig.GetCallingConventionModifiers())) { return false; } for (int i = 0; i < sourceSig.ParameterCount; i++) { var sourceParam = sourceSig.Parameters[i]; var destinationParam = destinationSig.Parameters[i]; if (sourceParam.RefKind != destinationParam.RefKind) { return false; } if (!hasConversion(sourceParam.RefKind, destinationSig.Parameters[i].TypeWithAnnotations, sourceSig.Parameters[i].TypeWithAnnotations, ref useSiteInfo)) { return false; } } return sourceSig.RefKind == destinationSig.RefKind && hasConversion(sourceSig.RefKind, sourceSig.ReturnTypeWithAnnotations, destinationSig.ReturnTypeWithAnnotations, ref useSiteInfo); bool hasConversion(RefKind refKind, TypeWithAnnotations sourceType, TypeWithAnnotations destinationType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { switch (refKind) { case RefKind.None: return (!IncludeNullability || HasTopLevelNullabilityImplicitConversion(sourceType, destinationType)) && (HasIdentityOrImplicitReferenceConversion(sourceType.Type, destinationType.Type, ref useSiteInfo) || HasImplicitPointerToVoidConversion(sourceType.Type, destinationType.Type) || HasImplicitPointerConversion(sourceType.Type, destinationType.Type, ref useSiteInfo)); default: return (!IncludeNullability || HasTopLevelNullabilityIdentityConversion(sourceType, destinationType)) && HasIdentityConversion(sourceType.Type, destinationType.Type); } } } #nullable disable private bool HasIdentityOrReferenceConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (HasIdentityConversionInternal(source, destination)) { return true; } if (HasImplicitReferenceConversion(source, destination, ref useSiteInfo)) { return true; } if (HasExplicitReferenceConversion(source, destination, ref useSiteInfo)) { return true; } return false; } private bool HasExplicitReferenceConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // SPEC: The explicit reference conversions are: // SPEC: From object and dynamic to any other reference type. if (source.SpecialType == SpecialType.System_Object) { if (destination.IsReferenceType) { return true; } } else if (source.Kind == SymbolKind.DynamicType && destination.IsReferenceType) { return true; } // SPEC: From any class-type S to any class-type T, provided S is a base class of T. if (destination.IsClassType() && IsBaseClass(destination, source, ref useSiteInfo)) { return true; } // SPEC: From any class-type S to any interface-type T, provided S is not sealed and provided S does not implement T. // ISSUE: class C : IEnumerable<Mammal> { } converting this to IEnumerable<Animal> is not an explicit conversion, // ISSUE: it is an implicit conversion. if (source.IsClassType() && destination.IsInterfaceType() && !source.IsSealed && !HasAnyBaseInterfaceConversion(source, destination, ref useSiteInfo)) { return true; } // SPEC: From any interface-type S to any class-type T, provided T is not sealed or provided T implements S. // ISSUE: What if T is sealed and implements an interface variance-convertible to S? // ISSUE: eg, sealed class C : IEnum<Mammal> { ... } you should be able to cast an IEnum<Animal> to C. if (source.IsInterfaceType() && destination.IsClassType() && (!destination.IsSealed || HasAnyBaseInterfaceConversion(destination, source, ref useSiteInfo))) { return true; } // SPEC: From any interface-type S to any interface-type T, provided S is not derived from T. // ISSUE: This does not rule out identity conversions, which ought not to be classified as // ISSUE: explicit reference conversions. // ISSUE: IEnumerable<Mammal> and IEnumerable<Animal> do not derive from each other but this is // ISSUE: not an explicit reference conversion, this is an implicit reference conversion. if (source.IsInterfaceType() && destination.IsInterfaceType() && !HasImplicitConversionToInterface(source, destination, ref useSiteInfo)) { return true; } // SPEC: UNDONE: From a reference type to a reference type T if it has an explicit reference conversion to a reference type T0 and T0 has an identity conversion T. // SPEC: UNDONE: From a reference type to an interface or delegate type T if it has an explicit reference conversion to an interface or delegate type T0 and either T0 is variance-convertible to T or T is variance-convertible to T0 (§13.1.3.2). if (HasExplicitArrayConversion(source, destination, ref useSiteInfo)) { return true; } if (HasExplicitDelegateConversion(source, destination, ref useSiteInfo)) { return true; } if (HasExplicitReferenceTypeParameterConversion(source, destination, ref useSiteInfo)) { return true; } return false; } // Spec 6.2.7 Explicit conversions involving type parameters private bool HasExplicitReferenceTypeParameterConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); TypeParameterSymbol s = source as TypeParameterSymbol; TypeParameterSymbol t = destination as TypeParameterSymbol; // SPEC: The following explicit conversions exist for a given type parameter T: // SPEC: If T is known to be a reference type, the conversions are all classified as explicit reference conversions. // SPEC: If T is not known to be a reference type, the conversions are classified as unboxing conversions. // SPEC: From the effective base class C of T to T and from any base class of C to T. if ((object)t != null && t.IsReferenceType) { for (var type = t.EffectiveBaseClass(ref useSiteInfo); (object)type != null; type = type.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { if (HasIdentityConversionInternal(type, source)) { return true; } } } // SPEC: From any interface type to T. if ((object)t != null && source.IsInterfaceType() && t.IsReferenceType) { return true; } // SPEC: From T to any interface-type I provided there is not already an implicit conversion from T to I. if ((object)s != null && s.IsReferenceType && destination.IsInterfaceType() && !HasImplicitReferenceTypeParameterConversion(s, destination, ref useSiteInfo)) { return true; } // SPEC: From a type parameter U to T, provided T depends on U (§10.1.5) if ((object)s != null && (object)t != null && t.IsReferenceType && t.DependsOn(s)) { return true; } return false; } // Spec 6.2.7 Explicit conversions involving type parameters private bool HasUnboxingTypeParameterConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); TypeParameterSymbol s = source as TypeParameterSymbol; TypeParameterSymbol t = destination as TypeParameterSymbol; // SPEC: The following explicit conversions exist for a given type parameter T: // SPEC: If T is known to be a reference type, the conversions are all classified as explicit reference conversions. // SPEC: If T is not known to be a reference type, the conversions are classified as unboxing conversions. // SPEC: From the effective base class C of T to T and from any base class of C to T. if ((object)t != null && !t.IsReferenceType) { for (var type = t.EffectiveBaseClass(ref useSiteInfo); (object)type != null; type = type.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { if (TypeSymbol.Equals(type, source, TypeCompareKind.ConsiderEverything2)) { return true; } } } // SPEC: From any interface type to T. if (source.IsInterfaceType() && (object)t != null && !t.IsReferenceType) { return true; } // SPEC: From T to any interface-type I provided there is not already an implicit conversion from T to I. if ((object)s != null && !s.IsReferenceType && destination.IsInterfaceType() && !HasImplicitReferenceTypeParameterConversion(s, destination, ref useSiteInfo)) { return true; } // SPEC: From a type parameter U to T, provided T depends on U (§10.1.5) if ((object)s != null && (object)t != null && !t.IsReferenceType && t.DependsOn(s)) { return true; } return false; } private bool HasExplicitDelegateConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // SPEC: From System.Delegate and the interfaces it implements to any delegate-type. // We also support System.MulticastDelegate in the implementation, in spite of it not being mentioned in the spec. if (destination.IsDelegateType()) { if (source.SpecialType == SpecialType.System_Delegate || source.SpecialType == SpecialType.System_MulticastDelegate) { return true; } if (HasImplicitConversionToInterface(this.corLibrary.GetDeclaredSpecialType(SpecialType.System_Delegate), source, ref useSiteInfo)) { return true; } } // SPEC: From D<S1...Sn> to a D<T1...Tn> where D<X1...Xn> is a generic delegate type, D<S1...Sn> is not compatible with or identical to D<T1...Tn>, // SPEC: and for each type parameter Xi of D the following holds: // SPEC: If Xi is invariant, then Si is identical to Ti. // SPEC: If Xi is covariant, then there is an implicit or explicit identity or reference conversion from Si to Ti. // SPECL If Xi is contravariant, then Si and Ti are either identical or both reference types. if (!source.IsDelegateType() || !destination.IsDelegateType()) { return false; } if (!TypeSymbol.Equals(source.OriginalDefinition, destination.OriginalDefinition, TypeCompareKind.ConsiderEverything2)) { return false; } var sourceType = (NamedTypeSymbol)source; var destinationType = (NamedTypeSymbol)destination; var original = sourceType.OriginalDefinition; if (HasIdentityConversionInternal(source, destination)) { return false; } if (HasDelegateVarianceConversion(source, destination, ref useSiteInfo)) { return false; } var sourceTypeArguments = sourceType.TypeArgumentsWithDefinitionUseSiteDiagnostics(ref useSiteInfo); var destinationTypeArguments = destinationType.TypeArgumentsWithDefinitionUseSiteDiagnostics(ref useSiteInfo); for (int i = 0; i < sourceTypeArguments.Length; ++i) { var sourceArg = sourceTypeArguments[i].Type; var destinationArg = destinationTypeArguments[i].Type; switch (original.TypeParameters[i].Variance) { case VarianceKind.None: if (!HasIdentityConversionInternal(sourceArg, destinationArg)) { return false; } break; case VarianceKind.Out: if (!HasIdentityOrReferenceConversion(sourceArg, destinationArg, ref useSiteInfo)) { return false; } break; case VarianceKind.In: bool hasIdentityConversion = HasIdentityConversionInternal(sourceArg, destinationArg); bool bothAreReferenceTypes = sourceArg.IsReferenceType && destinationArg.IsReferenceType; if (!(hasIdentityConversion || bothAreReferenceTypes)) { return false; } break; } } return true; } private bool HasExplicitArrayConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); var sourceArray = source as ArrayTypeSymbol; var destinationArray = destination as ArrayTypeSymbol; // SPEC: From an array-type S with an element type SE to an array-type T with an element type TE, provided all of the following are true: // SPEC: S and T differ only in element type. (In other words, S and T have the same number of dimensions.) // SPEC: Both SE and TE are reference-types. // SPEC: An explicit reference conversion exists from SE to TE. if ((object)sourceArray != null && (object)destinationArray != null) { // HasExplicitReferenceConversion checks that SE and TE are reference types so // there's no need for that check here. Moreover, it's not as simple as checking // IsReferenceType, at least not in the case of type parameters, since SE will be // considered a reference type implicitly in the case of "where TE : class, SE" even // though SE.IsReferenceType may be false. Again, HasExplicitReferenceConversion // already handles these cases. return sourceArray.HasSameShapeAs(destinationArray) && HasExplicitReferenceConversion(sourceArray.ElementType, destinationArray.ElementType, ref useSiteInfo); } // SPEC: From System.Array and the interfaces it implements to any array-type. if ((object)destinationArray != null) { if (source.SpecialType == SpecialType.System_Array) { return true; } foreach (var iface in this.corLibrary.GetDeclaredSpecialType(SpecialType.System_Array).AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { if (HasIdentityConversionInternal(iface, source)) { return true; } } } // SPEC: From a single-dimensional array type S[] to System.Collections.Generic.IList<T> and its base interfaces // SPEC: provided that there is an explicit reference conversion from S to T. // The framework now also allows arrays to be converted to IReadOnlyList<T> and IReadOnlyCollection<T>; we // honor that as well. if ((object)sourceArray != null && sourceArray.IsSZArray && destination.IsPossibleArrayGenericInterface()) { if (HasExplicitReferenceConversion(sourceArray.ElementType, ((NamedTypeSymbol)destination).TypeArgumentWithDefinitionUseSiteDiagnostics(0, ref useSiteInfo).Type, ref useSiteInfo)) { return true; } } // SPEC: From System.Collections.Generic.IList<S> and its base interfaces to a single-dimensional array type T[], // provided that there is an explicit identity or reference conversion from S to T. // Similarly, we honor IReadOnlyList<S> and IReadOnlyCollection<S> in the same way. if ((object)destinationArray != null && destinationArray.IsSZArray) { var specialDefinition = ((TypeSymbol)source.OriginalDefinition).SpecialType; if (specialDefinition == SpecialType.System_Collections_Generic_IList_T || specialDefinition == SpecialType.System_Collections_Generic_ICollection_T || specialDefinition == SpecialType.System_Collections_Generic_IEnumerable_T || specialDefinition == SpecialType.System_Collections_Generic_IReadOnlyList_T || specialDefinition == SpecialType.System_Collections_Generic_IReadOnlyCollection_T) { var sourceElement = ((NamedTypeSymbol)source).TypeArgumentWithDefinitionUseSiteDiagnostics(0, ref useSiteInfo).Type; var destinationElement = destinationArray.ElementType; if (HasIdentityConversionInternal(sourceElement, destinationElement)) { return true; } if (HasImplicitReferenceConversion(sourceElement, destinationElement, ref useSiteInfo)) { return true; } if (HasExplicitReferenceConversion(sourceElement, destinationElement, ref useSiteInfo)) { return true; } } } return false; } private bool HasUnboxingConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (destination.IsPointerOrFunctionPointer()) { return false; } // Ref-like types cannot be boxed or unboxed if (destination.IsRestrictedType()) { return false; } // SPEC: An unboxing conversion permits a reference type to be explicitly converted to a value-type. // SPEC: An unboxing conversion exists from the types object and System.ValueType to any non-nullable-value-type, var specialTypeSource = source.SpecialType; if (specialTypeSource == SpecialType.System_Object || specialTypeSource == SpecialType.System_ValueType) { if (destination.IsValueType && !destination.IsNullableType()) { return true; } } // SPEC: and from any interface-type to any non-nullable-value-type that implements the interface-type. if (source.IsInterfaceType() && destination.IsValueType && !destination.IsNullableType() && HasBoxingConversion(destination, source, ref useSiteInfo)) { return true; } // SPEC: Furthermore type System.Enum can be unboxed to any enum-type. if (source.SpecialType == SpecialType.System_Enum && destination.IsEnumType()) { return true; } // SPEC: An unboxing conversion exists from a reference type to a nullable-type if an unboxing // SPEC: conversion exists from the reference type to the underlying non-nullable-value-type // SPEC: of the nullable-type. if (source.IsReferenceType && destination.IsNullableType() && HasUnboxingConversion(source, destination.GetNullableUnderlyingType(), ref useSiteInfo)) { return true; } // SPEC: UNDONE A value type S has an unboxing conversion from an interface type I if it has an unboxing // SPEC: UNDONE conversion from an interface type I0 and I0 has an identity conversion to I. // SPEC: UNDONE A value type S has an unboxing conversion from an interface type I if it has an unboxing conversion // SPEC: UNDONE from an interface or delegate type I0 and either I0 is variance-convertible to I or I is variance-convertible to I0. if (HasUnboxingTypeParameterConversion(source, destination, ref useSiteInfo)) { return true; } return false; } private static bool HasPointerToPointerConversion(TypeSymbol source, TypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); return source.IsPointerOrFunctionPointer() && destination.IsPointerOrFunctionPointer(); } private static bool HasPointerToIntegerConversion(TypeSymbol source, TypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (!source.IsPointerOrFunctionPointer()) { return false; } // SPEC OMISSION: // // The spec should state that any pointer type is convertible to // sbyte, byte, ... etc, or any corresponding nullable type. return IsIntegerTypeSupportingPointerConversions(destination.StrippedType()); } private static bool HasIntegerToPointerConversion(TypeSymbol source, TypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (!destination.IsPointerOrFunctionPointer()) { return false; } // Note that void* is convertible to int?, but int? is not convertible to void*. return IsIntegerTypeSupportingPointerConversions(source); } private static bool IsIntegerTypeSupportingPointerConversions(TypeSymbol type) { switch (type.SpecialType) { case SpecialType.System_SByte: case SpecialType.System_Byte: case SpecialType.System_Int16: case SpecialType.System_UInt16: case SpecialType.System_Int32: case SpecialType.System_UInt32: case SpecialType.System_Int64: case SpecialType.System_UInt64: return true; case SpecialType.System_IntPtr: case SpecialType.System_UIntPtr: return type.IsNativeIntegerType; } return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal abstract partial class ConversionsBase { private const int MaximumRecursionDepth = 50; protected readonly AssemblySymbol corLibrary; protected readonly int currentRecursionDepth; internal readonly bool IncludeNullability; /// <summary> /// An optional clone of this instance with distinct IncludeNullability. /// Used to avoid unnecessary allocations when calling WithNullability() repeatedly. /// </summary> private ConversionsBase _lazyOtherNullability; protected ConversionsBase(AssemblySymbol corLibrary, int currentRecursionDepth, bool includeNullability, ConversionsBase otherNullabilityOpt) { Debug.Assert((object)corLibrary != null); Debug.Assert(otherNullabilityOpt == null || includeNullability != otherNullabilityOpt.IncludeNullability); Debug.Assert(otherNullabilityOpt == null || currentRecursionDepth == otherNullabilityOpt.currentRecursionDepth); this.corLibrary = corLibrary; this.currentRecursionDepth = currentRecursionDepth; IncludeNullability = includeNullability; _lazyOtherNullability = otherNullabilityOpt; } /// <summary> /// Returns this instance if includeNullability is correct, and returns a /// cached clone of this instance with distinct IncludeNullability otherwise. /// </summary> internal ConversionsBase WithNullability(bool includeNullability) { if (IncludeNullability == includeNullability) { return this; } if (_lazyOtherNullability == null) { Interlocked.CompareExchange(ref _lazyOtherNullability, WithNullabilityCore(includeNullability), null); } Debug.Assert(_lazyOtherNullability.IncludeNullability == includeNullability); Debug.Assert(_lazyOtherNullability._lazyOtherNullability == this); return _lazyOtherNullability; } protected abstract ConversionsBase WithNullabilityCore(bool includeNullability); public abstract Conversion GetMethodGroupDelegateConversion(BoundMethodGroup source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo); public abstract Conversion GetMethodGroupFunctionPointerConversion(BoundMethodGroup source, FunctionPointerTypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo); public abstract Conversion GetStackAllocConversion(BoundStackAllocArrayCreation sourceExpression, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo); protected abstract ConversionsBase CreateInstance(int currentRecursionDepth); protected abstract Conversion GetInterpolatedStringConversion(BoundExpression source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo); internal AssemblySymbol CorLibrary { get { return corLibrary; } } #nullable enable /// <summary> /// Determines if the source expression is convertible to the destination type via /// any built-in or user-defined implicit conversion. /// </summary> public Conversion ClassifyImplicitConversionFromExpression(BoundExpression sourceExpression, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(sourceExpression != null); Debug.Assert((object)destination != null); var sourceType = sourceExpression.Type; //PERF: identity conversion is by far the most common implicit conversion, check for that first if (sourceType is { } && HasIdentityConversionInternal(sourceType, destination)) { return Conversion.Identity; } Conversion conversion = ClassifyImplicitBuiltInConversionFromExpression(sourceExpression, sourceType, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } if (sourceType is { }) { // Try using the short-circuit "fast-conversion" path. Conversion fastConversion = FastClassifyConversion(sourceType, destination); if (fastConversion.Exists) { if (fastConversion.IsImplicit) { return fastConversion; } } else { conversion = ClassifyImplicitBuiltInConversionSlow(sourceType, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } } } else if (sourceExpression.GetFunctionType() is { } sourceFunctionType) { if (HasImplicitFunctionTypeConversion(sourceFunctionType, destination, ref useSiteInfo)) { return Conversion.FunctionType; } } conversion = GetImplicitUserDefinedConversion(sourceExpression, sourceType, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } // The switch expression conversion is "lowest priority", so that if there is a conversion from the expression's // type it will be preferred over the switch expression conversion. Technically, we would want the language // specification to say that the switch expression conversion only "exists" if there is no implicit conversion // from the type, and we accomplish that by making it lowest priority. The same is true for the conditional // expression conversion. conversion = GetSwitchExpressionConversion(sourceExpression, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } return GetConditionalExpressionConversion(sourceExpression, destination, ref useSiteInfo); } /// <summary> /// Determines if the source type is convertible to the destination type via /// any built-in or user-defined implicit conversion. /// </summary> public Conversion ClassifyImplicitConversionFromType(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); //PERF: identity conversions are very common, check for that first. if (HasIdentityConversionInternal(source, destination)) { return Conversion.Identity; } // Try using the short-circuit "fast-conversion" path. Conversion fastConversion = FastClassifyConversion(source, destination); if (fastConversion.Exists) { return fastConversion.IsImplicit ? fastConversion : Conversion.NoConversion; } else { Conversion conversion = ClassifyImplicitBuiltInConversionSlow(source, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } } return GetImplicitUserDefinedConversion(null, source, destination, ref useSiteInfo); } /// <summary> /// Helper method that calls <see cref="ClassifyImplicitConversionFromType"/> or /// <see cref="HasImplicitFunctionTypeToFunctionTypeConversion"/> depending on whether the /// types are <see cref="FunctionTypeSymbol"/> instances. /// Used by method type inference and best common type only. /// </summary> public Conversion ClassifyImplicitConversionFromTypeWhenNeitherOrBothFunctionTypes(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var sourceFunctionType = source as FunctionTypeSymbol; var destinationFunctionType = destination as FunctionTypeSymbol; if (sourceFunctionType is null && destinationFunctionType is null) { return ClassifyImplicitConversionFromType(source, destination, ref useSiteInfo); } if (sourceFunctionType is { } && destinationFunctionType is { }) { return HasImplicitFunctionTypeToFunctionTypeConversion(sourceFunctionType, destinationFunctionType, ref useSiteInfo) ? Conversion.FunctionType : Conversion.NoConversion; } Debug.Assert(false); return Conversion.NoConversion; } #nullable disable /// <summary> /// Determines if the source expression of given type is convertible to the destination type via /// any built-in or user-defined conversion. /// /// This helper is used in rare cases involving synthesized expressions where we know the type of an expression, but do not have the actual expression. /// The reason for this helper (as opposed to ClassifyConversionFromType) is that conversions from expressions could be different /// from conversions from type. For example expressions of dynamic type are implicitly convertable to any type, while dynamic type itself is not. /// </summary> public Conversion ClassifyConversionFromExpressionType(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // since we are converting from expression, we may have implicit dynamic conversion if (HasImplicitDynamicConversionFromExpression(source, destination)) { return Conversion.ImplicitDynamic; } return ClassifyConversionFromType(source, destination, ref useSiteInfo); } private static bool TryGetVoidConversion(TypeSymbol source, TypeSymbol destination, out Conversion conversion) { var sourceIsVoid = source?.SpecialType == SpecialType.System_Void; var destIsVoid = destination.SpecialType == SpecialType.System_Void; // 'void' is not supposed to be able to convert to or from anything, but in practice, // a lot of code depends on checking whether an expression of type 'void' is convertible to 'void'. // (e.g. for an expression lambda which returns void). // Therefore we allow an identity conversion between 'void' and 'void'. if (sourceIsVoid && destIsVoid) { conversion = Conversion.Identity; return true; } // If exactly one of source or destination is of type 'void' then no conversion may exist. if (sourceIsVoid || destIsVoid) { conversion = Conversion.NoConversion; return true; } conversion = default; return false; } /// <summary> /// Determines if the source expression is convertible to the destination type via /// any conversion: implicit, explicit, user-defined or built-in. /// </summary> /// <remarks> /// It is rare but possible for a source expression to be convertible to a destination type /// by both an implicit user-defined conversion and a built-in explicit conversion. /// In that circumstance, this method classifies the conversion as the implicit conversion or explicit depending on "forCast" /// </remarks> public Conversion ClassifyConversionFromExpression(BoundExpression sourceExpression, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool forCast = false) { Debug.Assert(sourceExpression != null); Debug.Assert((object)destination != null); if (TryGetVoidConversion(sourceExpression.Type, destination, out var conversion)) { return conversion; } if (forCast) { return ClassifyConversionFromExpressionForCast(sourceExpression, destination, ref useSiteInfo); } var result = ClassifyImplicitConversionFromExpression(sourceExpression, destination, ref useSiteInfo); if (result.Exists) { return result; } return ClassifyExplicitOnlyConversionFromExpression(sourceExpression, destination, ref useSiteInfo, forCast: false); } /// <summary> /// Determines if the source type is convertible to the destination type via /// any conversion: implicit, explicit, user-defined or built-in. /// </summary> /// <remarks> /// It is rare but possible for a source type to be convertible to a destination type /// by both an implicit user-defined conversion and a built-in explicit conversion. /// In that circumstance, this method classifies the conversion as the implicit conversion or explicit depending on "forCast" /// </remarks> public Conversion ClassifyConversionFromType(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool forCast = false) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (TryGetVoidConversion(source, destination, out var voidConversion)) { return voidConversion; } if (forCast) { return ClassifyConversionFromTypeForCast(source, destination, ref useSiteInfo); } // Try using the short-circuit "fast-conversion" path. Conversion fastConversion = FastClassifyConversion(source, destination); if (fastConversion.Exists) { return fastConversion; } else { Conversion conversion1 = ClassifyImplicitBuiltInConversionSlow(source, destination, ref useSiteInfo); if (conversion1.Exists) { return conversion1; } } Conversion conversion = GetImplicitUserDefinedConversion(null, source, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } conversion = ClassifyExplicitBuiltInOnlyConversion(source, destination, ref useSiteInfo, forCast: false); if (conversion.Exists) { return conversion; } return GetExplicitUserDefinedConversion(null, source, destination, ref useSiteInfo); } /// <summary> /// Determines if the source expression is convertible to the destination type via /// any conversion: implicit, explicit, user-defined or built-in. /// </summary> /// <remarks> /// It is rare but possible for a source expression to be convertible to a destination type /// by both an implicit user-defined conversion and a built-in explicit conversion. /// In that circumstance, this method classifies the conversion as the built-in conversion. /// /// An implicit conversion exists from an expression of a dynamic type to any type. /// An explicit conversion exists from a dynamic type to any type. /// When casting we prefer the explicit conversion. /// </remarks> private Conversion ClassifyConversionFromExpressionForCast(BoundExpression source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source != null); Debug.Assert((object)destination != null); Conversion implicitConversion = ClassifyImplicitConversionFromExpression(source, destination, ref useSiteInfo); if (implicitConversion.Exists && !ExplicitConversionMayDifferFromImplicit(implicitConversion)) { return implicitConversion; } Conversion explicitConversion = ClassifyExplicitOnlyConversionFromExpression(source, destination, ref useSiteInfo, forCast: true); if (explicitConversion.Exists) { return explicitConversion; } // It is possible for a user-defined conversion to be unambiguous when considered as // an implicit conversion and ambiguous when considered as an explicit conversion. // The native compiler does not check to see if a cast could be successfully bound as // an unambiguous user-defined implicit conversion; it goes right to the ambiguous // user-defined explicit conversion and produces an error. This means that in // C# 5 it is possible to have: // // Y y = new Y(); // Z z1 = y; // // succeed but // // Z z2 = (Z)y; // // fail. // // However, there is another interesting wrinkle. It is possible for both // an implicit user-defined conversion and an explicit user-defined conversion // to exist and be unambiguous. For example, if there is an implicit conversion // double-->C and an explicit conversion from int-->C, and the user casts a short // to C, then both the implicit and explicit conversions are applicable and // unambiguous. The native compiler in this case prefers the explicit conversion, // and for backwards compatibility, we match it. return implicitConversion; } /// <summary> /// Determines if the source type is convertible to the destination type via /// any conversion: implicit, explicit, user-defined or built-in. /// </summary> /// <remarks> /// It is rare but possible for a source type to be convertible to a destination type /// by both an implicit user-defined conversion and a built-in explicit conversion. /// In that circumstance, this method classifies the conversion as the built-in conversion. /// </remarks> private Conversion ClassifyConversionFromTypeForCast(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // Try using the short-circuit "fast-conversion" path. Conversion fastConversion = FastClassifyConversion(source, destination); if (fastConversion.Exists) { return fastConversion; } Conversion implicitBuiltInConversion = ClassifyImplicitBuiltInConversionSlow(source, destination, ref useSiteInfo); if (implicitBuiltInConversion.Exists && !ExplicitConversionMayDifferFromImplicit(implicitBuiltInConversion)) { return implicitBuiltInConversion; } Conversion explicitBuiltInConversion = ClassifyExplicitBuiltInOnlyConversion(source, destination, ref useSiteInfo, forCast: true); if (explicitBuiltInConversion.Exists) { return explicitBuiltInConversion; } if (implicitBuiltInConversion.Exists) { return implicitBuiltInConversion; } // It is possible for a user-defined conversion to be unambiguous when considered as // an implicit conversion and ambiguous when considered as an explicit conversion. // The native compiler does not check to see if a cast could be successfully bound as // an unambiguous user-defined implicit conversion; it goes right to the ambiguous // user-defined explicit conversion and produces an error. This means that in // C# 5 it is possible to have: // // Y y = new Y(); // Z z1 = y; // // succeed but // // Z z2 = (Z)y; // // fail. var conversion = GetExplicitUserDefinedConversion(null, source, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } return GetImplicitUserDefinedConversion(null, source, destination, ref useSiteInfo); } /// <summary> /// Attempt a quick classification of builtin conversions. As result of "no conversion" /// means that there is no built-in conversion, though there still may be a user-defined /// conversion if compiling against a custom mscorlib. /// </summary> public static Conversion FastClassifyConversion(TypeSymbol source, TypeSymbol target) { ConversionKind convKind = ConversionEasyOut.ClassifyConversion(source, target); if (convKind != ConversionKind.ImplicitNullable && convKind != ConversionKind.ExplicitNullable) { return Conversion.GetTrivialConversion(convKind); } return Conversion.MakeNullableConversion(convKind, FastClassifyConversion(source.StrippedType(), target.StrippedType())); } public Conversion ClassifyBuiltInConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // Try using the short-circuit "fast-conversion" path. Conversion fastConversion = FastClassifyConversion(source, destination); if (fastConversion.Exists) { return fastConversion; } else { Conversion conversion = ClassifyImplicitBuiltInConversionSlow(source, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } } return ClassifyExplicitBuiltInOnlyConversion(source, destination, ref useSiteInfo, forCast: false); } /// <summary> /// Determines if the source type is convertible to the destination type via /// any standard implicit or standard explicit conversion. /// </summary> /// <remarks> /// Not all built-in explicit conversions are standard explicit conversions. /// </remarks> public Conversion ClassifyStandardConversion(BoundExpression sourceExpression, TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(sourceExpression != null || (object)source != null); Debug.Assert((object)destination != null); // Note that the definition of explicit standard conversion does not include all explicit // reference conversions! There is a standard implicit reference conversion from // Action<Object> to Action<Exception>, thanks to contravariance. There is a standard // implicit reference conversion from Action<Object> to Action<String> for the same reason. // Therefore there is an explicit reference conversion from Action<Exception> to // Action<String>; a given Action<Exception> might be an Action<Object>, and hence // convertible to Action<String>. However, this is not a *standard* explicit conversion. The // standard explicit conversions are all the standard implicit conversions and their // opposites. Therefore Action<Object>-->Action<String> and Action<String>-->Action<Object> // are both standard conversions. But Action<String>-->Action<Exception> is not a standard // explicit conversion because neither it nor its opposite is a standard implicit // conversion. // // Similarly, there is no standard explicit conversion from double to decimal, because // there is no standard implicit conversion between the two types. // SPEC: The standard explicit conversions are all standard implicit conversions plus // SPEC: the subset of the explicit conversions for which an opposite standard implicit // SPEC: conversion exists. In other words, if a standard implicit conversion exists from // SPEC: a type A to a type B, then a standard explicit conversion exists from type A to // SPEC: type B and from type B to type A. Conversion conversion = ClassifyStandardImplicitConversion(sourceExpression, source, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } if ((object)source != null) { return DeriveStandardExplicitFromOppositeStandardImplicitConversion(source, destination, ref useSiteInfo); } return Conversion.NoConversion; } private static bool IsStandardImplicitConversionFromExpression(ConversionKind kind) { if (IsStandardImplicitConversionFromType(kind)) { return true; } // See comment in ClassifyStandardImplicitConversion(BoundExpression, ...) // where the set of standard implicit conversions is extended from the spec // to include conversions from expression. switch (kind) { case ConversionKind.AnonymousFunction: case ConversionKind.MethodGroup: case ConversionKind.ImplicitEnumeration: case ConversionKind.ImplicitDynamic: case ConversionKind.ImplicitNullToPointer: case ConversionKind.ImplicitTupleLiteral: case ConversionKind.StackAllocToPointerType: case ConversionKind.StackAllocToSpanType: return true; default: return false; } } // See https://github.com/dotnet/csharplang/blob/main/spec/conversions.md#standard-conversions: // "The standard conversions are those pre-defined conversions that can occur as part of a user-defined conversion." private static bool IsStandardImplicitConversionFromType(ConversionKind kind) { switch (kind) { case ConversionKind.Identity: case ConversionKind.ImplicitNumeric: case ConversionKind.ImplicitNullable: case ConversionKind.ImplicitReference: case ConversionKind.Boxing: case ConversionKind.ImplicitConstant: case ConversionKind.ImplicitPointer: case ConversionKind.ImplicitPointerToVoid: case ConversionKind.ImplicitTuple: return true; default: return false; } } private Conversion ClassifyStandardImplicitConversion(BoundExpression sourceExpression, TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(sourceExpression != null || (object)source != null); Debug.Assert(sourceExpression == null || (object)sourceExpression.Type == (object)source); Debug.Assert((object)destination != null); // SPEC: The following implicit conversions are classified as standard implicit conversions: // SPEC: Identity conversions // SPEC: Implicit numeric conversions // SPEC: Implicit nullable conversions // SPEC: Implicit reference conversions // SPEC: Boxing conversions // SPEC: Implicit constant expression conversions // SPEC: Implicit conversions involving type parameters // // and in unsafe code: // // SPEC: From any pointer type to void* // // SPEC ERROR: // The specification does not say to take into account the conversion from // the *expression*, only its *type*. But the expression may not have a type // (because it is null, a method group, or a lambda), or the expression might // be convertible to the destination type via a constant numeric conversion. // For example, the native compiler allows "C c = 1;" to work if C is a class which // has an implicit conversion from byte to C, despite the fact that there is // obviously no standard implicit conversion from *int* to *byte*. // Similarly, if a struct S has an implicit conversion from string to S, then // "S s = null;" should be allowed. // // We extend the definition of standard implicit conversions to include // all of the implicit conversions that are allowed based on an expression, // with the exception of the switch expression conversion. Conversion conversion = ClassifyImplicitBuiltInConversionFromExpression(sourceExpression, source, destination, ref useSiteInfo); if (conversion.Exists) { Debug.Assert(IsStandardImplicitConversionFromExpression(conversion.Kind)); return conversion; } if ((object)source != null) { return ClassifyStandardImplicitConversion(source, destination, ref useSiteInfo); } return Conversion.NoConversion; } private Conversion ClassifyStandardImplicitConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var conversion = classifyConversion(source, destination, ref useSiteInfo); Debug.Assert(conversion.Kind == ConversionKind.NoConversion || IsStandardImplicitConversionFromType(conversion.Kind)); return conversion; Conversion classifyConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (HasIdentityConversionInternal(source, destination)) { return Conversion.Identity; } if (HasImplicitNumericConversion(source, destination)) { return Conversion.ImplicitNumeric; } var nullableConversion = ClassifyImplicitNullableConversion(source, destination, ref useSiteInfo); if (nullableConversion.Exists) { return nullableConversion; } if (source is FunctionTypeSymbol) { Debug.Assert(false); return Conversion.NoConversion; } if (HasImplicitReferenceConversion(source, destination, ref useSiteInfo)) { return Conversion.ImplicitReference; } if (HasBoxingConversion(source, destination, ref useSiteInfo)) { return Conversion.Boxing; } if (HasImplicitPointerToVoidConversion(source, destination)) { return Conversion.PointerToVoid; } if (HasImplicitPointerConversion(source, destination, ref useSiteInfo)) { return Conversion.ImplicitPointer; } var tupleConversion = ClassifyImplicitTupleConversion(source, destination, ref useSiteInfo); if (tupleConversion.Exists) { return tupleConversion; } return Conversion.NoConversion; } } private Conversion ClassifyImplicitBuiltInConversionSlow(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (source.IsVoidType() || destination.IsVoidType()) { return Conversion.NoConversion; } Conversion conversion = ClassifyStandardImplicitConversion(source, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } return Conversion.NoConversion; } private Conversion GetImplicitUserDefinedConversion(BoundExpression sourceExpression, TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var conversionResult = AnalyzeImplicitUserDefinedConversions(sourceExpression, source, destination, ref useSiteInfo); return new Conversion(conversionResult, isImplicit: true); } private Conversion ClassifyExplicitBuiltInOnlyConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool forCast) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (source.IsVoidType() || destination.IsVoidType()) { return Conversion.NoConversion; } // The call to HasExplicitNumericConversion isn't necessary, because it is always tested // already by the "FastConversion" code. Debug.Assert(!HasExplicitNumericConversion(source, destination)); //if (HasExplicitNumericConversion(source, specialTypeSource, destination, specialTypeDest)) //{ // return Conversion.ExplicitNumeric; //} if (HasSpecialIntPtrConversion(source, destination)) { return Conversion.IntPtr; } if (HasExplicitEnumerationConversion(source, destination)) { return Conversion.ExplicitEnumeration; } var nullableConversion = ClassifyExplicitNullableConversion(source, destination, ref useSiteInfo, forCast); if (nullableConversion.Exists) { return nullableConversion; } if (HasExplicitReferenceConversion(source, destination, ref useSiteInfo)) { return (source.Kind == SymbolKind.DynamicType) ? Conversion.ExplicitDynamic : Conversion.ExplicitReference; } if (HasUnboxingConversion(source, destination, ref useSiteInfo)) { return Conversion.Unboxing; } var tupleConversion = ClassifyExplicitTupleConversion(source, destination, ref useSiteInfo, forCast); if (tupleConversion.Exists) { return tupleConversion; } if (HasPointerToPointerConversion(source, destination)) { return Conversion.PointerToPointer; } if (HasPointerToIntegerConversion(source, destination)) { return Conversion.PointerToInteger; } if (HasIntegerToPointerConversion(source, destination)) { return Conversion.IntegerToPointer; } if (HasExplicitDynamicConversion(source, destination)) { return Conversion.ExplicitDynamic; } return Conversion.NoConversion; } private Conversion GetExplicitUserDefinedConversion(BoundExpression sourceExpression, TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { UserDefinedConversionResult conversionResult = AnalyzeExplicitUserDefinedConversions(sourceExpression, source, destination, ref useSiteInfo); return new Conversion(conversionResult, isImplicit: false); } private Conversion DeriveStandardExplicitFromOppositeStandardImplicitConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var oppositeConversion = ClassifyStandardImplicitConversion(destination, source, ref useSiteInfo); Conversion impliedExplicitConversion; switch (oppositeConversion.Kind) { case ConversionKind.Identity: impliedExplicitConversion = Conversion.Identity; break; case ConversionKind.ImplicitNumeric: impliedExplicitConversion = Conversion.ExplicitNumeric; break; case ConversionKind.ImplicitReference: impliedExplicitConversion = Conversion.ExplicitReference; break; case ConversionKind.Boxing: impliedExplicitConversion = Conversion.Unboxing; break; case ConversionKind.NoConversion: impliedExplicitConversion = Conversion.NoConversion; break; case ConversionKind.ImplicitPointerToVoid: impliedExplicitConversion = Conversion.PointerToPointer; break; case ConversionKind.ImplicitTuple: // only implicit tuple conversions are standard conversions, // having implicit conversion in the other direction does not help here. impliedExplicitConversion = Conversion.NoConversion; break; case ConversionKind.ImplicitNullable: var strippedSource = source.StrippedType(); var strippedDestination = destination.StrippedType(); var underlyingConversion = DeriveStandardExplicitFromOppositeStandardImplicitConversion(strippedSource, strippedDestination, ref useSiteInfo); // the opposite underlying conversion may not exist // for example if underlying conversion is implicit tuple impliedExplicitConversion = underlyingConversion.Exists ? Conversion.MakeNullableConversion(ConversionKind.ExplicitNullable, underlyingConversion) : Conversion.NoConversion; break; default: throw ExceptionUtilities.UnexpectedValue(oppositeConversion.Kind); } return impliedExplicitConversion; } #nullable enable /// <summary> /// IsBaseInterface returns true if baseType is on the base interface list of derivedType or /// any base class of derivedType. It may be on the base interface list either directly or /// indirectly. /// * baseType must be an interface. /// * type parameters do not have base interfaces. (They have an "effective interface list".) /// * an interface is not a base of itself. /// * this does not check for variance conversions; if a type inherits from /// IEnumerable&lt;string> then IEnumerable&lt;object> is not a base interface. /// </summary> public bool IsBaseInterface(TypeSymbol baseType, TypeSymbol derivedType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)baseType != null); Debug.Assert((object)derivedType != null); if (!baseType.IsInterfaceType()) { return false; } var d = derivedType as NamedTypeSymbol; if (d is null) { return false; } foreach (var iface in d.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { if (HasIdentityConversionInternal(iface, baseType)) { return true; } } return false; } // IsBaseClass returns true if and only if baseType is a base class of derivedType, period. // // * interfaces do not have base classes. (Structs, enums and classes other than object do.) // * a class is not a base class of itself // * type parameters do not have base classes. (They have "effective base classes".) // * all base classes must be classes // * dynamics are removed; if we have class D : B<dynamic> then B<object> is a // base class of D. However, dynamic is never a base class of anything. public bool IsBaseClass(TypeSymbol derivedType, TypeSymbol baseType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)derivedType != null); Debug.Assert((object)baseType != null); // A base class has got to be a class. The derived type might be a struct, enum, or delegate. if (!baseType.IsClassType()) { return false; } for (TypeSymbol b = derivedType.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); (object)b != null; b = b.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { if (HasIdentityConversionInternal(b, baseType)) { return true; } } return false; } /// <summary> /// returns true when implicit conversion is not necessarily the same as explicit conversion /// </summary> private static bool ExplicitConversionMayDifferFromImplicit(Conversion implicitConversion) { switch (implicitConversion.Kind) { case ConversionKind.ImplicitUserDefined: case ConversionKind.ImplicitDynamic: case ConversionKind.ImplicitTuple: case ConversionKind.ImplicitTupleLiteral: case ConversionKind.ImplicitNullable: case ConversionKind.ConditionalExpression: return true; default: return false; } } #nullable disable private Conversion ClassifyImplicitBuiltInConversionFromExpression(BoundExpression sourceExpression, TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(sourceExpression != null || (object)source != null); Debug.Assert(sourceExpression == null || (object)sourceExpression.Type == (object)source); Debug.Assert((object)destination != null); if (HasImplicitDynamicConversionFromExpression(source, destination)) { return Conversion.ImplicitDynamic; } // The following conversions only exist for certain form of expressions, // if we have no expression none if them is applicable. if (sourceExpression == null) { return Conversion.NoConversion; } if (HasImplicitEnumerationConversion(sourceExpression, destination)) { return Conversion.ImplicitEnumeration; } var constantConversion = ClassifyImplicitConstantExpressionConversion(sourceExpression, destination); if (constantConversion.Exists) { return constantConversion; } switch (sourceExpression.Kind) { case BoundKind.Literal: var nullLiteralConversion = ClassifyNullLiteralConversion(sourceExpression, destination); if (nullLiteralConversion.Exists) { return nullLiteralConversion; } break; case BoundKind.DefaultLiteral: return Conversion.DefaultLiteral; case BoundKind.ExpressionWithNullability: { var innerExpression = ((BoundExpressionWithNullability)sourceExpression).Expression; var innerConversion = ClassifyImplicitBuiltInConversionFromExpression(innerExpression, innerExpression.Type, destination, ref useSiteInfo); if (innerConversion.Exists) { return innerConversion; } break; } case BoundKind.TupleLiteral: var tupleConversion = ClassifyImplicitTupleLiteralConversion((BoundTupleLiteral)sourceExpression, destination, ref useSiteInfo); if (tupleConversion.Exists) { return tupleConversion; } break; case BoundKind.UnboundLambda: if (HasAnonymousFunctionConversion(sourceExpression, destination)) { return Conversion.AnonymousFunction; } break; case BoundKind.MethodGroup: Conversion methodGroupConversion = GetMethodGroupDelegateConversion((BoundMethodGroup)sourceExpression, destination, ref useSiteInfo); if (methodGroupConversion.Exists) { return methodGroupConversion; } break; case BoundKind.UnconvertedInterpolatedString: case BoundKind.BinaryOperator when ((BoundBinaryOperator)sourceExpression).IsUnconvertedInterpolatedStringAddition: Conversion interpolatedStringConversion = GetInterpolatedStringConversion(sourceExpression, destination, ref useSiteInfo); if (interpolatedStringConversion.Exists) { return interpolatedStringConversion; } break; case BoundKind.StackAllocArrayCreation: var stackAllocConversion = GetStackAllocConversion((BoundStackAllocArrayCreation)sourceExpression, destination, ref useSiteInfo); if (stackAllocConversion.Exists) { return stackAllocConversion; } break; case BoundKind.UnconvertedAddressOfOperator when destination is FunctionPointerTypeSymbol funcPtrType: var addressOfConversion = GetMethodGroupFunctionPointerConversion(((BoundUnconvertedAddressOfOperator)sourceExpression).Operand, funcPtrType, ref useSiteInfo); if (addressOfConversion.Exists) { return addressOfConversion; } break; case BoundKind.ThrowExpression: return Conversion.ImplicitThrow; case BoundKind.UnconvertedObjectCreationExpression: return Conversion.ObjectCreation; } return Conversion.NoConversion; } private Conversion GetSwitchExpressionConversion(BoundExpression source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { switch (source) { case BoundConvertedSwitchExpression _: // It has already been subjected to a switch expression conversion. return Conversion.NoConversion; case BoundUnconvertedSwitchExpression switchExpression: var innerConversions = ArrayBuilder<Conversion>.GetInstance(switchExpression.SwitchArms.Length); foreach (var arm in switchExpression.SwitchArms) { var nestedConversion = this.ClassifyImplicitConversionFromExpression(arm.Value, destination, ref useSiteInfo); if (!nestedConversion.Exists) { innerConversions.Free(); return Conversion.NoConversion; } innerConversions.Add(nestedConversion); } return Conversion.MakeSwitchExpression(innerConversions.ToImmutableAndFree()); default: return Conversion.NoConversion; } } private Conversion GetConditionalExpressionConversion(BoundExpression source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (!(source is BoundUnconvertedConditionalOperator conditionalOperator)) return Conversion.NoConversion; var trueConversion = this.ClassifyImplicitConversionFromExpression(conditionalOperator.Consequence, destination, ref useSiteInfo); if (!trueConversion.Exists) return Conversion.NoConversion; var falseConversion = this.ClassifyImplicitConversionFromExpression(conditionalOperator.Alternative, destination, ref useSiteInfo); if (!falseConversion.Exists) return Conversion.NoConversion; return Conversion.MakeConditionalExpression(ImmutableArray.Create(trueConversion, falseConversion)); } private static Conversion ClassifyNullLiteralConversion(BoundExpression source, TypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (!source.IsLiteralNull()) { return Conversion.NoConversion; } // SPEC: An implicit conversion exists from the null literal to any nullable type. if (destination.IsNullableType()) { // The spec defines a "null literal conversion" specifically as a conversion from // null to nullable type. return Conversion.NullLiteral; } // SPEC: An implicit conversion exists from the null literal to any reference type. // SPEC: An implicit conversion exists from the null literal to type parameter T, // SPEC: provided T is known to be a reference type. [...] The conversion [is] classified // SPEC: as implicit reference conversion. if (destination.IsReferenceType) { return Conversion.ImplicitReference; } // SPEC: The set of implicit conversions is extended to include... // SPEC: ... from the null literal to any pointer type. if (destination.IsPointerOrFunctionPointer()) { return Conversion.NullToPointer; } return Conversion.NoConversion; } private static Conversion ClassifyImplicitConstantExpressionConversion(BoundExpression source, TypeSymbol destination) { if (HasImplicitConstantExpressionConversion(source, destination)) { return Conversion.ImplicitConstant; } // strip nullable from the destination // // the following should work and it is an ImplicitNullable conversion // int? x = 1; if (destination.Kind == SymbolKind.NamedType) { var nt = (NamedTypeSymbol)destination; if (nt.OriginalDefinition.GetSpecialTypeSafe() == SpecialType.System_Nullable_T && HasImplicitConstantExpressionConversion(source, nt.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].Type)) { return new Conversion(ConversionKind.ImplicitNullable, Conversion.ImplicitConstantUnderlying); } } return Conversion.NoConversion; } private Conversion ClassifyImplicitTupleLiteralConversion(BoundTupleLiteral source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var tupleConversion = GetImplicitTupleLiteralConversion(source, destination, ref useSiteInfo); if (tupleConversion.Exists) { return tupleConversion; } // strip nullable from the destination // // the following should work and it is an ImplicitNullable conversion // (int, double)? x = (1,2); if (destination.Kind == SymbolKind.NamedType) { var nt = (NamedTypeSymbol)destination; if (nt.OriginalDefinition.GetSpecialTypeSafe() == SpecialType.System_Nullable_T) { var underlyingTupleConversion = GetImplicitTupleLiteralConversion(source, nt.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].Type, ref useSiteInfo); if (underlyingTupleConversion.Exists) { return new Conversion(ConversionKind.ImplicitNullable, ImmutableArray.Create(underlyingTupleConversion)); } } } return Conversion.NoConversion; } private Conversion ClassifyExplicitTupleLiteralConversion(BoundTupleLiteral source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool forCast) { var tupleConversion = GetExplicitTupleLiteralConversion(source, destination, ref useSiteInfo, forCast); if (tupleConversion.Exists) { return tupleConversion; } // strip nullable from the destination // // the following should work and it is an ExplicitNullable conversion // var x = ((byte, string)?)(1,null); if (destination.Kind == SymbolKind.NamedType) { var nt = (NamedTypeSymbol)destination; if (nt.OriginalDefinition.GetSpecialTypeSafe() == SpecialType.System_Nullable_T) { var underlyingTupleConversion = GetExplicitTupleLiteralConversion(source, nt.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].Type, ref useSiteInfo, forCast); if (underlyingTupleConversion.Exists) { return new Conversion(ConversionKind.ExplicitNullable, ImmutableArray.Create(underlyingTupleConversion)); } } } return Conversion.NoConversion; } internal static bool HasImplicitConstantExpressionConversion(BoundExpression source, TypeSymbol destination) { var constantValue = source.ConstantValue; if (constantValue == null || (object)source.Type == null) { return false; } // An implicit constant expression conversion permits the following conversions: // A constant-expression of type int can be converted to type sbyte, byte, short, // ushort, uint, or ulong, provided the value of the constant-expression is within the // range of the destination type. var specialSource = source.Type.GetSpecialTypeSafe(); if (specialSource == SpecialType.System_Int32) { //if the constant value could not be computed, be generous and assume the conversion will work int value = constantValue.IsBad ? 0 : constantValue.Int32Value; switch (destination.GetSpecialTypeSafe()) { case SpecialType.System_Byte: return byte.MinValue <= value && value <= byte.MaxValue; case SpecialType.System_SByte: return sbyte.MinValue <= value && value <= sbyte.MaxValue; case SpecialType.System_Int16: return short.MinValue <= value && value <= short.MaxValue; case SpecialType.System_IntPtr when destination.IsNativeIntegerType: return true; case SpecialType.System_UInt32: case SpecialType.System_UIntPtr when destination.IsNativeIntegerType: return uint.MinValue <= value; case SpecialType.System_UInt64: return (int)ulong.MinValue <= value; case SpecialType.System_UInt16: return ushort.MinValue <= value && value <= ushort.MaxValue; default: return false; } } else if (specialSource == SpecialType.System_Int64 && destination.GetSpecialTypeSafe() == SpecialType.System_UInt64 && (constantValue.IsBad || 0 <= constantValue.Int64Value)) { // A constant-expression of type long can be converted to type ulong, provided the // value of the constant-expression is not negative. return true; } return false; } #nullable enable private Conversion ClassifyExplicitOnlyConversionFromExpression(BoundExpression sourceExpression, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool forCast) { Debug.Assert(sourceExpression != null); Debug.Assert((object)destination != null); // NB: need to check for explicit tuple literal conversion before checking for explicit conversion from type // The same literal may have both explicit tuple conversion and explicit tuple literal conversion to the target type. // They are, however, observably different conversions via the order of argument evaluations and element-wise conversions if (sourceExpression.Kind == BoundKind.TupleLiteral) { Conversion tupleConversion = ClassifyExplicitTupleLiteralConversion((BoundTupleLiteral)sourceExpression, destination, ref useSiteInfo, forCast); if (tupleConversion.Exists) { return tupleConversion; } } var sourceType = sourceExpression.Type; if (sourceType is { }) { // Try using the short-circuit "fast-conversion" path. Conversion fastConversion = FastClassifyConversion(sourceType, destination); if (fastConversion.Exists) { return fastConversion; } else { var conversion = ClassifyExplicitBuiltInOnlyConversion(sourceType, destination, ref useSiteInfo, forCast); if (conversion.Exists) { return conversion; } } } return GetExplicitUserDefinedConversion(sourceExpression, sourceType, destination, ref useSiteInfo); } private static bool HasImplicitEnumerationConversion(BoundExpression source, TypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // SPEC: An implicit enumeration conversion permits the decimal-integer-literal 0 to be converted to any enum-type // SPEC: and to any nullable-type whose underlying type is an enum-type. // // For historical reasons we actually allow a conversion from any *numeric constant // zero* to be converted to any enum type, not just the literal integer zero. bool validType = destination.IsEnumType() || destination.IsNullableType() && destination.GetNullableUnderlyingType().IsEnumType(); if (!validType) { return false; } var sourceConstantValue = source.ConstantValue; return sourceConstantValue != null && source.Type is object && IsNumericType(source.Type) && IsConstantNumericZero(sourceConstantValue); } private static LambdaConversionResult IsAnonymousFunctionCompatibleWithDelegate(UnboundLambda anonymousFunction, TypeSymbol type, bool isTargetExpressionTree) { Debug.Assert((object)anonymousFunction != null); Debug.Assert((object)type != null); // SPEC: An anonymous-method-expression or lambda-expression is classified as an anonymous function. // SPEC: The expression does not have a type but can be implicitly converted to a compatible delegate // SPEC: type or expression tree type. Specifically, a delegate type D is compatible with an // SPEC: anonymous function F provided: var delegateType = (NamedTypeSymbol)type; var invokeMethod = delegateType.DelegateInvokeMethod; if (invokeMethod is null || invokeMethod.HasUseSiteError) { return LambdaConversionResult.BadTargetType; } if (anonymousFunction.HasExplicitReturnType(out var refKind, out var returnType)) { if (invokeMethod.RefKind != refKind || !invokeMethod.ReturnType.Equals(returnType.Type, TypeCompareKind.AllIgnoreOptions)) { return LambdaConversionResult.MismatchedReturnType; } } var delegateParameters = invokeMethod.Parameters; // SPEC: If F contains an anonymous-function-signature, then D and F have the same number of parameters. // SPEC: If F does not contain an anonymous-function-signature, then D may have zero or more parameters // SPEC: of any type, as long as no parameter of D has the out parameter modifier. if (anonymousFunction.HasSignature) { if (anonymousFunction.ParameterCount != invokeMethod.ParameterCount) { return LambdaConversionResult.BadParameterCount; } // SPEC: If F has an explicitly typed parameter list, each parameter in D has the same type // SPEC: and modifiers as the corresponding parameter in F. // SPEC: If F has an implicitly typed parameter list, D has no ref or out parameters. if (anonymousFunction.HasExplicitlyTypedParameterList) { for (int p = 0; p < delegateParameters.Length; ++p) { if (delegateParameters[p].RefKind != anonymousFunction.RefKind(p) || !delegateParameters[p].Type.Equals(anonymousFunction.ParameterType(p), TypeCompareKind.AllIgnoreOptions)) { return LambdaConversionResult.MismatchedParameterType; } } } else { for (int p = 0; p < delegateParameters.Length; ++p) { if (delegateParameters[p].RefKind != RefKind.None) { return LambdaConversionResult.RefInImplicitlyTypedLambda; } } // In C# it is not possible to make a delegate type // such that one of its parameter types is a static type. But static types are // in metadata just sealed abstract types; there is nothing stopping someone in // another language from creating a delegate with a static type for a parameter, // though the only argument you could pass for that parameter is null. // // In the native compiler we forbid conversion of an anonymous function that has // an implicitly-typed parameter list to a delegate type that has a static type // for a formal parameter type. However, we do *not* forbid it for an explicitly- // typed lambda (because we already require that the explicitly typed parameter not // be static) and we do not forbid it for an anonymous method with the entire // parameter list missing (because the body cannot possibly have a parameter that // is of static type, even though this means that we will be generating a hidden // method with a parameter of static type.) // // We also allow more exotic situations to work in the native compiler. For example, // though it is not possible to convert x=>{} to Action<GC>, it is possible to convert // it to Action<List<GC>> should there be a language that allows you to construct // a variable of that type. // // We might consider beefing up this rule to disallow a conversion of *any* anonymous // function to *any* delegate that has a static type *anywhere* in the parameter list. for (int p = 0; p < delegateParameters.Length; ++p) { if (delegateParameters[p].TypeWithAnnotations.IsStatic) { return LambdaConversionResult.StaticTypeInImplicitlyTypedLambda; } } } } else { for (int p = 0; p < delegateParameters.Length; ++p) { if (delegateParameters[p].RefKind == RefKind.Out) { return LambdaConversionResult.MissingSignatureWithOutParameter; } } } // Ensure the body can be converted to that delegate type var bound = anonymousFunction.Bind(delegateType, isTargetExpressionTree); if (ErrorFacts.PreventsSuccessfulDelegateConversion(bound.Diagnostics.Diagnostics)) { return LambdaConversionResult.BindingFailed; } return LambdaConversionResult.Success; } private static LambdaConversionResult IsAnonymousFunctionCompatibleWithExpressionTree(UnboundLambda anonymousFunction, NamedTypeSymbol type) { Debug.Assert((object)anonymousFunction != null); Debug.Assert((object)type != null); Debug.Assert(type.IsExpressionTree()); // SPEC OMISSION: // // The C# 3 spec said that anonymous methods and statement lambdas are *convertible* to expression tree // types if the anonymous method/statement lambda is convertible to its delegate type; however, actually // *using* such a conversion is an error. However, that is not what we implemented. In C# 3 we implemented // that an anonymous method is *not convertible* to an expression tree type, period. (Statement lambdas // used the rule described in the spec.) // // This appears to be a spec omission; the intention is to make old-style anonymous methods not // convertible to expression trees. var delegateType = type.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].Type; if (!delegateType.IsDelegateType()) { return LambdaConversionResult.ExpressionTreeMustHaveDelegateTypeArgument; } if (anonymousFunction.Syntax.Kind() == SyntaxKind.AnonymousMethodExpression) { return LambdaConversionResult.ExpressionTreeFromAnonymousMethod; } return IsAnonymousFunctionCompatibleWithDelegate(anonymousFunction, delegateType, isTargetExpressionTree: true); } internal bool IsAssignableFromMulticastDelegate(TypeSymbol type, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var multicastDelegateType = corLibrary.GetSpecialType(SpecialType.System_MulticastDelegate); multicastDelegateType.AddUseSiteInfo(ref useSiteInfo); return ClassifyImplicitConversionFromType(multicastDelegateType, type, ref useSiteInfo).Exists; } public static LambdaConversionResult IsAnonymousFunctionCompatibleWithType(UnboundLambda anonymousFunction, TypeSymbol type) { Debug.Assert((object)anonymousFunction != null); Debug.Assert((object)type != null); if (type.IsDelegateType()) { return IsAnonymousFunctionCompatibleWithDelegate(anonymousFunction, type, isTargetExpressionTree: false); } else if (type.IsExpressionTree()) { return IsAnonymousFunctionCompatibleWithExpressionTree(anonymousFunction, (NamedTypeSymbol)type); } return LambdaConversionResult.BadTargetType; } private static bool HasAnonymousFunctionConversion(BoundExpression source, TypeSymbol destination) { Debug.Assert(source != null); Debug.Assert((object)destination != null); if (source.Kind != BoundKind.UnboundLambda) { return false; } return IsAnonymousFunctionCompatibleWithType((UnboundLambda)source, destination) == LambdaConversionResult.Success; } #nullable disable internal Conversion ClassifyImplicitUserDefinedConversionForV6SwitchGoverningType(TypeSymbol sourceType, out TypeSymbol switchGoverningType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: The governing type of a switch statement is established by the switch expression. // SPEC: 1) If the type of the switch expression is sbyte, byte, short, ushort, int, uint, // SPEC: long, ulong, bool, char, string, or an enum-type, or if it is the nullable type // SPEC: corresponding to one of these types, then that is the governing type of the switch statement. // SPEC: 2) Otherwise, exactly one user-defined implicit conversion (§6.4) must exist from the // SPEC: type of the switch expression to one of the following possible governing types: // SPEC: sbyte, byte, short, ushort, int, uint, long, ulong, char, string, or, a nullable type // SPEC: corresponding to one of those types // NOTE: We should be called only if (1) is false for source type. Debug.Assert((object)sourceType != null); Debug.Assert(!sourceType.IsValidV6SwitchGoverningType()); UserDefinedConversionResult result = AnalyzeImplicitUserDefinedConversionForV6SwitchGoverningType(sourceType, ref useSiteInfo); if (result.Kind == UserDefinedConversionResultKind.Valid) { UserDefinedConversionAnalysis analysis = result.Results[result.Best]; switchGoverningType = analysis.ToType; Debug.Assert(switchGoverningType.IsValidV6SwitchGoverningType(isTargetTypeOfUserDefinedOp: true)); } else { switchGoverningType = null; } return new Conversion(result, isImplicit: true); } internal Conversion GetCallerLineNumberConversion(TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var greenNode = new Syntax.InternalSyntax.LiteralExpressionSyntax(SyntaxKind.NumericLiteralExpression, new Syntax.InternalSyntax.SyntaxToken(SyntaxKind.NumericLiteralToken)); var syntaxNode = new LiteralExpressionSyntax(greenNode, null, 0); TypeSymbol expectedAttributeType = corLibrary.GetSpecialType(SpecialType.System_Int32); BoundLiteral intMaxValueLiteral = new BoundLiteral(syntaxNode, ConstantValue.Create(int.MaxValue), expectedAttributeType); return ClassifyStandardImplicitConversion(intMaxValueLiteral, expectedAttributeType, destination, ref useSiteInfo); } internal bool HasCallerLineNumberConversion(TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { return GetCallerLineNumberConversion(destination, ref useSiteInfo).Exists; } internal bool HasCallerInfoStringConversion(TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { TypeSymbol expectedAttributeType = corLibrary.GetSpecialType(SpecialType.System_String); Conversion conversion = ClassifyStandardImplicitConversion(expectedAttributeType, destination, ref useSiteInfo); return conversion.Exists; } public static bool HasIdentityConversion(TypeSymbol type1, TypeSymbol type2) { return HasIdentityConversionInternal(type1, type2, includeNullability: false); } private static bool HasIdentityConversionInternal(TypeSymbol type1, TypeSymbol type2, bool includeNullability) { // Spec (6.1.1): // An identity conversion converts from any type to the same type. This conversion exists // such that an entity that already has a required type can be said to be convertible to // that type. // // Because object and dynamic are considered equivalent there is an identity conversion // between object and dynamic, and between constructed types that are the same when replacing // all occurrences of dynamic with object. Debug.Assert((object)type1 != null); Debug.Assert((object)type2 != null); // Note, when we are paying attention to nullability, we ignore oblivious mismatch. // See TypeCompareKind.ObliviousNullableModifierMatchesAny var compareKind = includeNullability ? TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.IgnoreNullableModifiersForReferenceTypes : TypeCompareKind.AllIgnoreOptions; return type1.Equals(type2, compareKind); } private bool HasIdentityConversionInternal(TypeSymbol type1, TypeSymbol type2) { return HasIdentityConversionInternal(type1, type2, IncludeNullability); } /// <summary> /// Returns true if: /// - Either type has no nullability information (oblivious). /// - Both types cannot have different nullability at the same time, /// including the case of type parameters that by themselves can represent nullable and not nullable reference types. /// </summary> internal bool HasTopLevelNullabilityIdentityConversion(TypeWithAnnotations source, TypeWithAnnotations destination) { if (!IncludeNullability) { return true; } if (source.NullableAnnotation.IsOblivious() || destination.NullableAnnotation.IsOblivious()) { return true; } var sourceIsPossiblyNullableTypeParameter = IsPossiblyNullableTypeTypeParameter(source); var destinationIsPossiblyNullableTypeParameter = IsPossiblyNullableTypeTypeParameter(destination); if (sourceIsPossiblyNullableTypeParameter && !destinationIsPossiblyNullableTypeParameter) { return destination.NullableAnnotation.IsAnnotated(); } if (destinationIsPossiblyNullableTypeParameter && !sourceIsPossiblyNullableTypeParameter) { return source.NullableAnnotation.IsAnnotated(); } return source.NullableAnnotation.IsAnnotated() == destination.NullableAnnotation.IsAnnotated(); } /// <summary> /// Returns false if source type can be nullable at the same time when destination type can be not nullable, /// including the case of type parameters that by themselves can represent nullable and not nullable reference types. /// When either type has no nullability information (oblivious), this method returns true. /// </summary> internal bool HasTopLevelNullabilityImplicitConversion(TypeWithAnnotations source, TypeWithAnnotations destination) { if (!IncludeNullability) { return true; } if (source.NullableAnnotation.IsOblivious() || destination.NullableAnnotation.IsOblivious() || destination.NullableAnnotation.IsAnnotated()) { return true; } if (IsPossiblyNullableTypeTypeParameter(source) && !IsPossiblyNullableTypeTypeParameter(destination)) { return false; } return !source.NullableAnnotation.IsAnnotated(); } private static bool IsPossiblyNullableTypeTypeParameter(in TypeWithAnnotations typeWithAnnotations) { var type = typeWithAnnotations.Type; return type is object && (type.IsPossiblyNullableReferenceTypeTypeParameter() || type.IsNullableTypeOrTypeParameter()); } /// <summary> /// Returns false if the source does not have an implicit conversion to the destination /// because of either incompatible top level or nested nullability. /// </summary> public bool HasAnyNullabilityImplicitConversion(TypeWithAnnotations source, TypeWithAnnotations destination) { Debug.Assert(IncludeNullability); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; return HasTopLevelNullabilityImplicitConversion(source, destination) && ClassifyImplicitConversionFromType(source.Type, destination.Type, ref discardedUseSiteInfo).Kind != ConversionKind.NoConversion; } public static bool HasIdentityConversionToAny<T>(T type, ArrayBuilder<T> targetTypes) where T : TypeSymbol { foreach (var targetType in targetTypes) { if (HasIdentityConversionInternal(type, targetType, includeNullability: false)) { return true; } } return false; } public Conversion ConvertExtensionMethodThisArg(TypeSymbol parameterType, TypeSymbol thisType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)thisType != null); var conversion = this.ClassifyImplicitExtensionMethodThisArgConversion(null, thisType, parameterType, ref useSiteInfo); return IsValidExtensionMethodThisArgConversion(conversion) ? conversion : Conversion.NoConversion; } // Spec 7.6.5.2: "An extension method ... is eligible if ... [an] implicit identity, reference, // or boxing conversion exists from expr to the type of the first parameter" public Conversion ClassifyImplicitExtensionMethodThisArgConversion(BoundExpression sourceExpressionOpt, TypeSymbol sourceType, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(sourceExpressionOpt == null || (object)sourceExpressionOpt.Type == sourceType); Debug.Assert((object)destination != null); if ((object)sourceType != null) { if (HasIdentityConversionInternal(sourceType, destination)) { return Conversion.Identity; } if (HasBoxingConversion(sourceType, destination, ref useSiteInfo)) { return Conversion.Boxing; } if (HasImplicitReferenceConversion(sourceType, destination, ref useSiteInfo)) { return Conversion.ImplicitReference; } } if (sourceExpressionOpt?.Kind == BoundKind.TupleLiteral) { // GetTupleLiteralConversion is not used with IncludeNullability currently. // If that changes, the delegate below will need to consider top-level nullability. Debug.Assert(!IncludeNullability); var tupleConversion = GetTupleLiteralConversion( (BoundTupleLiteral)sourceExpressionOpt, destination, ref useSiteInfo, ConversionKind.ImplicitTupleLiteral, (ConversionsBase conversions, BoundExpression s, TypeWithAnnotations d, ref CompoundUseSiteInfo<AssemblySymbol> u, bool a) => conversions.ClassifyImplicitExtensionMethodThisArgConversion(s, s.Type, d.Type, ref u), arg: false); if (tupleConversion.Exists) { return tupleConversion; } } if ((object)sourceType != null) { var tupleConversion = ClassifyTupleConversion( sourceType, destination, ref useSiteInfo, ConversionKind.ImplicitTuple, (ConversionsBase conversions, TypeWithAnnotations s, TypeWithAnnotations d, ref CompoundUseSiteInfo<AssemblySymbol> u, bool a) => { if (!conversions.HasTopLevelNullabilityImplicitConversion(s, d)) { return Conversion.NoConversion; } return conversions.ClassifyImplicitExtensionMethodThisArgConversion(null, s.Type, d.Type, ref u); }, arg: false); if (tupleConversion.Exists) { return tupleConversion; } } return Conversion.NoConversion; } // It should be possible to remove IsValidExtensionMethodThisArgConversion // since ClassifyImplicitExtensionMethodThisArgConversion should only // return valid conversions. https://github.com/dotnet/roslyn/issues/19622 // Spec 7.6.5.2: "An extension method ... is eligible if ... [an] implicit identity, reference, // or boxing conversion exists from expr to the type of the first parameter" public static bool IsValidExtensionMethodThisArgConversion(Conversion conversion) { switch (conversion.Kind) { case ConversionKind.Identity: case ConversionKind.Boxing: case ConversionKind.ImplicitReference: return true; case ConversionKind.ImplicitTuple: case ConversionKind.ImplicitTupleLiteral: // check if all element conversions satisfy the requirement foreach (var elementConversion in conversion.UnderlyingConversions) { if (!IsValidExtensionMethodThisArgConversion(elementConversion)) { return false; } } return true; default: // Caller should have not have calculated another conversion. Debug.Assert(conversion.Kind == ConversionKind.NoConversion); return false; } } private const bool F = false; private const bool T = true; // Notice that there is no implicit numeric conversion from a type to itself. That's an // identity conversion. private static readonly bool[,] s_implicitNumericConversions = { // to sb b s us i ui l ul c f d m // from /* sb */ { F, F, T, F, T, F, T, F, F, T, T, T }, /* b */ { F, F, T, T, T, T, T, T, F, T, T, T }, /* s */ { F, F, F, F, T, F, T, F, F, T, T, T }, /* us */ { F, F, F, F, T, T, T, T, F, T, T, T }, /* i */ { F, F, F, F, F, F, T, F, F, T, T, T }, /* ui */ { F, F, F, F, F, F, T, T, F, T, T, T }, /* l */ { F, F, F, F, F, F, F, F, F, T, T, T }, /* ul */ { F, F, F, F, F, F, F, F, F, T, T, T }, /* c */ { F, F, F, T, T, T, T, T, F, T, T, T }, /* f */ { F, F, F, F, F, F, F, F, F, F, T, F }, /* d */ { F, F, F, F, F, F, F, F, F, F, F, F }, /* m */ { F, F, F, F, F, F, F, F, F, F, F, F } }; private static readonly bool[,] s_explicitNumericConversions = { // to sb b s us i ui l ul c f d m // from /* sb */ { F, T, F, T, F, T, F, T, T, F, F, F }, /* b */ { T, F, F, F, F, F, F, F, T, F, F, F }, /* s */ { T, T, F, T, F, T, F, T, T, F, F, F }, /* us */ { T, T, T, F, F, F, F, F, T, F, F, F }, /* i */ { T, T, T, T, F, T, F, T, T, F, F, F }, /* ui */ { T, T, T, T, T, F, F, F, T, F, F, F }, /* l */ { T, T, T, T, T, T, F, T, T, F, F, F }, /* ul */ { T, T, T, T, T, T, T, F, T, F, F, F }, /* c */ { T, T, T, F, F, F, F, F, F, F, F, F }, /* f */ { T, T, T, T, T, T, T, T, T, F, F, T }, /* d */ { T, T, T, T, T, T, T, T, T, T, F, T }, /* m */ { T, T, T, T, T, T, T, T, T, T, T, F } }; private static int GetNumericTypeIndex(SpecialType specialType) { switch (specialType) { case SpecialType.System_SByte: return 0; case SpecialType.System_Byte: return 1; case SpecialType.System_Int16: return 2; case SpecialType.System_UInt16: return 3; case SpecialType.System_Int32: return 4; case SpecialType.System_UInt32: return 5; case SpecialType.System_Int64: return 6; case SpecialType.System_UInt64: return 7; case SpecialType.System_Char: return 8; case SpecialType.System_Single: return 9; case SpecialType.System_Double: return 10; case SpecialType.System_Decimal: return 11; default: return -1; } } #nullable enable private static bool HasImplicitNumericConversion(TypeSymbol source, TypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); int sourceIndex = GetNumericTypeIndex(source.SpecialType); if (sourceIndex < 0) { return false; } int destinationIndex = GetNumericTypeIndex(destination.SpecialType); if (destinationIndex < 0) { return false; } return s_implicitNumericConversions[sourceIndex, destinationIndex]; } private static bool HasExplicitNumericConversion(TypeSymbol source, TypeSymbol destination) { // SPEC: The explicit numeric conversions are the conversions from a numeric-type to another // SPEC: numeric-type for which an implicit numeric conversion does not already exist. Debug.Assert((object)source != null); Debug.Assert((object)destination != null); int sourceIndex = GetNumericTypeIndex(source.SpecialType); if (sourceIndex < 0) { return false; } int destinationIndex = GetNumericTypeIndex(destination.SpecialType); if (destinationIndex < 0) { return false; } return s_explicitNumericConversions[sourceIndex, destinationIndex]; } private static bool IsConstantNumericZero(ConstantValue value) { switch (value.Discriminator) { case ConstantValueTypeDiscriminator.SByte: return value.SByteValue == 0; case ConstantValueTypeDiscriminator.Byte: return value.ByteValue == 0; case ConstantValueTypeDiscriminator.Int16: return value.Int16Value == 0; case ConstantValueTypeDiscriminator.Int32: case ConstantValueTypeDiscriminator.NInt: return value.Int32Value == 0; case ConstantValueTypeDiscriminator.Int64: return value.Int64Value == 0; case ConstantValueTypeDiscriminator.UInt16: return value.UInt16Value == 0; case ConstantValueTypeDiscriminator.UInt32: case ConstantValueTypeDiscriminator.NUInt: return value.UInt32Value == 0; case ConstantValueTypeDiscriminator.UInt64: return value.UInt64Value == 0; case ConstantValueTypeDiscriminator.Single: case ConstantValueTypeDiscriminator.Double: return value.DoubleValue == 0; case ConstantValueTypeDiscriminator.Decimal: return value.DecimalValue == 0; } return false; } private static bool IsNumericType(TypeSymbol type) { switch (type.SpecialType) { case SpecialType.System_Char: case SpecialType.System_SByte: case SpecialType.System_Byte: case SpecialType.System_Int16: case SpecialType.System_UInt16: case SpecialType.System_Int32: case SpecialType.System_UInt32: case SpecialType.System_Int64: case SpecialType.System_UInt64: case SpecialType.System_Single: case SpecialType.System_Double: case SpecialType.System_Decimal: case SpecialType.System_IntPtr when type.IsNativeIntegerType: case SpecialType.System_UIntPtr when type.IsNativeIntegerType: return true; default: return false; } } private static bool HasSpecialIntPtrConversion(TypeSymbol source, TypeSymbol target) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); // There are only a total of twelve user-defined explicit conversions on IntPtr and UIntPtr: // // IntPtr <---> int // IntPtr <---> long // IntPtr <---> void* // UIntPtr <---> uint // UIntPtr <---> ulong // UIntPtr <---> void* // // The specification says that you can put any *standard* implicit or explicit conversion // on "either side" of a user-defined explicit conversion, so the specification allows, say, // UIntPtr --> byte because the conversion UIntPtr --> uint is user-defined and the // conversion uint --> byte is "standard". It is "standard" because the conversion // byte --> uint is an implicit numeric conversion. // This means that certain conversions should be illegal. For example, IntPtr --> ulong // should be illegal because none of int --> ulong, long --> ulong and void* --> ulong // are "standard" conversions. // Similarly, some conversions involving IntPtr should be illegal because they are // ambiguous. byte --> IntPtr?, for example, is ambiguous. (There are four possible // UD operators: int --> IntPtr and long --> IntPtr, and their lifted versions. The // best possible source type is int, the best possible target type is IntPtr?, and // there is an ambiguity between the unlifted int --> IntPtr, and the lifted // int? --> IntPtr? conversions.) // In practice, the native compiler, and hence, the Roslyn compiler, allows all // these conversions. Any conversion from a numeric type to IntPtr, or from an IntPtr // to a numeric type, is allowed. Also, any conversion from a pointer type to IntPtr // or vice versa is allowed. var s0 = source.StrippedType(); var t0 = target.StrippedType(); TypeSymbol otherType; if (isIntPtrOrUIntPtr(s0)) { otherType = t0; } else if (isIntPtrOrUIntPtr(t0)) { otherType = s0; } else { return false; } if (otherType.IsPointerOrFunctionPointer()) { return true; } if (otherType.TypeKind == TypeKind.Enum) { return true; } switch (otherType.SpecialType) { case SpecialType.System_SByte: case SpecialType.System_Byte: case SpecialType.System_Int16: case SpecialType.System_UInt16: case SpecialType.System_Char: case SpecialType.System_Int32: case SpecialType.System_UInt32: case SpecialType.System_Int64: case SpecialType.System_UInt64: case SpecialType.System_Double: case SpecialType.System_Single: case SpecialType.System_Decimal: return true; } return false; static bool isIntPtrOrUIntPtr(TypeSymbol type) => (type.SpecialType == SpecialType.System_IntPtr || type.SpecialType == SpecialType.System_UIntPtr) && !type.IsNativeIntegerType; } private static bool HasExplicitEnumerationConversion(TypeSymbol source, TypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // SPEC: The explicit enumeration conversions are: // SPEC: From sbyte, byte, short, ushort, int, uint, long, ulong, nint, nuint, char, float, double, or decimal to any enum-type. // SPEC: From any enum-type to sbyte, byte, short, ushort, int, uint, long, ulong, nint, nuint, char, float, double, or decimal. // SPEC: From any enum-type to any other enum-type. if (IsNumericType(source) && destination.IsEnumType()) { return true; } if (IsNumericType(destination) && source.IsEnumType()) { return true; } if (source.IsEnumType() && destination.IsEnumType()) { return true; } return false; } #nullable disable private Conversion ClassifyImplicitNullableConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // SPEC: Predefined implicit conversions that operate on non-nullable value types can also be used with // SPEC: nullable forms of those types. For each of the predefined implicit identity, numeric and tuple conversions // SPEC: that convert from a non-nullable value type S to a non-nullable value type T, the following implicit // SPEC: nullable conversions exist: // SPEC: * An implicit conversion from S? to T?. // SPEC: * An implicit conversion from S to T?. if (!destination.IsNullableType()) { return Conversion.NoConversion; } TypeSymbol unwrappedDestination = destination.GetNullableUnderlyingType(); TypeSymbol unwrappedSource = source.StrippedType(); if (!unwrappedSource.IsValueType) { return Conversion.NoConversion; } if (HasIdentityConversionInternal(unwrappedSource, unwrappedDestination)) { return new Conversion(ConversionKind.ImplicitNullable, Conversion.IdentityUnderlying); } if (HasImplicitNumericConversion(unwrappedSource, unwrappedDestination)) { return new Conversion(ConversionKind.ImplicitNullable, Conversion.ImplicitNumericUnderlying); } var tupleConversion = ClassifyImplicitTupleConversion(unwrappedSource, unwrappedDestination, ref useSiteInfo); if (tupleConversion.Exists) { return new Conversion(ConversionKind.ImplicitNullable, ImmutableArray.Create(tupleConversion)); } return Conversion.NoConversion; } private delegate Conversion ClassifyConversionFromExpressionDelegate(ConversionsBase conversions, BoundExpression sourceExpression, TypeWithAnnotations destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool arg); private delegate Conversion ClassifyConversionFromTypeDelegate(ConversionsBase conversions, TypeWithAnnotations source, TypeWithAnnotations destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool arg); private Conversion GetImplicitTupleLiteralConversion(BoundTupleLiteral source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // GetTupleLiteralConversion is not used with IncludeNullability currently. // If that changes, the delegate below will need to consider top-level nullability. Debug.Assert(!IncludeNullability); return GetTupleLiteralConversion( source, destination, ref useSiteInfo, ConversionKind.ImplicitTupleLiteral, (ConversionsBase conversions, BoundExpression s, TypeWithAnnotations d, ref CompoundUseSiteInfo<AssemblySymbol> u, bool a) => conversions.ClassifyImplicitConversionFromExpression(s, d.Type, ref u), arg: false); } private Conversion GetExplicitTupleLiteralConversion(BoundTupleLiteral source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool forCast) { // GetTupleLiteralConversion is not used with IncludeNullability currently. // If that changes, the delegate below will need to consider top-level nullability. Debug.Assert(!IncludeNullability); return GetTupleLiteralConversion( source, destination, ref useSiteInfo, ConversionKind.ExplicitTupleLiteral, (ConversionsBase conversions, BoundExpression s, TypeWithAnnotations d, ref CompoundUseSiteInfo<AssemblySymbol> u, bool a) => conversions.ClassifyConversionFromExpression(s, d.Type, ref u, a), forCast); } private Conversion GetTupleLiteralConversion( BoundTupleLiteral source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, ConversionKind kind, ClassifyConversionFromExpressionDelegate classifyConversion, bool arg) { var arguments = source.Arguments; // check if the type is actually compatible type for a tuple of given cardinality if (!destination.IsTupleTypeOfCardinality(arguments.Length)) { return Conversion.NoConversion; } var targetElementTypes = destination.TupleElementTypesWithAnnotations; Debug.Assert(arguments.Length == targetElementTypes.Length); // check arguments against flattened list of target element types var argumentConversions = ArrayBuilder<Conversion>.GetInstance(arguments.Length); for (int i = 0; i < arguments.Length; i++) { var argument = arguments[i]; var result = classifyConversion(this, argument, targetElementTypes[i], ref useSiteInfo, arg); if (!result.Exists) { argumentConversions.Free(); return Conversion.NoConversion; } argumentConversions.Add(result); } return new Conversion(kind, argumentConversions.ToImmutableAndFree()); } private Conversion ClassifyImplicitTupleConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { return ClassifyTupleConversion( source, destination, ref useSiteInfo, ConversionKind.ImplicitTuple, (ConversionsBase conversions, TypeWithAnnotations s, TypeWithAnnotations d, ref CompoundUseSiteInfo<AssemblySymbol> u, bool a) => { if (!conversions.HasTopLevelNullabilityImplicitConversion(s, d)) { return Conversion.NoConversion; } return conversions.ClassifyImplicitConversionFromType(s.Type, d.Type, ref u); }, arg: false); } private Conversion ClassifyExplicitTupleConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool forCast) { return ClassifyTupleConversion( source, destination, ref useSiteInfo, ConversionKind.ExplicitTuple, (ConversionsBase conversions, TypeWithAnnotations s, TypeWithAnnotations d, ref CompoundUseSiteInfo<AssemblySymbol> u, bool a) => { if (!conversions.HasTopLevelNullabilityImplicitConversion(s, d)) { return Conversion.NoConversion; } return conversions.ClassifyConversionFromType(s.Type, d.Type, ref u, a); }, forCast); } private Conversion ClassifyTupleConversion( TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, ConversionKind kind, ClassifyConversionFromTypeDelegate classifyConversion, bool arg) { ImmutableArray<TypeWithAnnotations> sourceTypes; ImmutableArray<TypeWithAnnotations> destTypes; if (!source.TryGetElementTypesWithAnnotationsIfTupleType(out sourceTypes) || !destination.TryGetElementTypesWithAnnotationsIfTupleType(out destTypes) || sourceTypes.Length != destTypes.Length) { return Conversion.NoConversion; } var nestedConversions = ArrayBuilder<Conversion>.GetInstance(sourceTypes.Length); for (int i = 0; i < sourceTypes.Length; i++) { var conversion = classifyConversion(this, sourceTypes[i], destTypes[i], ref useSiteInfo, arg); if (!conversion.Exists) { nestedConversions.Free(); return Conversion.NoConversion; } nestedConversions.Add(conversion); } return new Conversion(kind, nestedConversions.ToImmutableAndFree()); } private Conversion ClassifyExplicitNullableConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool forCast) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // SPEC: Explicit nullable conversions permit predefined explicit conversions that operate on // SPEC: non-nullable value types to also be used with nullable forms of those types. For // SPEC: each of the predefined explicit conversions that convert from a non-nullable value type // SPEC: S to a non-nullable value type T, the following nullable conversions exist: // SPEC: An explicit conversion from S? to T?. // SPEC: An explicit conversion from S to T?. // SPEC: An explicit conversion from S? to T. if (!source.IsNullableType() && !destination.IsNullableType()) { return Conversion.NoConversion; } TypeSymbol unwrappedSource = source.StrippedType(); TypeSymbol unwrappedDestination = destination.StrippedType(); if (HasIdentityConversionInternal(unwrappedSource, unwrappedDestination)) { return new Conversion(ConversionKind.ExplicitNullable, Conversion.IdentityUnderlying); } if (HasImplicitNumericConversion(unwrappedSource, unwrappedDestination)) { return new Conversion(ConversionKind.ExplicitNullable, Conversion.ImplicitNumericUnderlying); } if (HasExplicitNumericConversion(unwrappedSource, unwrappedDestination)) { return new Conversion(ConversionKind.ExplicitNullable, Conversion.ExplicitNumericUnderlying); } var tupleConversion = ClassifyExplicitTupleConversion(unwrappedSource, unwrappedDestination, ref useSiteInfo, forCast); if (tupleConversion.Exists) { return new Conversion(ConversionKind.ExplicitNullable, ImmutableArray.Create(tupleConversion)); } if (HasExplicitEnumerationConversion(unwrappedSource, unwrappedDestination)) { return new Conversion(ConversionKind.ExplicitNullable, Conversion.ExplicitEnumerationUnderlying); } if (HasPointerToIntegerConversion(unwrappedSource, unwrappedDestination)) { return new Conversion(ConversionKind.ExplicitNullable, Conversion.PointerToIntegerUnderlying); } return Conversion.NoConversion; } private bool HasCovariantArrayConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); var s = source as ArrayTypeSymbol; var d = destination as ArrayTypeSymbol; if ((object)s == null || (object)d == null) { return false; } // * S and T differ only in element type. In other words, S and T have the same number of dimensions. if (!s.HasSameShapeAs(d)) { return false; } // * Both SE and TE are reference types. // * An implicit reference conversion exists from SE to TE. return HasImplicitReferenceConversion(s.ElementTypeWithAnnotations, d.ElementTypeWithAnnotations, ref useSiteInfo); } public bool HasIdentityOrImplicitReferenceConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (HasIdentityConversionInternal(source, destination)) { return true; } return HasImplicitReferenceConversion(source, destination, ref useSiteInfo); } private static bool HasImplicitDynamicConversionFromExpression(TypeSymbol expressionType, TypeSymbol destination) { // Spec (§6.1.8) // An implicit dynamic conversion exists from an expression of type dynamic to any type T. Debug.Assert((object)destination != null); return expressionType?.Kind == SymbolKind.DynamicType && !destination.IsPointerOrFunctionPointer(); } private static bool HasExplicitDynamicConversion(TypeSymbol source, TypeSymbol destination) { // SPEC: An explicit dynamic conversion exists from an expression of [sic] type dynamic to any type T. // ISSUE: The "an expression of" part of the spec is probably an error; see https://github.com/dotnet/csharplang/issues/132 Debug.Assert((object)source != null); Debug.Assert((object)destination != null); return source.Kind == SymbolKind.DynamicType && !destination.IsPointerOrFunctionPointer(); } private bool HasArrayConversionToInterface(ArrayTypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (!source.IsSZArray) { return false; } if (!destination.IsInterfaceType()) { return false; } // The specification says that there is a conversion: // * From a single-dimensional array type S[] to IList<T> and its base // interfaces, provided that there is an implicit identity or reference // conversion from S to T. // // Newer versions of the framework also have arrays be convertible to // IReadOnlyList<T> and IReadOnlyCollection<T>; we honor that as well. // // Therefore we must check for: // // IList<T> // ICollection<T> // IEnumerable<T> // IEnumerable // IReadOnlyList<T> // IReadOnlyCollection<T> if (destination.SpecialType == SpecialType.System_Collections_IEnumerable) { return true; } NamedTypeSymbol destinationAgg = (NamedTypeSymbol)destination; if (destinationAgg.AllTypeArgumentCount() != 1) { return false; } if (!destinationAgg.IsPossibleArrayGenericInterface()) { return false; } TypeWithAnnotations elementType = source.ElementTypeWithAnnotations; TypeWithAnnotations argument0 = destinationAgg.TypeArgumentWithDefinitionUseSiteDiagnostics(0, ref useSiteInfo); if (IncludeNullability && !HasTopLevelNullabilityImplicitConversion(elementType, argument0)) { return false; } return HasIdentityOrImplicitReferenceConversion(elementType.Type, argument0.Type, ref useSiteInfo); } private bool HasImplicitReferenceConversion(TypeWithAnnotations source, TypeWithAnnotations destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (IncludeNullability) { if (!HasTopLevelNullabilityImplicitConversion(source, destination)) { return false; } // Check for identity conversion of underlying types if the top-level nullability is distinct. // (An identity conversion where nullability matches is not considered an implicit reference conversion.) if (source.NullableAnnotation != destination.NullableAnnotation && HasIdentityConversionInternal(source.Type, destination.Type, includeNullability: true)) { return true; } } return HasImplicitReferenceConversion(source.Type, destination.Type, ref useSiteInfo); } #nullable enable internal bool HasImplicitReferenceConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (source.IsErrorType()) { return false; } if (!source.IsReferenceType) { return false; } // SPEC: The implicit reference conversions are: // SPEC: UNDONE: From any reference-type to a reference-type T if it has an implicit identity // SPEC: UNDONE: or reference conversion to a reference-type T0 and T0 has an identity conversion to T. // UNDONE: Is the right thing to do here to strip dynamic off and check for convertibility? // SPEC: From any reference type to object and dynamic. if (destination.SpecialType == SpecialType.System_Object || destination.Kind == SymbolKind.DynamicType) { return true; } switch (source.TypeKind) { case TypeKind.Class: // SPEC: From any class type S to any class type T provided S is derived from T. if (destination.IsClassType() && IsBaseClass(source, destination, ref useSiteInfo)) { return true; } return HasImplicitConversionToInterface(source, destination, ref useSiteInfo); case TypeKind.Interface: // SPEC: From any interface-type S to any interface-type T, provided S is derived from T. // NOTE: This handles variance conversions return HasImplicitConversionToInterface(source, destination, ref useSiteInfo); case TypeKind.Delegate: // SPEC: From any delegate-type to System.Delegate and the interfaces it implements. // NOTE: This handles variance conversions. return HasImplicitConversionFromDelegate(source, destination, ref useSiteInfo); case TypeKind.TypeParameter: return HasImplicitReferenceTypeParameterConversion((TypeParameterSymbol)source, destination, ref useSiteInfo); case TypeKind.Array: // SPEC: From an array-type S ... to an array-type T, provided ... // SPEC: From any array-type to System.Array and the interfaces it implements. // SPEC: From a single-dimensional array type S[] to IList<T>, provided ... return HasImplicitConversionFromArray(source, destination, ref useSiteInfo); } // UNDONE: Implicit conversions involving type parameters that are known to be reference types. return false; } private bool HasImplicitConversionToInterface(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (!destination.IsInterfaceType()) { return false; } // * From any class type S to any interface type T provided S implements an interface // convertible to T. if (source.IsClassType()) { return HasAnyBaseInterfaceConversion(source, destination, ref useSiteInfo); } // * From any interface type S to any interface type T provided S implements an interface // convertible to T. // * From any interface type S to any interface type T provided S is not T and S is // an interface convertible to T. if (source.IsInterfaceType()) { if (HasAnyBaseInterfaceConversion(source, destination, ref useSiteInfo)) { return true; } if (!HasIdentityConversionInternal(source, destination) && HasInterfaceVarianceConversion(source, destination, ref useSiteInfo)) { return true; } } return false; } private bool HasImplicitConversionFromArray(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var s = source as ArrayTypeSymbol; if (s is null) { return false; } // * From an array type S with an element type SE to an array type T with element type TE // provided that all of the following are true: // * S and T differ only in element type. In other words, S and T have the same number of dimensions. // * Both SE and TE are reference types. // * An implicit reference conversion exists from SE to TE. if (HasCovariantArrayConversion(source, destination, ref useSiteInfo)) { return true; } // * From any array type to System.Array or any interface implemented by System.Array. if (destination.GetSpecialTypeSafe() == SpecialType.System_Array) { return true; } if (IsBaseInterface(destination, this.corLibrary.GetDeclaredSpecialType(SpecialType.System_Array), ref useSiteInfo)) { return true; } // * From a single-dimensional array type S[] to IList<T> and its base // interfaces, provided that there is an implicit identity or reference // conversion from S to T. if (HasArrayConversionToInterface(s, destination, ref useSiteInfo)) { return true; } return false; } private bool HasImplicitConversionFromDelegate(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (!source.IsDelegateType()) { return false; } // * From any delegate type to System.Delegate // // SPEC OMISSION: // // The spec should actually say // // * From any delegate type to System.Delegate // * From any delegate type to System.MulticastDelegate // * From any delegate type to any interface implemented by System.MulticastDelegate var specialDestination = destination.GetSpecialTypeSafe(); if (specialDestination == SpecialType.System_MulticastDelegate || specialDestination == SpecialType.System_Delegate || IsBaseInterface(destination, this.corLibrary.GetDeclaredSpecialType(SpecialType.System_MulticastDelegate), ref useSiteInfo)) { return true; } // * From any delegate type S to a delegate type T provided S is not T and // S is a delegate convertible to T if (HasDelegateVarianceConversion(source, destination, ref useSiteInfo)) { return true; } return false; } private bool HasImplicitFunctionTypeConversion(FunctionTypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (destination is FunctionTypeSymbol destinationFunctionType) { return HasImplicitFunctionTypeToFunctionTypeConversion(source, destinationFunctionType, ref useSiteInfo); } return IsValidFunctionTypeConversionTarget(destination, ref useSiteInfo); } internal bool IsValidFunctionTypeConversionTarget(TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (destination.SpecialType == SpecialType.System_MulticastDelegate) { return true; } if (destination.IsNonGenericExpressionType()) { return true; } var derivedType = this.corLibrary.GetDeclaredSpecialType(SpecialType.System_MulticastDelegate); if (IsBaseClass(derivedType, destination, ref useSiteInfo) || IsBaseInterface(destination, derivedType, ref useSiteInfo)) { return true; } return false; } private bool HasImplicitFunctionTypeToFunctionTypeConversion(FunctionTypeSymbol sourceType, FunctionTypeSymbol destinationType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var sourceDelegate = sourceType.GetInternalDelegateType(); var destinationDelegate = destinationType.GetInternalDelegateType(); // https://github.com/dotnet/roslyn/issues/55909: We're relying on the variance of // FunctionTypeSymbol.GetInternalDelegateType() which fails for synthesized // delegate types where the type parameters are invariant. return HasDelegateVarianceConversion(sourceDelegate, destinationDelegate, ref useSiteInfo); } #nullable disable public bool HasImplicitTypeParameterConversion(TypeParameterSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (HasImplicitReferenceTypeParameterConversion(source, destination, ref useSiteInfo)) { return true; } if (HasImplicitBoxingTypeParameterConversion(source, destination, ref useSiteInfo)) { return true; } if ((destination.TypeKind == TypeKind.TypeParameter) && source.DependsOn((TypeParameterSymbol)destination)) { return true; } return false; } private bool HasImplicitReferenceTypeParameterConversion(TypeParameterSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (source.IsValueType) { return false; // Not a reference conversion. } // The following implicit conversions exist for a given type parameter T: // // * From T to its effective base class C. // * From T to any base class of C. // * From T to any interface implemented by C (or any interface variance-compatible with such) if (HasImplicitEffectiveBaseConversion(source, destination, ref useSiteInfo)) { return true; } // * From T to any interface type I in T's effective interface set, and // from T to any base interface of I (or any interface variance-compatible with such) if (HasImplicitEffectiveInterfaceSetConversion(source, destination, ref useSiteInfo)) { return true; } // * From T to a type parameter U, provided T depends on U. if ((destination.TypeKind == TypeKind.TypeParameter) && source.DependsOn((TypeParameterSymbol)destination)) { return true; } return false; } // Spec 6.1.10: Implicit conversions involving type parameters private bool HasImplicitEffectiveBaseConversion(TypeParameterSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // * From T to its effective base class C. var effectiveBaseClass = source.EffectiveBaseClass(ref useSiteInfo); if (HasIdentityConversionInternal(effectiveBaseClass, destination)) { return true; } // * From T to any base class of C. if (IsBaseClass(effectiveBaseClass, destination, ref useSiteInfo)) { return true; } // * From T to any interface implemented by C (or any interface variance-compatible with such) if (HasAnyBaseInterfaceConversion(effectiveBaseClass, destination, ref useSiteInfo)) { return true; } return false; } private bool HasImplicitEffectiveInterfaceSetConversion(TypeParameterSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (!destination.IsInterfaceType()) { return false; } // * From T to any interface type I in T's effective interface set, and // from T to any base interface of I (or any interface variance-compatible with such) foreach (var i in source.AllEffectiveInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { if (HasInterfaceVarianceConversion(i, destination, ref useSiteInfo)) { return true; } } return false; } private bool HasAnyBaseInterfaceConversion(TypeSymbol derivedType, TypeSymbol baseType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)derivedType != null); Debug.Assert((object)baseType != null); if (!baseType.IsInterfaceType()) { return false; } var d = derivedType as NamedTypeSymbol; if ((object)d == null) { return false; } foreach (var i in d.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { if (HasInterfaceVarianceConversion(i, baseType, ref useSiteInfo)) { return true; } } return false; } //////////////////////////////////////////////////////////////////////////////// // The rules for variant interface and delegate conversions are the same: // // An interface/delegate type S is convertible to an interface/delegate type T // if and only if T is U<S1, ... Sn> and T is U<T1, ... Tn> such that for all // parameters of U: // // * if the ith parameter of U is invariant then Si is exactly equal to Ti. // * if the ith parameter of U is covariant then either Si is exactly equal // to Ti, or there is an implicit reference conversion from Si to Ti. // * if the ith parameter of U is contravariant then either Si is exactly // equal to Ti, or there is an implicit reference conversion from Ti to Si. private bool HasInterfaceVarianceConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); NamedTypeSymbol s = source as NamedTypeSymbol; NamedTypeSymbol d = destination as NamedTypeSymbol; if ((object)s == null || (object)d == null) { return false; } if (!s.IsInterfaceType() || !d.IsInterfaceType()) { return false; } return HasVariantConversion(s, d, ref useSiteInfo); } private bool HasDelegateVarianceConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); NamedTypeSymbol s = source as NamedTypeSymbol; NamedTypeSymbol d = destination as NamedTypeSymbol; if ((object)s == null || (object)d == null) { return false; } if (!s.IsDelegateType() || !d.IsDelegateType()) { return false; } return HasVariantConversion(s, d, ref useSiteInfo); } private bool HasVariantConversion(NamedTypeSymbol source, NamedTypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // We check for overflows in HasVariantConversion, because they are only an issue // in the presence of contravariant type parameters, which are not involved in // most conversions. // See VarianceTests for examples (e.g. TestVarianceConversionCycle, // TestVarianceConversionInfiniteExpansion). // // CONSIDER: A more rigorous solution would mimic the CLI approach, which uses // a combination of requiring finite instantiation closures (see section 9.2 of // the CLI spec) and records previous conversion steps to check for cycles. if (currentRecursionDepth >= MaximumRecursionDepth) { // NOTE: The spec doesn't really address what happens if there's an overflow // in our conversion check. It's sort of implied that the conversion "proof" // should be finite, so we'll just say that no conversion is possible. return false; } // Do a quick check up front to avoid instantiating a new Conversions object, // if possible. var quickResult = HasVariantConversionQuick(source, destination); if (quickResult.HasValue()) { return quickResult.Value(); } return this.CreateInstance(currentRecursionDepth + 1). HasVariantConversionNoCycleCheck(source, destination, ref useSiteInfo); } private ThreeState HasVariantConversionQuick(NamedTypeSymbol source, NamedTypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (HasIdentityConversionInternal(source, destination)) { return ThreeState.True; } NamedTypeSymbol typeSymbol = source.OriginalDefinition; if (!TypeSymbol.Equals(typeSymbol, destination.OriginalDefinition, TypeCompareKind.ConsiderEverything2)) { return ThreeState.False; } return ThreeState.Unknown; } private bool HasVariantConversionNoCycleCheck(NamedTypeSymbol source, NamedTypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); var typeParameters = ArrayBuilder<TypeWithAnnotations>.GetInstance(); var sourceTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); var destinationTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); try { source.OriginalDefinition.GetAllTypeArguments(typeParameters, ref useSiteInfo); source.GetAllTypeArguments(sourceTypeArguments, ref useSiteInfo); destination.GetAllTypeArguments(destinationTypeArguments, ref useSiteInfo); Debug.Assert(TypeSymbol.Equals(source.OriginalDefinition, destination.OriginalDefinition, TypeCompareKind.AllIgnoreOptions)); Debug.Assert(typeParameters.Count == sourceTypeArguments.Count); Debug.Assert(typeParameters.Count == destinationTypeArguments.Count); for (int paramIndex = 0; paramIndex < typeParameters.Count; ++paramIndex) { var sourceTypeArgument = sourceTypeArguments[paramIndex]; var destinationTypeArgument = destinationTypeArguments[paramIndex]; // If they're identical then this one is automatically good, so skip it. if (HasIdentityConversionInternal(sourceTypeArgument.Type, destinationTypeArgument.Type) && HasTopLevelNullabilityIdentityConversion(sourceTypeArgument, destinationTypeArgument)) { continue; } TypeParameterSymbol typeParameterSymbol = (TypeParameterSymbol)typeParameters[paramIndex].Type; switch (typeParameterSymbol.Variance) { case VarianceKind.None: // System.IEquatable<T> is invariant for back compat reasons (dynamic type checks could start // to succeed where they previously failed, creating different runtime behavior), but the uses // require treatment specifically of nullability as contravariant, so we special case the // behavior here. Normally we use GetWellKnownType for these kinds of checks, but in this // case we don't want just the canonical IEquatable to be special-cased, we want all definitions // to be treated as contravariant, in case there are other definitions in metadata that were // compiled with that expectation. if (isTypeIEquatable(destination.OriginalDefinition) && TypeSymbol.Equals(destinationTypeArgument.Type, sourceTypeArgument.Type, TypeCompareKind.AllNullableIgnoreOptions) && HasAnyNullabilityImplicitConversion(destinationTypeArgument, sourceTypeArgument)) { return true; } return false; case VarianceKind.Out: if (!HasImplicitReferenceConversion(sourceTypeArgument, destinationTypeArgument, ref useSiteInfo)) { return false; } break; case VarianceKind.In: if (!HasImplicitReferenceConversion(destinationTypeArgument, sourceTypeArgument, ref useSiteInfo)) { return false; } break; default: throw ExceptionUtilities.UnexpectedValue(typeParameterSymbol.Variance); } } } finally { typeParameters.Free(); sourceTypeArguments.Free(); destinationTypeArguments.Free(); } return true; static bool isTypeIEquatable(NamedTypeSymbol type) { return type is { IsInterface: true, Name: "IEquatable", ContainingNamespace: { Name: "System", ContainingNamespace: { IsGlobalNamespace: true } }, ContainingSymbol: { Kind: SymbolKind.Namespace }, TypeParameters: { Length: 1 } }; } } // Spec 6.1.10 private bool HasImplicitBoxingTypeParameterConversion(TypeParameterSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (source.IsReferenceType) { return false; // Not a boxing conversion; both source and destination are references. } // The following implicit conversions exist for a given type parameter T: // // * From T to its effective base class C. // * From T to any base class of C. // * From T to any interface implemented by C (or any interface variance-compatible with such) if (HasImplicitEffectiveBaseConversion(source, destination, ref useSiteInfo)) { return true; } // * From T to any interface type I in T's effective interface set, and // from T to any base interface of I (or any interface variance-compatible with such) if (HasImplicitEffectiveInterfaceSetConversion(source, destination, ref useSiteInfo)) { return true; } // SPEC: From T to a type parameter U, provided T depends on U if ((destination.TypeKind == TypeKind.TypeParameter) && source.DependsOn((TypeParameterSymbol)destination)) { return true; } // SPEC: From T to a reference type I if it has an implicit conversion to a reference // SPEC: type S0 and S0 has an identity conversion to S. At run-time the conversion // SPEC: is executed the same way as the conversion to S0. // REVIEW: If T is not known to be a reference type then the only way this clause can // REVIEW: come into effect is if the target type is dynamic. Is that correct? if (destination.Kind == SymbolKind.DynamicType) { return true; } return false; } public bool HasBoxingConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // Certain type parameter conversions are classified as boxing conversions. if ((source.TypeKind == TypeKind.TypeParameter) && HasImplicitBoxingTypeParameterConversion((TypeParameterSymbol)source, destination, ref useSiteInfo)) { return true; } // The rest of the boxing conversions only operate when going from a value type to a // reference type. if (!source.IsValueType || !destination.IsReferenceType) { return false; } // A boxing conversion exists from a nullable type to a reference type if and only if a // boxing conversion exists from the underlying type. if (source.IsNullableType()) { return HasBoxingConversion(source.GetNullableUnderlyingType(), destination, ref useSiteInfo); } // A boxing conversion exists from any non-nullable value type to object and dynamic, to // System.ValueType, and to any interface type variance-compatible with one implemented // by the non-nullable value type. // Furthermore, an enum type can be converted to the type System.Enum. // We set the base class of the structs to System.ValueType, System.Enum, etc, so we can // just check here. // There are a couple of exceptions. The very special types ArgIterator, ArgumentHandle and // TypedReference are not boxable: if (source.IsRestrictedType()) { return false; } if (destination.Kind == SymbolKind.DynamicType) { return !source.IsPointerOrFunctionPointer(); } if (IsBaseClass(source, destination, ref useSiteInfo)) { return true; } if (HasAnyBaseInterfaceConversion(source, destination, ref useSiteInfo)) { return true; } return false; } internal static bool HasImplicitPointerToVoidConversion(TypeSymbol source, TypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // SPEC: The set of implicit conversions is extended to include... // SPEC: ... from any pointer type to the type void*. return source.IsPointerOrFunctionPointer() && destination is PointerTypeSymbol { PointedAtType: { SpecialType: SpecialType.System_Void } }; } #nullable enable internal bool HasImplicitPointerConversion(TypeSymbol? source, TypeSymbol? destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (!(source is FunctionPointerTypeSymbol { Signature: { } sourceSig }) || !(destination is FunctionPointerTypeSymbol { Signature: { } destinationSig })) { return false; } if (sourceSig.ParameterCount != destinationSig.ParameterCount || sourceSig.CallingConvention != destinationSig.CallingConvention) { return false; } if (sourceSig.CallingConvention == Cci.CallingConvention.Unmanaged && !sourceSig.GetCallingConventionModifiers().SetEquals(destinationSig.GetCallingConventionModifiers())) { return false; } for (int i = 0; i < sourceSig.ParameterCount; i++) { var sourceParam = sourceSig.Parameters[i]; var destinationParam = destinationSig.Parameters[i]; if (sourceParam.RefKind != destinationParam.RefKind) { return false; } if (!hasConversion(sourceParam.RefKind, destinationSig.Parameters[i].TypeWithAnnotations, sourceSig.Parameters[i].TypeWithAnnotations, ref useSiteInfo)) { return false; } } return sourceSig.RefKind == destinationSig.RefKind && hasConversion(sourceSig.RefKind, sourceSig.ReturnTypeWithAnnotations, destinationSig.ReturnTypeWithAnnotations, ref useSiteInfo); bool hasConversion(RefKind refKind, TypeWithAnnotations sourceType, TypeWithAnnotations destinationType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { switch (refKind) { case RefKind.None: return (!IncludeNullability || HasTopLevelNullabilityImplicitConversion(sourceType, destinationType)) && (HasIdentityOrImplicitReferenceConversion(sourceType.Type, destinationType.Type, ref useSiteInfo) || HasImplicitPointerToVoidConversion(sourceType.Type, destinationType.Type) || HasImplicitPointerConversion(sourceType.Type, destinationType.Type, ref useSiteInfo)); default: return (!IncludeNullability || HasTopLevelNullabilityIdentityConversion(sourceType, destinationType)) && HasIdentityConversion(sourceType.Type, destinationType.Type); } } } #nullable disable private bool HasIdentityOrReferenceConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (HasIdentityConversionInternal(source, destination)) { return true; } if (HasImplicitReferenceConversion(source, destination, ref useSiteInfo)) { return true; } if (HasExplicitReferenceConversion(source, destination, ref useSiteInfo)) { return true; } return false; } private bool HasExplicitReferenceConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // SPEC: The explicit reference conversions are: // SPEC: From object and dynamic to any other reference type. if (source.SpecialType == SpecialType.System_Object) { if (destination.IsReferenceType) { return true; } } else if (source.Kind == SymbolKind.DynamicType && destination.IsReferenceType) { return true; } // SPEC: From any class-type S to any class-type T, provided S is a base class of T. if (destination.IsClassType() && IsBaseClass(destination, source, ref useSiteInfo)) { return true; } // SPEC: From any class-type S to any interface-type T, provided S is not sealed and provided S does not implement T. // ISSUE: class C : IEnumerable<Mammal> { } converting this to IEnumerable<Animal> is not an explicit conversion, // ISSUE: it is an implicit conversion. if (source.IsClassType() && destination.IsInterfaceType() && !source.IsSealed && !HasAnyBaseInterfaceConversion(source, destination, ref useSiteInfo)) { return true; } // SPEC: From any interface-type S to any class-type T, provided T is not sealed or provided T implements S. // ISSUE: What if T is sealed and implements an interface variance-convertible to S? // ISSUE: eg, sealed class C : IEnum<Mammal> { ... } you should be able to cast an IEnum<Animal> to C. if (source.IsInterfaceType() && destination.IsClassType() && (!destination.IsSealed || HasAnyBaseInterfaceConversion(destination, source, ref useSiteInfo))) { return true; } // SPEC: From any interface-type S to any interface-type T, provided S is not derived from T. // ISSUE: This does not rule out identity conversions, which ought not to be classified as // ISSUE: explicit reference conversions. // ISSUE: IEnumerable<Mammal> and IEnumerable<Animal> do not derive from each other but this is // ISSUE: not an explicit reference conversion, this is an implicit reference conversion. if (source.IsInterfaceType() && destination.IsInterfaceType() && !HasImplicitConversionToInterface(source, destination, ref useSiteInfo)) { return true; } // SPEC: UNDONE: From a reference type to a reference type T if it has an explicit reference conversion to a reference type T0 and T0 has an identity conversion T. // SPEC: UNDONE: From a reference type to an interface or delegate type T if it has an explicit reference conversion to an interface or delegate type T0 and either T0 is variance-convertible to T or T is variance-convertible to T0 (§13.1.3.2). if (HasExplicitArrayConversion(source, destination, ref useSiteInfo)) { return true; } if (HasExplicitDelegateConversion(source, destination, ref useSiteInfo)) { return true; } if (HasExplicitReferenceTypeParameterConversion(source, destination, ref useSiteInfo)) { return true; } return false; } // Spec 6.2.7 Explicit conversions involving type parameters private bool HasExplicitReferenceTypeParameterConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); TypeParameterSymbol s = source as TypeParameterSymbol; TypeParameterSymbol t = destination as TypeParameterSymbol; // SPEC: The following explicit conversions exist for a given type parameter T: // SPEC: If T is known to be a reference type, the conversions are all classified as explicit reference conversions. // SPEC: If T is not known to be a reference type, the conversions are classified as unboxing conversions. // SPEC: From the effective base class C of T to T and from any base class of C to T. if ((object)t != null && t.IsReferenceType) { for (var type = t.EffectiveBaseClass(ref useSiteInfo); (object)type != null; type = type.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { if (HasIdentityConversionInternal(type, source)) { return true; } } } // SPEC: From any interface type to T. if ((object)t != null && source.IsInterfaceType() && t.IsReferenceType) { return true; } // SPEC: From T to any interface-type I provided there is not already an implicit conversion from T to I. if ((object)s != null && s.IsReferenceType && destination.IsInterfaceType() && !HasImplicitReferenceTypeParameterConversion(s, destination, ref useSiteInfo)) { return true; } // SPEC: From a type parameter U to T, provided T depends on U (§10.1.5) if ((object)s != null && (object)t != null && t.IsReferenceType && t.DependsOn(s)) { return true; } return false; } // Spec 6.2.7 Explicit conversions involving type parameters private bool HasUnboxingTypeParameterConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); TypeParameterSymbol s = source as TypeParameterSymbol; TypeParameterSymbol t = destination as TypeParameterSymbol; // SPEC: The following explicit conversions exist for a given type parameter T: // SPEC: If T is known to be a reference type, the conversions are all classified as explicit reference conversions. // SPEC: If T is not known to be a reference type, the conversions are classified as unboxing conversions. // SPEC: From the effective base class C of T to T and from any base class of C to T. if ((object)t != null && !t.IsReferenceType) { for (var type = t.EffectiveBaseClass(ref useSiteInfo); (object)type != null; type = type.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { if (TypeSymbol.Equals(type, source, TypeCompareKind.ConsiderEverything2)) { return true; } } } // SPEC: From any interface type to T. if (source.IsInterfaceType() && (object)t != null && !t.IsReferenceType) { return true; } // SPEC: From T to any interface-type I provided there is not already an implicit conversion from T to I. if ((object)s != null && !s.IsReferenceType && destination.IsInterfaceType() && !HasImplicitReferenceTypeParameterConversion(s, destination, ref useSiteInfo)) { return true; } // SPEC: From a type parameter U to T, provided T depends on U (§10.1.5) if ((object)s != null && (object)t != null && !t.IsReferenceType && t.DependsOn(s)) { return true; } return false; } private bool HasExplicitDelegateConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // SPEC: From System.Delegate and the interfaces it implements to any delegate-type. // We also support System.MulticastDelegate in the implementation, in spite of it not being mentioned in the spec. if (destination.IsDelegateType()) { if (source.SpecialType == SpecialType.System_Delegate || source.SpecialType == SpecialType.System_MulticastDelegate) { return true; } if (HasImplicitConversionToInterface(this.corLibrary.GetDeclaredSpecialType(SpecialType.System_Delegate), source, ref useSiteInfo)) { return true; } } // SPEC: From D<S1...Sn> to a D<T1...Tn> where D<X1...Xn> is a generic delegate type, D<S1...Sn> is not compatible with or identical to D<T1...Tn>, // SPEC: and for each type parameter Xi of D the following holds: // SPEC: If Xi is invariant, then Si is identical to Ti. // SPEC: If Xi is covariant, then there is an implicit or explicit identity or reference conversion from Si to Ti. // SPECL If Xi is contravariant, then Si and Ti are either identical or both reference types. if (!source.IsDelegateType() || !destination.IsDelegateType()) { return false; } if (!TypeSymbol.Equals(source.OriginalDefinition, destination.OriginalDefinition, TypeCompareKind.ConsiderEverything2)) { return false; } var sourceType = (NamedTypeSymbol)source; var destinationType = (NamedTypeSymbol)destination; var original = sourceType.OriginalDefinition; if (HasIdentityConversionInternal(source, destination)) { return false; } if (HasDelegateVarianceConversion(source, destination, ref useSiteInfo)) { return false; } var sourceTypeArguments = sourceType.TypeArgumentsWithDefinitionUseSiteDiagnostics(ref useSiteInfo); var destinationTypeArguments = destinationType.TypeArgumentsWithDefinitionUseSiteDiagnostics(ref useSiteInfo); for (int i = 0; i < sourceTypeArguments.Length; ++i) { var sourceArg = sourceTypeArguments[i].Type; var destinationArg = destinationTypeArguments[i].Type; switch (original.TypeParameters[i].Variance) { case VarianceKind.None: if (!HasIdentityConversionInternal(sourceArg, destinationArg)) { return false; } break; case VarianceKind.Out: if (!HasIdentityOrReferenceConversion(sourceArg, destinationArg, ref useSiteInfo)) { return false; } break; case VarianceKind.In: bool hasIdentityConversion = HasIdentityConversionInternal(sourceArg, destinationArg); bool bothAreReferenceTypes = sourceArg.IsReferenceType && destinationArg.IsReferenceType; if (!(hasIdentityConversion || bothAreReferenceTypes)) { return false; } break; } } return true; } private bool HasExplicitArrayConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); var sourceArray = source as ArrayTypeSymbol; var destinationArray = destination as ArrayTypeSymbol; // SPEC: From an array-type S with an element type SE to an array-type T with an element type TE, provided all of the following are true: // SPEC: S and T differ only in element type. (In other words, S and T have the same number of dimensions.) // SPEC: Both SE and TE are reference-types. // SPEC: An explicit reference conversion exists from SE to TE. if ((object)sourceArray != null && (object)destinationArray != null) { // HasExplicitReferenceConversion checks that SE and TE are reference types so // there's no need for that check here. Moreover, it's not as simple as checking // IsReferenceType, at least not in the case of type parameters, since SE will be // considered a reference type implicitly in the case of "where TE : class, SE" even // though SE.IsReferenceType may be false. Again, HasExplicitReferenceConversion // already handles these cases. return sourceArray.HasSameShapeAs(destinationArray) && HasExplicitReferenceConversion(sourceArray.ElementType, destinationArray.ElementType, ref useSiteInfo); } // SPEC: From System.Array and the interfaces it implements to any array-type. if ((object)destinationArray != null) { if (source.SpecialType == SpecialType.System_Array) { return true; } foreach (var iface in this.corLibrary.GetDeclaredSpecialType(SpecialType.System_Array).AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { if (HasIdentityConversionInternal(iface, source)) { return true; } } } // SPEC: From a single-dimensional array type S[] to System.Collections.Generic.IList<T> and its base interfaces // SPEC: provided that there is an explicit reference conversion from S to T. // The framework now also allows arrays to be converted to IReadOnlyList<T> and IReadOnlyCollection<T>; we // honor that as well. if ((object)sourceArray != null && sourceArray.IsSZArray && destination.IsPossibleArrayGenericInterface()) { if (HasExplicitReferenceConversion(sourceArray.ElementType, ((NamedTypeSymbol)destination).TypeArgumentWithDefinitionUseSiteDiagnostics(0, ref useSiteInfo).Type, ref useSiteInfo)) { return true; } } // SPEC: From System.Collections.Generic.IList<S> and its base interfaces to a single-dimensional array type T[], // provided that there is an explicit identity or reference conversion from S to T. // Similarly, we honor IReadOnlyList<S> and IReadOnlyCollection<S> in the same way. if ((object)destinationArray != null && destinationArray.IsSZArray) { var specialDefinition = ((TypeSymbol)source.OriginalDefinition).SpecialType; if (specialDefinition == SpecialType.System_Collections_Generic_IList_T || specialDefinition == SpecialType.System_Collections_Generic_ICollection_T || specialDefinition == SpecialType.System_Collections_Generic_IEnumerable_T || specialDefinition == SpecialType.System_Collections_Generic_IReadOnlyList_T || specialDefinition == SpecialType.System_Collections_Generic_IReadOnlyCollection_T) { var sourceElement = ((NamedTypeSymbol)source).TypeArgumentWithDefinitionUseSiteDiagnostics(0, ref useSiteInfo).Type; var destinationElement = destinationArray.ElementType; if (HasIdentityConversionInternal(sourceElement, destinationElement)) { return true; } if (HasImplicitReferenceConversion(sourceElement, destinationElement, ref useSiteInfo)) { return true; } if (HasExplicitReferenceConversion(sourceElement, destinationElement, ref useSiteInfo)) { return true; } } } return false; } private bool HasUnboxingConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (destination.IsPointerOrFunctionPointer()) { return false; } // Ref-like types cannot be boxed or unboxed if (destination.IsRestrictedType()) { return false; } // SPEC: An unboxing conversion permits a reference type to be explicitly converted to a value-type. // SPEC: An unboxing conversion exists from the types object and System.ValueType to any non-nullable-value-type, var specialTypeSource = source.SpecialType; if (specialTypeSource == SpecialType.System_Object || specialTypeSource == SpecialType.System_ValueType) { if (destination.IsValueType && !destination.IsNullableType()) { return true; } } // SPEC: and from any interface-type to any non-nullable-value-type that implements the interface-type. if (source.IsInterfaceType() && destination.IsValueType && !destination.IsNullableType() && HasBoxingConversion(destination, source, ref useSiteInfo)) { return true; } // SPEC: Furthermore type System.Enum can be unboxed to any enum-type. if (source.SpecialType == SpecialType.System_Enum && destination.IsEnumType()) { return true; } // SPEC: An unboxing conversion exists from a reference type to a nullable-type if an unboxing // SPEC: conversion exists from the reference type to the underlying non-nullable-value-type // SPEC: of the nullable-type. if (source.IsReferenceType && destination.IsNullableType() && HasUnboxingConversion(source, destination.GetNullableUnderlyingType(), ref useSiteInfo)) { return true; } // SPEC: UNDONE A value type S has an unboxing conversion from an interface type I if it has an unboxing // SPEC: UNDONE conversion from an interface type I0 and I0 has an identity conversion to I. // SPEC: UNDONE A value type S has an unboxing conversion from an interface type I if it has an unboxing conversion // SPEC: UNDONE from an interface or delegate type I0 and either I0 is variance-convertible to I or I is variance-convertible to I0. if (HasUnboxingTypeParameterConversion(source, destination, ref useSiteInfo)) { return true; } return false; } private static bool HasPointerToPointerConversion(TypeSymbol source, TypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); return source.IsPointerOrFunctionPointer() && destination.IsPointerOrFunctionPointer(); } private static bool HasPointerToIntegerConversion(TypeSymbol source, TypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (!source.IsPointerOrFunctionPointer()) { return false; } // SPEC OMISSION: // // The spec should state that any pointer type is convertible to // sbyte, byte, ... etc, or any corresponding nullable type. return IsIntegerTypeSupportingPointerConversions(destination.StrippedType()); } private static bool HasIntegerToPointerConversion(TypeSymbol source, TypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (!destination.IsPointerOrFunctionPointer()) { return false; } // Note that void* is convertible to int?, but int? is not convertible to void*. return IsIntegerTypeSupportingPointerConversions(source); } private static bool IsIntegerTypeSupportingPointerConversions(TypeSymbol type) { switch (type.SpecialType) { case SpecialType.System_SByte: case SpecialType.System_Byte: case SpecialType.System_Int16: case SpecialType.System_UInt16: case SpecialType.System_Int32: case SpecialType.System_UInt32: case SpecialType.System_Int64: case SpecialType.System_UInt64: return true; case SpecialType.System_IntPtr: case SpecialType.System_UIntPtr: return type.IsNativeIntegerType; } return false; } } }
1
dotnet/roslyn
56,416
Do not include function type conversions in user-defined conversions
Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
cston
"2021-09-15T18:16:38Z"
"2021-09-24T23:24:46Z"
bb99d0bc89bde01650d2a694d720d600dd952dcb
3913f352cf066fa485869d866e4753fa721cbe93
Do not include function type conversions in user-defined conversions. Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
./src/Compilers/CSharp/Portable/Binder/Semantics/Conversions/UserDefinedImplicitConversions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal abstract partial class ConversionsBase { /// <remarks> /// NOTE: Keep this method in sync with <see cref="AnalyzeImplicitUserDefinedConversionForV6SwitchGoverningType"/>. /// </remarks> private UserDefinedConversionResult AnalyzeImplicitUserDefinedConversions( BoundExpression sourceExpression, TypeSymbol source, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(sourceExpression != null || (object)source != null); Debug.Assert((object)target != null); // User-defined conversions that involve generics can be quite strange. There // are two basic problems: first, that generic user-defined conversions can be // "shadowed" by built-in conversions, and second, that generic user-defined // conversions can make conversions that would never have been legal user-defined // conversions if declared non-generically. I call this latter kind of conversion // a "suspicious" conversion. // // The shadowed conversions are easily dealt with: // // SPEC: If a predefined implicit conversion exists from a type S to type T, // SPEC: all user-defined conversions, implicit or explicit, are ignored. // SPEC: If a predefined explicit conversion exists from a type S to type T, // SPEC: any user-defined explicit conversion from S to T are ignored. // // The rule above can come into play in cases like: // // sealed class C<T> { public static implicit operator T(C<T> c) { ... } } // C<object> c = whatever; // object o = c; // // The built-in implicit conversion from C<object> to object must shadow // the user-defined implicit conversion. // // The caller of this method checks for user-defined conversions *after* // predefined implicit conversions, so we already know that if we got here, // there was no predefined implicit conversion. // // Note that a user-defined *implicit* conversion may win over a built-in // *explicit* conversion by the rule given above. That is, if we created // an implicit conversion from T to C<T>, then the user-defined implicit // conversion from object to C<object> could be valid, even though that // would be "replacing" a built-in explicit conversion with a user-defined // implicit conversion. This is one of the "suspicious" conversions, // as it would not be legal to declare a user-defined conversion from // object in a non-generic type. // // The way the native compiler handles suspicious conversions involving // interfaces is neither sensible nor in line with the rules in the // specification. It is not clear at this time whether we should be exactly // matching the native compiler, the specification, or neither, in Roslyn. // Spec (6.4.4 User-defined implicit conversions) // A user-defined implicit conversion from an expression E to type T is processed as follows: // SPEC: Find the set of types D from which user-defined conversion operators... var d = ArrayBuilder<TypeSymbol>.GetInstance(); ComputeUserDefinedImplicitConversionTypeSet(source, target, d, ref useSiteInfo); // SPEC: Find the set of applicable user-defined and lifted conversion operators, U... var ubuild = ArrayBuilder<UserDefinedConversionAnalysis>.GetInstance(); ComputeApplicableUserDefinedImplicitConversionSet(sourceExpression, source, target, d, ubuild, ref useSiteInfo); d.Free(); ImmutableArray<UserDefinedConversionAnalysis> u = ubuild.ToImmutableAndFree(); // SPEC: If U is empty, the conversion is undefined and a compile-time error occurs. if (u.Length == 0) { return UserDefinedConversionResult.NoApplicableOperators(u); } // SPEC: Find the most specific source type SX of the operators in U... TypeSymbol sx = MostSpecificSourceTypeForImplicitUserDefinedConversion(u, source, ref useSiteInfo); if ((object)sx == null) { return UserDefinedConversionResult.NoBestSourceType(u); } // SPEC: Find the most specific target type TX of the operators in U... TypeSymbol tx = MostSpecificTargetTypeForImplicitUserDefinedConversion(u, target, ref useSiteInfo); if ((object)tx == null) { return UserDefinedConversionResult.NoBestTargetType(u); } int? best = MostSpecificConversionOperator(sx, tx, u); if (best == null) { return UserDefinedConversionResult.Ambiguous(u); } return UserDefinedConversionResult.Valid(u, best.Value); } private static void ComputeUserDefinedImplicitConversionTypeSet(TypeSymbol s, TypeSymbol t, ArrayBuilder<TypeSymbol> d, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // Spec 6.4.4: User-defined implicit conversions // Find the set of types D from which user-defined conversion operators // will be considered. This set consists of S0 (if S0 is a class or struct), // the base classes of S0 (if S0 is a class), and T0 (if T0 is a class or struct). AddTypesParticipatingInUserDefinedConversion(d, s, includeBaseTypes: true, useSiteInfo: ref useSiteInfo); AddTypesParticipatingInUserDefinedConversion(d, t, includeBaseTypes: false, useSiteInfo: ref useSiteInfo); } /// <summary> /// This method find the set of applicable user-defined and lifted conversion operators, u. /// The set consists of the user-defined and lifted implicit conversion operators declared by /// the classes and structs in d that convert from a type encompassing source to a type encompassed by target. /// However if allowAnyTarget is true, then it considers all operators that convert from a type encompassing source /// to any target. This flag must be set only if we are computing user defined conversions from a given source /// type to any target type. /// </summary> /// <remarks> /// Currently allowAnyTarget flag is only set to true by <see cref="AnalyzeImplicitUserDefinedConversionForV6SwitchGoverningType"/>, /// where we must consider user defined implicit conversions from the type of the switch expression to /// any of the possible switch governing types. /// </remarks> private void ComputeApplicableUserDefinedImplicitConversionSet( BoundExpression sourceExpression, TypeSymbol source, TypeSymbol target, ArrayBuilder<TypeSymbol> d, ArrayBuilder<UserDefinedConversionAnalysis> u, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool allowAnyTarget = false) { Debug.Assert(sourceExpression != null || (object)source != null); Debug.Assert(((object)target != null) == !allowAnyTarget); Debug.Assert(d != null); Debug.Assert(u != null); // SPEC: Find the set of applicable user-defined and lifted conversion operators, U. // SPEC: The set consists of the user-defined and lifted implicit conversion operators // SPEC: declared by the classes and structs in D that convert from a type encompassing // SPEC: E to a type encompassed by T. If U is empty, the conversion is undefined and // SPEC: a compile-time error occurs. // SPEC: Give a user-defined conversion operator that converts from a non-nullable // SPEC: value type S to a non-nullable value type T, a lifted conversion operator // SPEC: exists that converts from S? to T?. // DELIBERATE SPEC VIOLATION: // // The spec here essentially says that we add an applicable "regular" conversion and // an applicable lifted conversion, if there is one, to the candidate set, and then // let them duke it out to determine which one is "best". // // This is not at all what the native compiler does, and attempting to implement // the specification, or slight variations on it, produces too many backwards-compatibility // breaking changes. // // The native compiler deviates from the specification in two major ways here. // First, it does not add *both* the regular and lifted forms to the candidate set. // Second, the way it characterizes a "lifted" form is very, very different from // how the specification characterizes a lifted form. // // An operation, in this case, X-->Y, is properly said to be "lifted" to X?-->Y? via // the rule that X?-->Y? matches the behavior of X-->Y for non-null X, and converts // null X to null Y otherwise. // // The native compiler, by contrast, takes the existing operator and "lifts" either // the operator's parameter type or the operator's return type to nullable. For // example, a conversion from X?-->Y would be "lifted" to X?-->Y? by making the // conversion from X? to Y, and then from Y to Y?. No "lifting" semantics // are imposed; we do not check to see if the X? is null. This operator is not // actually "lifted" at all; rather, an implicit conversion is applied to the // output. **The native compiler considers the result type Y? of that standard implicit // conversion to be the result type of the "lifted" conversion**, rather than // properly considering Y to be the result type of the conversion for the purposes // of computing the best output type. // // MOREOVER: the native compiler actually *does* implement nullable lifting semantics // in the case where the input type of the user-defined conversion is a non-nullable // value type and the output type is a nullable value type **or pointer type, or // reference type**. This is an enormous departure from the specification; the // native compiler will take a user-defined conversion from X-->Y? or X-->C and "lift" // it to a conversion from X?-->Y? or X?-->C that has nullable semantics. // // This is quite confusing. In this code we will classify the conversion as either // "normal" or "lifted" on the basis of *whether or not special lifting semantics // are to be applied*. That is, whether or not a later rewriting pass is going to // need to insert a check to see if the source expression is null, and decide // whether or not to call the underlying unlifted conversion or produce a null // value without calling the unlifted conversion. // DELIBERATE SPEC VIOLATION (See bug 17021) // The specification defines a type U as "encompassing" a type V // if there is a standard implicit conversion from U to V, and // neither are interface types. // // The intention of this language is to ensure that we do not allow user-defined // conversions that involve interfaces. We have a reasonable expectation that a // conversion that involves an interface is one that preserves referential identity, // and user-defined conversions usually do not. // // Now, suppose we have a standard conversion from Alpha to Beta, a user-defined // conversion from Beta to Gamma, and a standard conversion from Gamma to Delta. // The specification allows the implicit conversion from Alpha to Delta only if // Beta encompasses Alpha and Delta encompasses Gamma. And therefore, none of them // can be interface types, de jure. // // However, the dev10 compiler only checks Alpha and Delta to see if they are interfaces, // and allows Beta and Gamma to be interfaces. // // So what's the big deal there? It's not legal to define a user-defined conversion where // the input or output types are interfaces, right? // // It is not legal to define such a conversion, no, but it is legal to create one via generic // construction. If we have a conversion from T to C<T>, then C<I> has a conversion from I to C<I>. // // The dev10 compiler fails to check for this situation. This means that, // you can convert from int to C<IComparable> because int implements IComparable, but cannot // convert from IComparable to C<IComparable>! // // Unfortunately, we know of several real programs that rely upon this bug, so we are going // to reproduce it here. if ((object)source != null && source.IsInterfaceType() || (object)target != null && target.IsInterfaceType()) { return; } HashSet<NamedTypeSymbol> lookedInInterfaces = null; foreach (TypeSymbol declaringType in d) { if (declaringType is TypeParameterSymbol typeParameter) { ImmutableArray<NamedTypeSymbol> interfaceTypes = typeParameter.AllEffectiveInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo); if (!interfaceTypes.IsEmpty) { lookedInInterfaces ??= new HashSet<NamedTypeSymbol>(Symbols.SymbolEqualityComparer.AllIgnoreOptions); // Equivalent to has identity conversion check foreach (var interfaceType in interfaceTypes) { if (lookedInInterfaces.Add(interfaceType)) { addCandidatesFromType(constrainedToTypeOpt: typeParameter, interfaceType, sourceExpression, source, target, u, ref useSiteInfo, allowAnyTarget); } } } } else { addCandidatesFromType(constrainedToTypeOpt: null, (NamedTypeSymbol)declaringType, sourceExpression, source, target, u, ref useSiteInfo, allowAnyTarget); } } void addCandidatesFromType( TypeParameterSymbol constrainedToTypeOpt, NamedTypeSymbol declaringType, BoundExpression sourceExpression, TypeSymbol source, TypeSymbol target, ArrayBuilder<UserDefinedConversionAnalysis> u, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool allowAnyTarget) { foreach (MethodSymbol op in declaringType.GetOperators(WellKnownMemberNames.ImplicitConversionName)) { // We might have a bad operator and be in an error recovery situation. Ignore it. if (op.ReturnsVoid || op.ParameterCount != 1) { continue; } TypeSymbol convertsFrom = op.GetParameterType(0); TypeSymbol convertsTo = op.ReturnType; Conversion fromConversion = EncompassingImplicitConversion(sourceExpression, source, convertsFrom, ref useSiteInfo); Conversion toConversion = allowAnyTarget ? Conversion.Identity : EncompassingImplicitConversion(null, convertsTo, target, ref useSiteInfo); if (fromConversion.Exists && toConversion.Exists) { // There is an additional spec violation in the native compiler. Suppose // we have a conversion from X-->Y and are asked to do "Y? y = new X();" Clearly // the intention is to convert from X-->Y via the implicit conversion, and then // stick a standard implicit conversion from Y-->Y? on the back end. **In this // situation, the native compiler treats the conversion as though it were // actually X-->Y? in source for the purposes of determining the best target // type of an operator. // // We perpetuate this fiction here. if ((object)target != null && target.IsNullableType() && convertsTo.IsNonNullableValueType()) { convertsTo = MakeNullableType(convertsTo); toConversion = allowAnyTarget ? Conversion.Identity : EncompassingImplicitConversion(null, convertsTo, target, ref useSiteInfo); } u.Add(UserDefinedConversionAnalysis.Normal(constrainedToTypeOpt, op, fromConversion, toConversion, convertsFrom, convertsTo)); } else if ((object)source != null && source.IsNullableType() && convertsFrom.IsNonNullableValueType() && (allowAnyTarget || target.CanBeAssignedNull())) { // As mentioned above, here we diverge from the specification, in two ways. // First, we only check for the lifted form if the normal form was inapplicable. // Second, we are supposed to apply lifting semantics only if the conversion // parameter and return types are *both* non-nullable value types. // // In fact the native compiler determines whether to check for a lifted form on // the basis of: // // * Is the type we are ultimately converting from a nullable value type? // * Is the parameter type of the conversion a non-nullable value type? // * Is the type we are ultimately converting to a nullable value type, // pointer type, or reference type? // // If the answer to all those questions is "yes" then we lift to nullable // and see if the resulting operator is applicable. TypeSymbol nullableFrom = MakeNullableType(convertsFrom); TypeSymbol nullableTo = convertsTo.IsNonNullableValueType() ? MakeNullableType(convertsTo) : convertsTo; Conversion liftedFromConversion = EncompassingImplicitConversion(sourceExpression, source, nullableFrom, ref useSiteInfo); Conversion liftedToConversion = !allowAnyTarget ? EncompassingImplicitConversion(null, nullableTo, target, ref useSiteInfo) : Conversion.Identity; if (liftedFromConversion.Exists && liftedToConversion.Exists) { u.Add(UserDefinedConversionAnalysis.Lifted(constrainedToTypeOpt, op, liftedFromConversion, liftedToConversion, nullableFrom, nullableTo)); } } } } } private TypeSymbol MostSpecificSourceTypeForImplicitUserDefinedConversion(ImmutableArray<UserDefinedConversionAnalysis> u, TypeSymbol source, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: If any of the operators in U convert from S then SX is S. if ((object)source != null) { if (u.Any(conv => TypeSymbol.Equals(conv.FromType, source, TypeCompareKind.ConsiderEverything2))) { return source; } } // SPEC: Otherwise, SX is the most encompassed type in the set of // SPEC: source types of the operators in U. return MostEncompassedType(u, conv => conv.FromType, ref useSiteInfo); } private TypeSymbol MostSpecificTargetTypeForImplicitUserDefinedConversion(ImmutableArray<UserDefinedConversionAnalysis> u, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: If any of the operators in U convert to T then TX is T. // SPEC: Otherwise, TX is the most encompassing type in the set of // SPEC: target types of the operators in U. // DELIBERATE SPEC VIOLATION: // The native compiler deviates from the specification in the way it // determines what the "converts to" type is. The specification is pretty // clear that the "converts to" type is the actual return type of the // conversion operator, or, in the case of a lifted operator, the lifted-to- // nullable type. That is, if we have X-->Y then the converts-to type of // the operator in its normal form is Y, and the converts-to type of the // operator in its lifted form is Y?. // // The native compiler does not do this. Suppose we have a user-defined // conversion X-->Y, and the assignment Y? y = new X(); -- the native // compiler will consider the converts-to type of X-->Y to be Y?, surprisingly // enough. // // We have previously written the appropriate "ToType" into the conversion analysis // to perpetuate this fiction. if (u.Any(conv => TypeSymbol.Equals(conv.ToType, target, TypeCompareKind.ConsiderEverything2))) { return target; } return MostEncompassingType(u, conv => conv.ToType, ref useSiteInfo); } private static int LiftingCount(UserDefinedConversionAnalysis conv) { int count = 0; if (!TypeSymbol.Equals(conv.FromType, conv.Operator.GetParameterType(0), TypeCompareKind.ConsiderEverything2)) { count += 1; } if (!TypeSymbol.Equals(conv.ToType, conv.Operator.ReturnType, TypeCompareKind.ConsiderEverything2)) { count += 1; } return count; } private static int? MostSpecificConversionOperator(TypeSymbol sx, TypeSymbol tx, ImmutableArray<UserDefinedConversionAnalysis> u) { return MostSpecificConversionOperator(conv => TypeSymbol.Equals(conv.FromType, sx, TypeCompareKind.ConsiderEverything2) && TypeSymbol.Equals(conv.ToType, tx, TypeCompareKind.ConsiderEverything2), u); } /// <summary> /// Find the most specific among a set of conversion operators, with the given constraint on the conversion. /// </summary> private static int? MostSpecificConversionOperator(Func<UserDefinedConversionAnalysis, bool> constraint, ImmutableArray<UserDefinedConversionAnalysis> u) { // SPEC: If U contains exactly one user-defined conversion operator from SX to TX // SPEC: then that is the most-specific conversion operator; // // SPEC: Otherwise, if U contains exactly one lifted conversion operator that converts from // SPEC: SX to TX then this is the most specific operator. // // SPEC: Otherwise, the conversion is ambiguous and a compile-time error occurs. // // SPEC ERROR: // // Clearly the text above cannot be correct because it gives undesirable results. // Suppose we have structs E and F with an implicit user defined conversion from // F to E. We have an assignment from F to E?. Clearly what should happen is // we should convert F to E, then convert E to E?. But the spec says that this // should be an error. Why? Because both F-->E and F?-->E? are added to the candidate // set. What is SX? Clearly F, because there is a candidate that takes an F. // What is TX? Clearly E? because there is a candidate that returns an E?. // And now the overload resolution problem is ambiguous because neither operator // takes SX and returns TX. // // DELIBERATE SPEC VIOLATION: // // The native compiler takes a rather different approach than the approach described // in the specification. Rather than adding both the lifted and unlifted forms of // each operator to the candidate set, using those operators to determine the best // source and target types, and then choosing the unique operator from that source type // to that target type, it instead *transforms in place* the "from" and "to" types // of each operator so that their nullability matches those of the source and target // types. This can then lead to ambiguities; consider for example a type that // has user defined conversions X-->Y and X-->Y?. If we have a conversion from X to // Y?, the spec would say that the operators X-->Y, its lifted form X?-->Y?, and // X-->Y? are applicable candidates and that the best of them is X-->Y?. // // The native compiler arrives at the same conclusion but by different logic; it says // that X-->Y has a "half lifted" form X-->Y?, and that it is "worse" than X-->Y? // because it is half lifted. // Therefore we match this behavior by first checking to see if there is a unique // best operator that converts from the source type to the target type with liftings // on neither side. BestIndex bestUnlifted = UniqueIndex(u, conv => constraint(conv) && LiftingCount(conv) == 0); if (bestUnlifted.Kind == BestIndexKind.Best) { return bestUnlifted.Best; } else if (bestUnlifted.Kind == BestIndexKind.Ambiguous) { // If we got an ambiguity, don't continue. We need to bail immediately. // UNDONE: We can do better error reporting if we return the ambiguity and // use that in the error message. return null; } // There was no fully-unlifted operator. Check to see if there was any *half-lifted* operator. // // For example, suppose we had a conversion from X-->Y?, and lifted it to X?-->Y?. (The spec // says not to do such a lifting because Y? is not a non-nullable value type, but the native // compiler does so and we are being compatible with it.) That would be a half-lifted operator. // // For example, suppose we had a conversion from X-->Y, and the assignment Y? y = new X(); -- // this would also be a "half lifted" conversion even though there is no "lifting" going on // (in the sense that we are not checking the source to see if it is null.) // BestIndex bestHalfLifted = UniqueIndex(u, conv => constraint(conv) && LiftingCount(conv) == 1); if (bestHalfLifted.Kind == BestIndexKind.Best) { return bestHalfLifted.Best; } else if (bestHalfLifted.Kind == BestIndexKind.Ambiguous) { // UNDONE: We can do better error reporting if we return the ambiguity and // use that in the error message. return null; } // Finally, see if there is a unique best *fully lifted* operator. BestIndex bestFullyLifted = UniqueIndex(u, conv => constraint(conv) && LiftingCount(conv) == 2); if (bestFullyLifted.Kind == BestIndexKind.Best) { return bestFullyLifted.Best; } else if (bestFullyLifted.Kind == BestIndexKind.Ambiguous) { // UNDONE: We can do better error reporting if we return the ambiguity and // use that in the error message. return null; } return null; } // Return the index of the *unique* item in the array that matches the predicate, // or null if there is not one. private static BestIndex UniqueIndex<T>(ImmutableArray<T> items, Func<T, bool> predicate) { if (items.IsEmpty) { return BestIndex.None(); } int? result = null; for (int i = 0; i < items.Length; ++i) { if (predicate(items[i])) { if (result == null) { result = i; } else { // Not unique. return BestIndex.IsAmbiguous(result.Value, i); } } } return result == null ? BestIndex.None() : BestIndex.HasBest(result.Value); } // Is A encompassed by B? private bool IsEncompassedBy(BoundExpression aExpr, TypeSymbol a, TypeSymbol b, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)a != null); Debug.Assert((object)b != null); // SPEC: If a standard implicit conversion exists from a type A to a type B // SPEC: and if neither A nor B is an interface type then A is said to be // SPEC: encompassed by B, and B is said to encompass A. return EncompassingImplicitConversion(aExpr, a, b, ref useSiteInfo).Exists; } private Conversion EncompassingImplicitConversion(BoundExpression aExpr, TypeSymbol a, TypeSymbol b, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(aExpr != null || (object)a != null); Debug.Assert((object)b != null); // DELIBERATE SPEC VIOLATION: // We ought to be saying that an encompassing conversion never exists when one of // the types is an interface type, but due to a desire to be compatible with a // dev10 bug, we allow it. See the comment regarding bug 17021 above for more details. var result = ClassifyStandardImplicitConversion(aExpr, a, b, ref useSiteInfo); return IsEncompassingImplicitConversionKind(result.Kind) ? result : Conversion.NoConversion; } private static bool IsEncompassingImplicitConversionKind(ConversionKind kind) { switch (kind) { // Doesn't even exist. case ConversionKind.NoConversion: // These are conversions from expression and do not apply. // Specifically disallowed because there would be subtle consequences for the overload betterness rules. case ConversionKind.ImplicitDynamic: case ConversionKind.MethodGroup: case ConversionKind.AnonymousFunction: case ConversionKind.InterpolatedString: case ConversionKind.SwitchExpression: case ConversionKind.ConditionalExpression: case ConversionKind.ImplicitEnumeration: case ConversionKind.StackAllocToPointerType: case ConversionKind.StackAllocToSpanType: // Not "standard". case ConversionKind.ImplicitUserDefined: case ConversionKind.ExplicitUserDefined: // Not implicit. case ConversionKind.ExplicitNumeric: case ConversionKind.ExplicitEnumeration: case ConversionKind.ExplicitNullable: case ConversionKind.ExplicitReference: case ConversionKind.Unboxing: case ConversionKind.ExplicitDynamic: case ConversionKind.ExplicitPointerToPointer: case ConversionKind.ExplicitPointerToInteger: case ConversionKind.ExplicitIntegerToPointer: case ConversionKind.IntPtr: case ConversionKind.ExplicitTupleLiteral: case ConversionKind.ExplicitTuple: return false; // Spec'd in C# 4. case ConversionKind.Identity: case ConversionKind.ImplicitNumeric: case ConversionKind.ImplicitNullable: case ConversionKind.ImplicitReference: case ConversionKind.Boxing: case ConversionKind.ImplicitConstant: case ConversionKind.ImplicitPointerToVoid: // Added to spec in Roslyn timeframe. case ConversionKind.NullLiteral: case ConversionKind.ImplicitNullToPointer: // Added for C# 7. case ConversionKind.ImplicitTupleLiteral: case ConversionKind.ImplicitTuple: case ConversionKind.ImplicitThrow: // Added for C# 7.1 case ConversionKind.DefaultLiteral: return true; default: throw ExceptionUtilities.UnexpectedValue(kind); } } private TypeSymbol MostEncompassedType<T>( ImmutableArray<T> items, Func<T, TypeSymbol> extract, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { return MostEncompassedType<T>(items, x => true, extract, ref useSiteInfo); } private TypeSymbol MostEncompassedType<T>( ImmutableArray<T> items, Func<T, bool> valid, Func<T, TypeSymbol> extract, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: The most encompassed type is the one type in the set that // SPEC: is encompassed by all the other types. // We have a bit of a graph theory problem here. Suppose hypothetically // speaking we have three types in the set such that: // // X is encompassed by Y // X is encompassed by Z // Y is encompassed by X // // In that situation, X is the unique type in the set that is encompassed // by all the other types, despite the fact that it appears to be neither // better nor worse than Y! // // But in practice this situation never arises because implicit convertibility // is transitive; if Y is implicitly convertible to X and X is implicitly convertible // to Z, then Y is implicitly convertible to Z. // // Because we have this transitivity, we can rephrase the problem as follows: // // Find the unique best type in the set, where the best type is the type that is // better than every other type. By "X is better than Y" we mean "X is encompassed // by Y but Y is not encompassed by X". CompoundUseSiteInfo<AssemblySymbol> inLambdaUseSiteInfo = useSiteInfo; int? best = UniqueBestValidIndex(items, valid, (left, right) => { TypeSymbol leftType = extract(left); TypeSymbol rightType = extract(right); if (TypeSymbol.Equals(leftType, rightType, TypeCompareKind.ConsiderEverything2)) { return BetterResult.Equal; } bool leftWins = IsEncompassedBy(null, leftType, rightType, ref inLambdaUseSiteInfo); bool rightWins = IsEncompassedBy(null, rightType, leftType, ref inLambdaUseSiteInfo); if (leftWins == rightWins) { return BetterResult.Neither; } return leftWins ? BetterResult.Left : BetterResult.Right; }); useSiteInfo = inLambdaUseSiteInfo; return best == null ? null : extract(items[best.Value]); } private TypeSymbol MostEncompassingType<T>( ImmutableArray<T> items, Func<T, TypeSymbol> extract, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { return MostEncompassingType<T>(items, x => true, extract, ref useSiteInfo); } private TypeSymbol MostEncompassingType<T>( ImmutableArray<T> items, Func<T, bool> valid, Func<T, TypeSymbol> extract, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // See comments above. CompoundUseSiteInfo<AssemblySymbol> inLambdaUseSiteInfo = useSiteInfo; int? best = UniqueBestValidIndex(items, valid, (left, right) => { TypeSymbol leftType = extract(left); TypeSymbol rightType = extract(right); if (TypeSymbol.Equals(leftType, rightType, TypeCompareKind.ConsiderEverything2)) { return BetterResult.Equal; } bool leftWins = IsEncompassedBy(null, rightType, leftType, ref inLambdaUseSiteInfo); bool rightWins = IsEncompassedBy(null, leftType, rightType, ref inLambdaUseSiteInfo); if (leftWins == rightWins) { return BetterResult.Neither; } return leftWins ? BetterResult.Left : BetterResult.Right; }); useSiteInfo = inLambdaUseSiteInfo; return best == null ? null : extract(items[best.Value]); } // This method takes an array of items and a predicate which filters out the valid items. // From the valid items we find the index of the *unique best item* in the array. // In order for a valid item x to be considered best, x must be better than every other // item. The "better" relation must be consistent; that is: // // better(x,y) == Left requires that better(y,x) == Right // better(x,y) == Right requires that better(y,x) == Left // better(x,y) == Neither requires that better(y,x) == Neither // // It is possible for the array to contain the same item twice; if it does then // the duplicate is ignored. That is, having the "best" item twice does not preclude // it from being the best. // UNDONE: Update this to give a BestIndex result that indicates ambiguity. private static int? UniqueBestValidIndex<T>(ImmutableArray<T> items, Func<T, bool> valid, Func<T, T, BetterResult> better) { if (items.IsEmpty) { return null; } int? candidateIndex = null; T candidateItem = default(T); for (int currentIndex = 0; currentIndex < items.Length; ++currentIndex) { T currentItem = items[currentIndex]; if (!valid(currentItem)) { continue; } if (candidateIndex == null) { candidateIndex = currentIndex; candidateItem = currentItem; continue; } BetterResult result = better(candidateItem, currentItem); if (result == BetterResult.Equal) { // The list had the same item twice. Just ignore it. continue; } else if (result == BetterResult.Neither) { // Neither the current item nor the candidate item are better, // and therefore neither of them can be the best. We no longer // have a candidate for best item. candidateIndex = null; candidateItem = default(T); } else if (result == BetterResult.Right) { // The candidate is worse than the current item, so replace it // with the current item. candidateIndex = currentIndex; candidateItem = currentItem; } // Otherwise, the candidate is better than the current item, so // it continues to be the candidate. } if (candidateIndex == null) { return null; } // We had a candidate that was better than everything that came *after* it. // Now verify that it was better than everything that came before it. for (int currentIndex = 0; currentIndex < candidateIndex.Value; ++currentIndex) { T currentItem = items[currentIndex]; if (!valid(currentItem)) { continue; } BetterResult result = better(candidateItem, currentItem); if (result != BetterResult.Left && result != BetterResult.Equal) { // The candidate was not better than everything that came before it. There is // no best item. return null; } } // The candidate was better than everything that came before it. return candidateIndex; } private NamedTypeSymbol MakeNullableType(TypeSymbol type) { var nullable = this.corLibrary.GetDeclaredSpecialType(SpecialType.System_Nullable_T); return nullable.Construct(type); } /// <remarks> /// NOTE: Keep this method in sync with AnalyzeImplicitUserDefinedConversion. /// </remarks> protected UserDefinedConversionResult AnalyzeImplicitUserDefinedConversionForV6SwitchGoverningType(TypeSymbol source, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: The governing type of a switch statement is established by the switch expression. // SPEC: 1) If the type of the switch expression is sbyte, byte, short, ushort, int, uint, // SPEC: long, ulong, bool, char, string, or an enum-type, or if it is the nullable type // SPEC: corresponding to one of these types, then that is the governing type of the switch statement. // SPEC: 2) Otherwise, exactly one user-defined implicit conversion (§6.4) must exist from the // SPEC: type of the switch expression to one of the following possible governing types: // SPEC: sbyte, byte, short, ushort, int, uint, long, ulong, char, string, or, a nullable type // SPEC: corresponding to one of those types // NOTE: This method implements part (2) above, it should be called only if (1) is false for source type. Debug.Assert((object)source != null); Debug.Assert(!source.IsValidV6SwitchGoverningType()); // NOTE: For (2) we use an approach similar to native compiler's approach, but call into the common code for analyzing user defined implicit conversions. // NOTE: (a) Compute the set of types D from which user-defined conversion operators should be considered by considering only the source type. // NOTE: (b) Instead of computing applicable user defined implicit conversions U from the source type to a specific target type, // NOTE: we compute these from the source type to ANY target type. // NOTE: (c) From the conversions in U, select the most specific of them that targets a valid switch governing type // SPEC VIOLATION: Because we use the same strategy for computing the most specific conversion, as the Dev10 compiler did (in fact // SPEC VIOLATION: we share the code), we inherit any spec deviances in that analysis. Specifically, the analysis only considers // SPEC VIOLATION: which conversion has the least amount of lifting, where a conversion may be considered to be in unlifted form, // SPEC VIOLATION: half-lifted form (only the argument type or return type is lifted) or fully lifted form. The most specific computation // SPEC VIOLATION: looks for a unique conversion that is least lifted. The spec, on the other hand, requires that the conversion // SPEC VIOLATION: be *unique*, not merely most use the least amount of lifting among the applicable conversions. // SPEC VIOLATION: This introduces a SPEC VIOLATION for the following tests in the native compiler: // NOTE: // See test SwitchTests.CS0166_AggregateTypeWithMultipleImplicitConversions_07 // NOTE: struct Conv // NOTE: { // NOTE: public static implicit operator int (Conv C) { return 1; } // NOTE: public static implicit operator int (Conv? C2) { return 0; } // NOTE: public static int Main() // NOTE: { // NOTE: Conv? D = new Conv(); // NOTE: switch(D) // NOTE: { ... // SPEC VIOLATION: Native compiler allows the above code to compile // SPEC VIOLATION: even though there are two user-defined implicit conversions: // SPEC VIOLATION: 1) To int type (applicable in normal form): public static implicit operator int (Conv? C2) // SPEC VIOLATION: 2) To int? type (applicable in lifted form): public static implicit operator int (Conv C) // NOTE: // See also test SwitchTests.TODO // NOTE: struct Conv // NOTE: { // NOTE: public static implicit operator int? (Conv C) { return 1; } // NOTE: public static implicit operator string (Conv? C2) { return 0; } // NOTE: public static int Main() // NOTE: { // NOTE: Conv? D = new Conv(); // NOTE: switch(D) // NOTE: { ... // SPEC VIOLATION: Native compiler allows the above code to compile too // SPEC VIOLATION: even though there are two user-defined implicit conversions: // SPEC VIOLATION: 1) To string type (applicable in normal form): public static implicit operator string (Conv? C2) // SPEC VIOLATION: 2) To int? type (applicable in half-lifted form): public static implicit operator int? (Conv C) // SPEC VIOLATION: This occurs because the native compiler compares the applicable conversions to find one with the least amount // SPEC VIOLATION: of lifting, ignoring whether the return types are the same or not. // SPEC VIOLATION: We do the same to maintain compatibility with the native compiler. // (a) Compute the set of types D from which user-defined conversion operators should be considered by considering only the source type. var d = ArrayBuilder<TypeSymbol>.GetInstance(); ComputeUserDefinedImplicitConversionTypeSet(source, t: null, d: d, useSiteInfo: ref useSiteInfo); // (b) Instead of computing applicable user defined implicit conversions U from the source type to a specific target type, // we compute these from the source type to ANY target type. We will filter out those that are valid switch governing // types later. var ubuild = ArrayBuilder<UserDefinedConversionAnalysis>.GetInstance(); ComputeApplicableUserDefinedImplicitConversionSet(null, source, target: null, d: d, u: ubuild, useSiteInfo: ref useSiteInfo, allowAnyTarget: true); d.Free(); ImmutableArray<UserDefinedConversionAnalysis> u = ubuild.ToImmutableAndFree(); // (c) Find that conversion with the least amount of lifting int? best = MostSpecificConversionOperator(conv => conv.ToType.IsValidV6SwitchGoverningType(isTargetTypeOfUserDefinedOp: true), u); if (best != null) { return UserDefinedConversionResult.Valid(u, best.Value); } return UserDefinedConversionResult.NoApplicableOperators(u); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal abstract partial class ConversionsBase { /// <remarks> /// NOTE: Keep this method in sync with <see cref="AnalyzeImplicitUserDefinedConversionForV6SwitchGoverningType"/>. /// </remarks> private UserDefinedConversionResult AnalyzeImplicitUserDefinedConversions( BoundExpression sourceExpression, TypeSymbol source, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(sourceExpression != null || (object)source != null); Debug.Assert((object)target != null); // User-defined conversions that involve generics can be quite strange. There // are two basic problems: first, that generic user-defined conversions can be // "shadowed" by built-in conversions, and second, that generic user-defined // conversions can make conversions that would never have been legal user-defined // conversions if declared non-generically. I call this latter kind of conversion // a "suspicious" conversion. // // The shadowed conversions are easily dealt with: // // SPEC: If a predefined implicit conversion exists from a type S to type T, // SPEC: all user-defined conversions, implicit or explicit, are ignored. // SPEC: If a predefined explicit conversion exists from a type S to type T, // SPEC: any user-defined explicit conversion from S to T are ignored. // // The rule above can come into play in cases like: // // sealed class C<T> { public static implicit operator T(C<T> c) { ... } } // C<object> c = whatever; // object o = c; // // The built-in implicit conversion from C<object> to object must shadow // the user-defined implicit conversion. // // The caller of this method checks for user-defined conversions *after* // predefined implicit conversions, so we already know that if we got here, // there was no predefined implicit conversion. // // Note that a user-defined *implicit* conversion may win over a built-in // *explicit* conversion by the rule given above. That is, if we created // an implicit conversion from T to C<T>, then the user-defined implicit // conversion from object to C<object> could be valid, even though that // would be "replacing" a built-in explicit conversion with a user-defined // implicit conversion. This is one of the "suspicious" conversions, // as it would not be legal to declare a user-defined conversion from // object in a non-generic type. // // The way the native compiler handles suspicious conversions involving // interfaces is neither sensible nor in line with the rules in the // specification. It is not clear at this time whether we should be exactly // matching the native compiler, the specification, or neither, in Roslyn. // Spec (6.4.4 User-defined implicit conversions) // A user-defined implicit conversion from an expression E to type T is processed as follows: // SPEC: Find the set of types D from which user-defined conversion operators... var d = ArrayBuilder<TypeSymbol>.GetInstance(); ComputeUserDefinedImplicitConversionTypeSet(source, target, d, ref useSiteInfo); // SPEC: Find the set of applicable user-defined and lifted conversion operators, U... var ubuild = ArrayBuilder<UserDefinedConversionAnalysis>.GetInstance(); ComputeApplicableUserDefinedImplicitConversionSet(sourceExpression, source, target, d, ubuild, ref useSiteInfo); d.Free(); ImmutableArray<UserDefinedConversionAnalysis> u = ubuild.ToImmutableAndFree(); // SPEC: If U is empty, the conversion is undefined and a compile-time error occurs. if (u.Length == 0) { return UserDefinedConversionResult.NoApplicableOperators(u); } // SPEC: Find the most specific source type SX of the operators in U... TypeSymbol sx = MostSpecificSourceTypeForImplicitUserDefinedConversion(u, source, ref useSiteInfo); if ((object)sx == null) { return UserDefinedConversionResult.NoBestSourceType(u); } // SPEC: Find the most specific target type TX of the operators in U... TypeSymbol tx = MostSpecificTargetTypeForImplicitUserDefinedConversion(u, target, ref useSiteInfo); if ((object)tx == null) { return UserDefinedConversionResult.NoBestTargetType(u); } int? best = MostSpecificConversionOperator(sx, tx, u); if (best == null) { return UserDefinedConversionResult.Ambiguous(u); } return UserDefinedConversionResult.Valid(u, best.Value); } private static void ComputeUserDefinedImplicitConversionTypeSet(TypeSymbol s, TypeSymbol t, ArrayBuilder<TypeSymbol> d, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // Spec 6.4.4: User-defined implicit conversions // Find the set of types D from which user-defined conversion operators // will be considered. This set consists of S0 (if S0 is a class or struct), // the base classes of S0 (if S0 is a class), and T0 (if T0 is a class or struct). AddTypesParticipatingInUserDefinedConversion(d, s, includeBaseTypes: true, useSiteInfo: ref useSiteInfo); AddTypesParticipatingInUserDefinedConversion(d, t, includeBaseTypes: false, useSiteInfo: ref useSiteInfo); } /// <summary> /// This method find the set of applicable user-defined and lifted conversion operators, u. /// The set consists of the user-defined and lifted implicit conversion operators declared by /// the classes and structs in d that convert from a type encompassing source to a type encompassed by target. /// However if allowAnyTarget is true, then it considers all operators that convert from a type encompassing source /// to any target. This flag must be set only if we are computing user defined conversions from a given source /// type to any target type. /// </summary> /// <remarks> /// Currently allowAnyTarget flag is only set to true by <see cref="AnalyzeImplicitUserDefinedConversionForV6SwitchGoverningType"/>, /// where we must consider user defined implicit conversions from the type of the switch expression to /// any of the possible switch governing types. /// </remarks> private void ComputeApplicableUserDefinedImplicitConversionSet( BoundExpression sourceExpression, TypeSymbol source, TypeSymbol target, ArrayBuilder<TypeSymbol> d, ArrayBuilder<UserDefinedConversionAnalysis> u, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool allowAnyTarget = false) { Debug.Assert(sourceExpression != null || (object)source != null); Debug.Assert(((object)target != null) == !allowAnyTarget); Debug.Assert(d != null); Debug.Assert(u != null); // SPEC: Find the set of applicable user-defined and lifted conversion operators, U. // SPEC: The set consists of the user-defined and lifted implicit conversion operators // SPEC: declared by the classes and structs in D that convert from a type encompassing // SPEC: E to a type encompassed by T. If U is empty, the conversion is undefined and // SPEC: a compile-time error occurs. // SPEC: Give a user-defined conversion operator that converts from a non-nullable // SPEC: value type S to a non-nullable value type T, a lifted conversion operator // SPEC: exists that converts from S? to T?. // DELIBERATE SPEC VIOLATION: // // The spec here essentially says that we add an applicable "regular" conversion and // an applicable lifted conversion, if there is one, to the candidate set, and then // let them duke it out to determine which one is "best". // // This is not at all what the native compiler does, and attempting to implement // the specification, or slight variations on it, produces too many backwards-compatibility // breaking changes. // // The native compiler deviates from the specification in two major ways here. // First, it does not add *both* the regular and lifted forms to the candidate set. // Second, the way it characterizes a "lifted" form is very, very different from // how the specification characterizes a lifted form. // // An operation, in this case, X-->Y, is properly said to be "lifted" to X?-->Y? via // the rule that X?-->Y? matches the behavior of X-->Y for non-null X, and converts // null X to null Y otherwise. // // The native compiler, by contrast, takes the existing operator and "lifts" either // the operator's parameter type or the operator's return type to nullable. For // example, a conversion from X?-->Y would be "lifted" to X?-->Y? by making the // conversion from X? to Y, and then from Y to Y?. No "lifting" semantics // are imposed; we do not check to see if the X? is null. This operator is not // actually "lifted" at all; rather, an implicit conversion is applied to the // output. **The native compiler considers the result type Y? of that standard implicit // conversion to be the result type of the "lifted" conversion**, rather than // properly considering Y to be the result type of the conversion for the purposes // of computing the best output type. // // MOREOVER: the native compiler actually *does* implement nullable lifting semantics // in the case where the input type of the user-defined conversion is a non-nullable // value type and the output type is a nullable value type **or pointer type, or // reference type**. This is an enormous departure from the specification; the // native compiler will take a user-defined conversion from X-->Y? or X-->C and "lift" // it to a conversion from X?-->Y? or X?-->C that has nullable semantics. // // This is quite confusing. In this code we will classify the conversion as either // "normal" or "lifted" on the basis of *whether or not special lifting semantics // are to be applied*. That is, whether or not a later rewriting pass is going to // need to insert a check to see if the source expression is null, and decide // whether or not to call the underlying unlifted conversion or produce a null // value without calling the unlifted conversion. // DELIBERATE SPEC VIOLATION (See bug 17021) // The specification defines a type U as "encompassing" a type V // if there is a standard implicit conversion from U to V, and // neither are interface types. // // The intention of this language is to ensure that we do not allow user-defined // conversions that involve interfaces. We have a reasonable expectation that a // conversion that involves an interface is one that preserves referential identity, // and user-defined conversions usually do not. // // Now, suppose we have a standard conversion from Alpha to Beta, a user-defined // conversion from Beta to Gamma, and a standard conversion from Gamma to Delta. // The specification allows the implicit conversion from Alpha to Delta only if // Beta encompasses Alpha and Delta encompasses Gamma. And therefore, none of them // can be interface types, de jure. // // However, the dev10 compiler only checks Alpha and Delta to see if they are interfaces, // and allows Beta and Gamma to be interfaces. // // So what's the big deal there? It's not legal to define a user-defined conversion where // the input or output types are interfaces, right? // // It is not legal to define such a conversion, no, but it is legal to create one via generic // construction. If we have a conversion from T to C<T>, then C<I> has a conversion from I to C<I>. // // The dev10 compiler fails to check for this situation. This means that, // you can convert from int to C<IComparable> because int implements IComparable, but cannot // convert from IComparable to C<IComparable>! // // Unfortunately, we know of several real programs that rely upon this bug, so we are going // to reproduce it here. if ((object)source != null && source.IsInterfaceType() || (object)target != null && target.IsInterfaceType()) { return; } HashSet<NamedTypeSymbol> lookedInInterfaces = null; foreach (TypeSymbol declaringType in d) { if (declaringType is TypeParameterSymbol typeParameter) { ImmutableArray<NamedTypeSymbol> interfaceTypes = typeParameter.AllEffectiveInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo); if (!interfaceTypes.IsEmpty) { lookedInInterfaces ??= new HashSet<NamedTypeSymbol>(Symbols.SymbolEqualityComparer.AllIgnoreOptions); // Equivalent to has identity conversion check foreach (var interfaceType in interfaceTypes) { if (lookedInInterfaces.Add(interfaceType)) { addCandidatesFromType(constrainedToTypeOpt: typeParameter, interfaceType, sourceExpression, source, target, u, ref useSiteInfo, allowAnyTarget); } } } } else { addCandidatesFromType(constrainedToTypeOpt: null, (NamedTypeSymbol)declaringType, sourceExpression, source, target, u, ref useSiteInfo, allowAnyTarget); } } void addCandidatesFromType( TypeParameterSymbol constrainedToTypeOpt, NamedTypeSymbol declaringType, BoundExpression sourceExpression, TypeSymbol source, TypeSymbol target, ArrayBuilder<UserDefinedConversionAnalysis> u, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool allowAnyTarget) { foreach (MethodSymbol op in declaringType.GetOperators(WellKnownMemberNames.ImplicitConversionName)) { // We might have a bad operator and be in an error recovery situation. Ignore it. if (op.ReturnsVoid || op.ParameterCount != 1) { continue; } TypeSymbol convertsFrom = op.GetParameterType(0); TypeSymbol convertsTo = op.ReturnType; Conversion fromConversion = EncompassingImplicitConversion(sourceExpression, source, convertsFrom, ref useSiteInfo); Conversion toConversion = allowAnyTarget ? Conversion.Identity : EncompassingImplicitConversion(null, convertsTo, target, ref useSiteInfo); if (fromConversion.Exists && toConversion.Exists) { // There is an additional spec violation in the native compiler. Suppose // we have a conversion from X-->Y and are asked to do "Y? y = new X();" Clearly // the intention is to convert from X-->Y via the implicit conversion, and then // stick a standard implicit conversion from Y-->Y? on the back end. **In this // situation, the native compiler treats the conversion as though it were // actually X-->Y? in source for the purposes of determining the best target // type of an operator. // // We perpetuate this fiction here. if ((object)target != null && target.IsNullableType() && convertsTo.IsNonNullableValueType()) { convertsTo = MakeNullableType(convertsTo); toConversion = allowAnyTarget ? Conversion.Identity : EncompassingImplicitConversion(null, convertsTo, target, ref useSiteInfo); } u.Add(UserDefinedConversionAnalysis.Normal(constrainedToTypeOpt, op, fromConversion, toConversion, convertsFrom, convertsTo)); } else if ((object)source != null && source.IsNullableType() && convertsFrom.IsNonNullableValueType() && (allowAnyTarget || target.CanBeAssignedNull())) { // As mentioned above, here we diverge from the specification, in two ways. // First, we only check for the lifted form if the normal form was inapplicable. // Second, we are supposed to apply lifting semantics only if the conversion // parameter and return types are *both* non-nullable value types. // // In fact the native compiler determines whether to check for a lifted form on // the basis of: // // * Is the type we are ultimately converting from a nullable value type? // * Is the parameter type of the conversion a non-nullable value type? // * Is the type we are ultimately converting to a nullable value type, // pointer type, or reference type? // // If the answer to all those questions is "yes" then we lift to nullable // and see if the resulting operator is applicable. TypeSymbol nullableFrom = MakeNullableType(convertsFrom); TypeSymbol nullableTo = convertsTo.IsNonNullableValueType() ? MakeNullableType(convertsTo) : convertsTo; Conversion liftedFromConversion = EncompassingImplicitConversion(sourceExpression, source, nullableFrom, ref useSiteInfo); Conversion liftedToConversion = !allowAnyTarget ? EncompassingImplicitConversion(null, nullableTo, target, ref useSiteInfo) : Conversion.Identity; if (liftedFromConversion.Exists && liftedToConversion.Exists) { u.Add(UserDefinedConversionAnalysis.Lifted(constrainedToTypeOpt, op, liftedFromConversion, liftedToConversion, nullableFrom, nullableTo)); } } } } } private TypeSymbol MostSpecificSourceTypeForImplicitUserDefinedConversion(ImmutableArray<UserDefinedConversionAnalysis> u, TypeSymbol source, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: If any of the operators in U convert from S then SX is S. if ((object)source != null) { if (u.Any(conv => TypeSymbol.Equals(conv.FromType, source, TypeCompareKind.ConsiderEverything2))) { return source; } } // SPEC: Otherwise, SX is the most encompassed type in the set of // SPEC: source types of the operators in U. return MostEncompassedType(u, conv => conv.FromType, ref useSiteInfo); } private TypeSymbol MostSpecificTargetTypeForImplicitUserDefinedConversion(ImmutableArray<UserDefinedConversionAnalysis> u, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: If any of the operators in U convert to T then TX is T. // SPEC: Otherwise, TX is the most encompassing type in the set of // SPEC: target types of the operators in U. // DELIBERATE SPEC VIOLATION: // The native compiler deviates from the specification in the way it // determines what the "converts to" type is. The specification is pretty // clear that the "converts to" type is the actual return type of the // conversion operator, or, in the case of a lifted operator, the lifted-to- // nullable type. That is, if we have X-->Y then the converts-to type of // the operator in its normal form is Y, and the converts-to type of the // operator in its lifted form is Y?. // // The native compiler does not do this. Suppose we have a user-defined // conversion X-->Y, and the assignment Y? y = new X(); -- the native // compiler will consider the converts-to type of X-->Y to be Y?, surprisingly // enough. // // We have previously written the appropriate "ToType" into the conversion analysis // to perpetuate this fiction. if (u.Any(conv => TypeSymbol.Equals(conv.ToType, target, TypeCompareKind.ConsiderEverything2))) { return target; } return MostEncompassingType(u, conv => conv.ToType, ref useSiteInfo); } private static int LiftingCount(UserDefinedConversionAnalysis conv) { int count = 0; if (!TypeSymbol.Equals(conv.FromType, conv.Operator.GetParameterType(0), TypeCompareKind.ConsiderEverything2)) { count += 1; } if (!TypeSymbol.Equals(conv.ToType, conv.Operator.ReturnType, TypeCompareKind.ConsiderEverything2)) { count += 1; } return count; } private static int? MostSpecificConversionOperator(TypeSymbol sx, TypeSymbol tx, ImmutableArray<UserDefinedConversionAnalysis> u) { return MostSpecificConversionOperator(conv => TypeSymbol.Equals(conv.FromType, sx, TypeCompareKind.ConsiderEverything2) && TypeSymbol.Equals(conv.ToType, tx, TypeCompareKind.ConsiderEverything2), u); } /// <summary> /// Find the most specific among a set of conversion operators, with the given constraint on the conversion. /// </summary> private static int? MostSpecificConversionOperator(Func<UserDefinedConversionAnalysis, bool> constraint, ImmutableArray<UserDefinedConversionAnalysis> u) { // SPEC: If U contains exactly one user-defined conversion operator from SX to TX // SPEC: then that is the most-specific conversion operator; // // SPEC: Otherwise, if U contains exactly one lifted conversion operator that converts from // SPEC: SX to TX then this is the most specific operator. // // SPEC: Otherwise, the conversion is ambiguous and a compile-time error occurs. // // SPEC ERROR: // // Clearly the text above cannot be correct because it gives undesirable results. // Suppose we have structs E and F with an implicit user defined conversion from // F to E. We have an assignment from F to E?. Clearly what should happen is // we should convert F to E, then convert E to E?. But the spec says that this // should be an error. Why? Because both F-->E and F?-->E? are added to the candidate // set. What is SX? Clearly F, because there is a candidate that takes an F. // What is TX? Clearly E? because there is a candidate that returns an E?. // And now the overload resolution problem is ambiguous because neither operator // takes SX and returns TX. // // DELIBERATE SPEC VIOLATION: // // The native compiler takes a rather different approach than the approach described // in the specification. Rather than adding both the lifted and unlifted forms of // each operator to the candidate set, using those operators to determine the best // source and target types, and then choosing the unique operator from that source type // to that target type, it instead *transforms in place* the "from" and "to" types // of each operator so that their nullability matches those of the source and target // types. This can then lead to ambiguities; consider for example a type that // has user defined conversions X-->Y and X-->Y?. If we have a conversion from X to // Y?, the spec would say that the operators X-->Y, its lifted form X?-->Y?, and // X-->Y? are applicable candidates and that the best of them is X-->Y?. // // The native compiler arrives at the same conclusion but by different logic; it says // that X-->Y has a "half lifted" form X-->Y?, and that it is "worse" than X-->Y? // because it is half lifted. // Therefore we match this behavior by first checking to see if there is a unique // best operator that converts from the source type to the target type with liftings // on neither side. BestIndex bestUnlifted = UniqueIndex(u, conv => constraint(conv) && LiftingCount(conv) == 0); if (bestUnlifted.Kind == BestIndexKind.Best) { return bestUnlifted.Best; } else if (bestUnlifted.Kind == BestIndexKind.Ambiguous) { // If we got an ambiguity, don't continue. We need to bail immediately. // UNDONE: We can do better error reporting if we return the ambiguity and // use that in the error message. return null; } // There was no fully-unlifted operator. Check to see if there was any *half-lifted* operator. // // For example, suppose we had a conversion from X-->Y?, and lifted it to X?-->Y?. (The spec // says not to do such a lifting because Y? is not a non-nullable value type, but the native // compiler does so and we are being compatible with it.) That would be a half-lifted operator. // // For example, suppose we had a conversion from X-->Y, and the assignment Y? y = new X(); -- // this would also be a "half lifted" conversion even though there is no "lifting" going on // (in the sense that we are not checking the source to see if it is null.) // BestIndex bestHalfLifted = UniqueIndex(u, conv => constraint(conv) && LiftingCount(conv) == 1); if (bestHalfLifted.Kind == BestIndexKind.Best) { return bestHalfLifted.Best; } else if (bestHalfLifted.Kind == BestIndexKind.Ambiguous) { // UNDONE: We can do better error reporting if we return the ambiguity and // use that in the error message. return null; } // Finally, see if there is a unique best *fully lifted* operator. BestIndex bestFullyLifted = UniqueIndex(u, conv => constraint(conv) && LiftingCount(conv) == 2); if (bestFullyLifted.Kind == BestIndexKind.Best) { return bestFullyLifted.Best; } else if (bestFullyLifted.Kind == BestIndexKind.Ambiguous) { // UNDONE: We can do better error reporting if we return the ambiguity and // use that in the error message. return null; } return null; } // Return the index of the *unique* item in the array that matches the predicate, // or null if there is not one. private static BestIndex UniqueIndex<T>(ImmutableArray<T> items, Func<T, bool> predicate) { if (items.IsEmpty) { return BestIndex.None(); } int? result = null; for (int i = 0; i < items.Length; ++i) { if (predicate(items[i])) { if (result == null) { result = i; } else { // Not unique. return BestIndex.IsAmbiguous(result.Value, i); } } } return result == null ? BestIndex.None() : BestIndex.HasBest(result.Value); } // Is A encompassed by B? private bool IsEncompassedBy(BoundExpression aExpr, TypeSymbol a, TypeSymbol b, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)a != null); Debug.Assert((object)b != null); // SPEC: If a standard implicit conversion exists from a type A to a type B // SPEC: and if neither A nor B is an interface type then A is said to be // SPEC: encompassed by B, and B is said to encompass A. return EncompassingImplicitConversion(aExpr, a, b, ref useSiteInfo).Exists; } private Conversion EncompassingImplicitConversion(BoundExpression aExpr, TypeSymbol a, TypeSymbol b, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(aExpr != null || (object)a != null); Debug.Assert((object)b != null); // DELIBERATE SPEC VIOLATION: // We ought to be saying that an encompassing conversion never exists when one of // the types is an interface type, but due to a desire to be compatible with a // dev10 bug, we allow it. See the comment regarding bug 17021 above for more details. var result = ClassifyStandardImplicitConversion(aExpr, a, b, ref useSiteInfo); return IsEncompassingImplicitConversionKind(result.Kind) ? result : Conversion.NoConversion; } private static bool IsEncompassingImplicitConversionKind(ConversionKind kind) { switch (kind) { // Doesn't even exist. case ConversionKind.NoConversion: // These are conversions from expression and do not apply. // Specifically disallowed because there would be subtle consequences for the overload betterness rules. case ConversionKind.ImplicitDynamic: case ConversionKind.MethodGroup: case ConversionKind.AnonymousFunction: case ConversionKind.InterpolatedString: case ConversionKind.SwitchExpression: case ConversionKind.ConditionalExpression: case ConversionKind.ImplicitEnumeration: case ConversionKind.StackAllocToPointerType: case ConversionKind.StackAllocToSpanType: // Not "standard". case ConversionKind.ImplicitUserDefined: case ConversionKind.ExplicitUserDefined: case ConversionKind.FunctionType: // Not implicit. case ConversionKind.ExplicitNumeric: case ConversionKind.ExplicitEnumeration: case ConversionKind.ExplicitNullable: case ConversionKind.ExplicitReference: case ConversionKind.Unboxing: case ConversionKind.ExplicitDynamic: case ConversionKind.ExplicitPointerToPointer: case ConversionKind.ExplicitPointerToInteger: case ConversionKind.ExplicitIntegerToPointer: case ConversionKind.IntPtr: case ConversionKind.ExplicitTupleLiteral: case ConversionKind.ExplicitTuple: return false; // Spec'd in C# 4. case ConversionKind.Identity: case ConversionKind.ImplicitNumeric: case ConversionKind.ImplicitNullable: case ConversionKind.ImplicitReference: case ConversionKind.Boxing: case ConversionKind.ImplicitConstant: case ConversionKind.ImplicitPointerToVoid: // Added to spec in Roslyn timeframe. case ConversionKind.NullLiteral: case ConversionKind.ImplicitNullToPointer: // Added for C# 7. case ConversionKind.ImplicitTupleLiteral: case ConversionKind.ImplicitTuple: case ConversionKind.ImplicitThrow: // Added for C# 7.1 case ConversionKind.DefaultLiteral: return true; default: throw ExceptionUtilities.UnexpectedValue(kind); } } private TypeSymbol MostEncompassedType<T>( ImmutableArray<T> items, Func<T, TypeSymbol> extract, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { return MostEncompassedType<T>(items, x => true, extract, ref useSiteInfo); } private TypeSymbol MostEncompassedType<T>( ImmutableArray<T> items, Func<T, bool> valid, Func<T, TypeSymbol> extract, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: The most encompassed type is the one type in the set that // SPEC: is encompassed by all the other types. // We have a bit of a graph theory problem here. Suppose hypothetically // speaking we have three types in the set such that: // // X is encompassed by Y // X is encompassed by Z // Y is encompassed by X // // In that situation, X is the unique type in the set that is encompassed // by all the other types, despite the fact that it appears to be neither // better nor worse than Y! // // But in practice this situation never arises because implicit convertibility // is transitive; if Y is implicitly convertible to X and X is implicitly convertible // to Z, then Y is implicitly convertible to Z. // // Because we have this transitivity, we can rephrase the problem as follows: // // Find the unique best type in the set, where the best type is the type that is // better than every other type. By "X is better than Y" we mean "X is encompassed // by Y but Y is not encompassed by X". CompoundUseSiteInfo<AssemblySymbol> inLambdaUseSiteInfo = useSiteInfo; int? best = UniqueBestValidIndex(items, valid, (left, right) => { TypeSymbol leftType = extract(left); TypeSymbol rightType = extract(right); if (TypeSymbol.Equals(leftType, rightType, TypeCompareKind.ConsiderEverything2)) { return BetterResult.Equal; } bool leftWins = IsEncompassedBy(null, leftType, rightType, ref inLambdaUseSiteInfo); bool rightWins = IsEncompassedBy(null, rightType, leftType, ref inLambdaUseSiteInfo); if (leftWins == rightWins) { return BetterResult.Neither; } return leftWins ? BetterResult.Left : BetterResult.Right; }); useSiteInfo = inLambdaUseSiteInfo; return best == null ? null : extract(items[best.Value]); } private TypeSymbol MostEncompassingType<T>( ImmutableArray<T> items, Func<T, TypeSymbol> extract, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { return MostEncompassingType<T>(items, x => true, extract, ref useSiteInfo); } private TypeSymbol MostEncompassingType<T>( ImmutableArray<T> items, Func<T, bool> valid, Func<T, TypeSymbol> extract, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // See comments above. CompoundUseSiteInfo<AssemblySymbol> inLambdaUseSiteInfo = useSiteInfo; int? best = UniqueBestValidIndex(items, valid, (left, right) => { TypeSymbol leftType = extract(left); TypeSymbol rightType = extract(right); if (TypeSymbol.Equals(leftType, rightType, TypeCompareKind.ConsiderEverything2)) { return BetterResult.Equal; } bool leftWins = IsEncompassedBy(null, rightType, leftType, ref inLambdaUseSiteInfo); bool rightWins = IsEncompassedBy(null, leftType, rightType, ref inLambdaUseSiteInfo); if (leftWins == rightWins) { return BetterResult.Neither; } return leftWins ? BetterResult.Left : BetterResult.Right; }); useSiteInfo = inLambdaUseSiteInfo; return best == null ? null : extract(items[best.Value]); } // This method takes an array of items and a predicate which filters out the valid items. // From the valid items we find the index of the *unique best item* in the array. // In order for a valid item x to be considered best, x must be better than every other // item. The "better" relation must be consistent; that is: // // better(x,y) == Left requires that better(y,x) == Right // better(x,y) == Right requires that better(y,x) == Left // better(x,y) == Neither requires that better(y,x) == Neither // // It is possible for the array to contain the same item twice; if it does then // the duplicate is ignored. That is, having the "best" item twice does not preclude // it from being the best. // UNDONE: Update this to give a BestIndex result that indicates ambiguity. private static int? UniqueBestValidIndex<T>(ImmutableArray<T> items, Func<T, bool> valid, Func<T, T, BetterResult> better) { if (items.IsEmpty) { return null; } int? candidateIndex = null; T candidateItem = default(T); for (int currentIndex = 0; currentIndex < items.Length; ++currentIndex) { T currentItem = items[currentIndex]; if (!valid(currentItem)) { continue; } if (candidateIndex == null) { candidateIndex = currentIndex; candidateItem = currentItem; continue; } BetterResult result = better(candidateItem, currentItem); if (result == BetterResult.Equal) { // The list had the same item twice. Just ignore it. continue; } else if (result == BetterResult.Neither) { // Neither the current item nor the candidate item are better, // and therefore neither of them can be the best. We no longer // have a candidate for best item. candidateIndex = null; candidateItem = default(T); } else if (result == BetterResult.Right) { // The candidate is worse than the current item, so replace it // with the current item. candidateIndex = currentIndex; candidateItem = currentItem; } // Otherwise, the candidate is better than the current item, so // it continues to be the candidate. } if (candidateIndex == null) { return null; } // We had a candidate that was better than everything that came *after* it. // Now verify that it was better than everything that came before it. for (int currentIndex = 0; currentIndex < candidateIndex.Value; ++currentIndex) { T currentItem = items[currentIndex]; if (!valid(currentItem)) { continue; } BetterResult result = better(candidateItem, currentItem); if (result != BetterResult.Left && result != BetterResult.Equal) { // The candidate was not better than everything that came before it. There is // no best item. return null; } } // The candidate was better than everything that came before it. return candidateIndex; } private NamedTypeSymbol MakeNullableType(TypeSymbol type) { var nullable = this.corLibrary.GetDeclaredSpecialType(SpecialType.System_Nullable_T); return nullable.Construct(type); } /// <remarks> /// NOTE: Keep this method in sync with AnalyzeImplicitUserDefinedConversion. /// </remarks> protected UserDefinedConversionResult AnalyzeImplicitUserDefinedConversionForV6SwitchGoverningType(TypeSymbol source, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: The governing type of a switch statement is established by the switch expression. // SPEC: 1) If the type of the switch expression is sbyte, byte, short, ushort, int, uint, // SPEC: long, ulong, bool, char, string, or an enum-type, or if it is the nullable type // SPEC: corresponding to one of these types, then that is the governing type of the switch statement. // SPEC: 2) Otherwise, exactly one user-defined implicit conversion (§6.4) must exist from the // SPEC: type of the switch expression to one of the following possible governing types: // SPEC: sbyte, byte, short, ushort, int, uint, long, ulong, char, string, or, a nullable type // SPEC: corresponding to one of those types // NOTE: This method implements part (2) above, it should be called only if (1) is false for source type. Debug.Assert((object)source != null); Debug.Assert(!source.IsValidV6SwitchGoverningType()); // NOTE: For (2) we use an approach similar to native compiler's approach, but call into the common code for analyzing user defined implicit conversions. // NOTE: (a) Compute the set of types D from which user-defined conversion operators should be considered by considering only the source type. // NOTE: (b) Instead of computing applicable user defined implicit conversions U from the source type to a specific target type, // NOTE: we compute these from the source type to ANY target type. // NOTE: (c) From the conversions in U, select the most specific of them that targets a valid switch governing type // SPEC VIOLATION: Because we use the same strategy for computing the most specific conversion, as the Dev10 compiler did (in fact // SPEC VIOLATION: we share the code), we inherit any spec deviances in that analysis. Specifically, the analysis only considers // SPEC VIOLATION: which conversion has the least amount of lifting, where a conversion may be considered to be in unlifted form, // SPEC VIOLATION: half-lifted form (only the argument type or return type is lifted) or fully lifted form. The most specific computation // SPEC VIOLATION: looks for a unique conversion that is least lifted. The spec, on the other hand, requires that the conversion // SPEC VIOLATION: be *unique*, not merely most use the least amount of lifting among the applicable conversions. // SPEC VIOLATION: This introduces a SPEC VIOLATION for the following tests in the native compiler: // NOTE: // See test SwitchTests.CS0166_AggregateTypeWithMultipleImplicitConversions_07 // NOTE: struct Conv // NOTE: { // NOTE: public static implicit operator int (Conv C) { return 1; } // NOTE: public static implicit operator int (Conv? C2) { return 0; } // NOTE: public static int Main() // NOTE: { // NOTE: Conv? D = new Conv(); // NOTE: switch(D) // NOTE: { ... // SPEC VIOLATION: Native compiler allows the above code to compile // SPEC VIOLATION: even though there are two user-defined implicit conversions: // SPEC VIOLATION: 1) To int type (applicable in normal form): public static implicit operator int (Conv? C2) // SPEC VIOLATION: 2) To int? type (applicable in lifted form): public static implicit operator int (Conv C) // NOTE: // See also test SwitchTests.TODO // NOTE: struct Conv // NOTE: { // NOTE: public static implicit operator int? (Conv C) { return 1; } // NOTE: public static implicit operator string (Conv? C2) { return 0; } // NOTE: public static int Main() // NOTE: { // NOTE: Conv? D = new Conv(); // NOTE: switch(D) // NOTE: { ... // SPEC VIOLATION: Native compiler allows the above code to compile too // SPEC VIOLATION: even though there are two user-defined implicit conversions: // SPEC VIOLATION: 1) To string type (applicable in normal form): public static implicit operator string (Conv? C2) // SPEC VIOLATION: 2) To int? type (applicable in half-lifted form): public static implicit operator int? (Conv C) // SPEC VIOLATION: This occurs because the native compiler compares the applicable conversions to find one with the least amount // SPEC VIOLATION: of lifting, ignoring whether the return types are the same or not. // SPEC VIOLATION: We do the same to maintain compatibility with the native compiler. // (a) Compute the set of types D from which user-defined conversion operators should be considered by considering only the source type. var d = ArrayBuilder<TypeSymbol>.GetInstance(); ComputeUserDefinedImplicitConversionTypeSet(source, t: null, d: d, useSiteInfo: ref useSiteInfo); // (b) Instead of computing applicable user defined implicit conversions U from the source type to a specific target type, // we compute these from the source type to ANY target type. We will filter out those that are valid switch governing // types later. var ubuild = ArrayBuilder<UserDefinedConversionAnalysis>.GetInstance(); ComputeApplicableUserDefinedImplicitConversionSet(null, source, target: null, d: d, u: ubuild, useSiteInfo: ref useSiteInfo, allowAnyTarget: true); d.Free(); ImmutableArray<UserDefinedConversionAnalysis> u = ubuild.ToImmutableAndFree(); // (c) Find that conversion with the least amount of lifting int? best = MostSpecificConversionOperator(conv => conv.ToType.IsValidV6SwitchGoverningType(isTargetTypeOfUserDefinedOp: true), u); if (best != null) { return UserDefinedConversionResult.Valid(u, best.Value); } return UserDefinedConversionResult.NoApplicableOperators(u); } } }
1
dotnet/roslyn
56,416
Do not include function type conversions in user-defined conversions
Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
cston
"2021-09-15T18:16:38Z"
"2021-09-24T23:24:46Z"
bb99d0bc89bde01650d2a694d720d600dd952dcb
3913f352cf066fa485869d866e4753fa721cbe93
Do not include function type conversions in user-defined conversions. Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
./src/Compilers/CSharp/Portable/Binder/Semantics/OverloadResolution/MethodTypeInference.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; /* SPEC: Type inference occurs as part of the compile-time processing of a method invocation and takes place before the overload resolution step of the invocation. When a particular method group is specified in a method invocation, and no type arguments are specified as part of the method invocation, type inference is applied to each generic method in the method group. If type inference succeeds, then the inferred type arguments are used to determine the types of formal parameters for subsequent overload resolution. If overload resolution chooses a generic method as the one to invoke then the inferred type arguments are used as the actual type arguments for the invocation. If type inference for a particular method fails, that method does not participate in overload resolution. The failure of type inference, in and of itself, does not cause a compile-time error. However, it often leads to a compile-time error when overload resolution then fails to find any applicable methods. If the supplied number of arguments is different than the number of parameters in the method, then inference immediately fails. Otherwise, assume that the generic method has the following signature: Tr M<X1...Xn>(T1 x1 ... Tm xm) With a method call of the form M(E1...Em) the task of type inference is to find unique type arguments S1...Sn for each of the type parameters X1...Xn so that the call M<S1...Sn>(E1...Em)becomes valid. During the process of inference each type parameter Xi is either fixed to a particular type Si or unfixed with an associated set of bounds. Each of the bounds is some type T. Each bound is classified as an upper bound, lower bound or exact bound. Initially each type variable Xi is unfixed with an empty set of bounds. */ // This file contains the implementation for method type inference on calls (with // arguments, and method type inference on conversion of method groups to delegate // types (which will not have arguments.) namespace Microsoft.CodeAnalysis.CSharp { internal static class PooledDictionaryIgnoringNullableModifiersForReferenceTypes { private static readonly ObjectPool<PooledDictionary<NamedTypeSymbol, NamedTypeSymbol>> s_poolInstance = PooledDictionary<NamedTypeSymbol, NamedTypeSymbol>.CreatePool(Symbols.SymbolEqualityComparer.IgnoringNullable); internal static PooledDictionary<NamedTypeSymbol, NamedTypeSymbol> GetInstance() { var instance = s_poolInstance.Allocate(); Debug.Assert(instance.Count == 0); return instance; } } // Method type inference can fail, but we still might have some best guesses. internal readonly struct MethodTypeInferenceResult { public readonly ImmutableArray<TypeWithAnnotations> InferredTypeArguments; /// <summary> /// At least one type argument was inferred from a function type. /// </summary> public readonly bool HasTypeArgumentInferredFromFunctionType; public readonly bool Success; public MethodTypeInferenceResult( bool success, ImmutableArray<TypeWithAnnotations> inferredTypeArguments, bool hasTypeArgumentInferredFromFunctionType) { this.Success = success; this.InferredTypeArguments = inferredTypeArguments; this.HasTypeArgumentInferredFromFunctionType = hasTypeArgumentInferredFromFunctionType; } } internal sealed class MethodTypeInferrer { internal abstract class Extensions { internal static readonly Extensions Default = new DefaultExtensions(); internal abstract TypeWithAnnotations GetTypeWithAnnotations(BoundExpression expr); internal abstract TypeWithAnnotations GetMethodGroupResultType(BoundMethodGroup group, MethodSymbol method); private sealed class DefaultExtensions : Extensions { internal override TypeWithAnnotations GetTypeWithAnnotations(BoundExpression expr) { return TypeWithAnnotations.Create(expr.GetTypeOrFunctionType()); } internal override TypeWithAnnotations GetMethodGroupResultType(BoundMethodGroup group, MethodSymbol method) { return method.ReturnTypeWithAnnotations; } } } private enum InferenceResult { InferenceFailed, MadeProgress, NoProgress, Success } private enum Dependency { Unknown = 0x00, NotDependent = 0x01, DependsMask = 0x10, Direct = 0x11, Indirect = 0x12 } private readonly CSharpCompilation _compilation; private readonly ConversionsBase _conversions; private readonly ImmutableArray<TypeParameterSymbol> _methodTypeParameters; private readonly NamedTypeSymbol _constructedContainingTypeOfMethod; private readonly ImmutableArray<TypeWithAnnotations> _formalParameterTypes; private readonly ImmutableArray<RefKind> _formalParameterRefKinds; private readonly ImmutableArray<BoundExpression> _arguments; private readonly Extensions _extensions; private readonly (TypeWithAnnotations Type, bool FromFunctionType)[] _fixedResults; private readonly HashSet<TypeWithAnnotations>[] _exactBounds; private readonly HashSet<TypeWithAnnotations>[] _upperBounds; private readonly HashSet<TypeWithAnnotations>[] _lowerBounds; // https://github.com/dotnet/csharplang/blob/main/proposals/csharp-9.0/nullable-reference-types-specification.md#fixing // If the resulting candidate is a reference type and *all* of the exact bounds or *any* of // the lower bounds are nullable reference types, `null` or `default`, then `?` is added to // the resulting candidate, making it a nullable reference type. // // This set of bounds effectively tracks whether a typeless null expression (i.e. null // literal) was used as an argument to a parameter whose type is one of this method's type // parameters. Because such expressions only occur as by-value inputs, we only need to track // the lower bounds, not the exact or upper bounds. private readonly NullableAnnotation[] _nullableAnnotationLowerBounds; private Dependency[,] _dependencies; // Initialized lazily private bool _dependenciesDirty; /// <summary> /// For error recovery, we allow a mismatch between the number of arguments and parameters /// during type inference. This sometimes enables inferring the type for a lambda parameter. /// </summary> private int NumberArgumentsToProcess => System.Math.Min(_arguments.Length, _formalParameterTypes.Length); public static MethodTypeInferenceResult Infer( Binder binder, ConversionsBase conversions, ImmutableArray<TypeParameterSymbol> methodTypeParameters, // We are attempting to build a map from method type parameters // to inferred type arguments. NamedTypeSymbol constructedContainingTypeOfMethod, ImmutableArray<TypeWithAnnotations> formalParameterTypes, // We have some unusual requirements for the types that flow into the inference engine. // Consider the following inference problems: // // Scenario one: // // class C<T> // { // delegate Y FT<X, Y>(T t, X x); // static void M<U, V>(U u, FT<U, V> f); // ... // C<double>.M(123, (t,x)=>t+x); // // From the first argument we infer that U is int. How now must we make an inference on // the second argument? The *declared* type of the formal is C<T>.FT<U,V>. The // actual type at the time of inference is known to be C<double>.FT<int, something> // where "something" is to be determined by inferring the return type of the // lambda by determine the type of "double + int". // // Therefore when we do type inference, if a formal parameter type is a generic delegate // then *its* formal parameter types must be the formal parameter types of the // *constructed* generic delegate C<double>.FT<...>, not C<T>.FT<...>. // // One would therefore suppose that we'd expect the formal parameter types to here // be passed in with the types constructed with the information known from the // call site, not the declared types. // // Contrast that with this scenario: // // Scenario Two: // // interface I<T> // { // void M<U>(T t, U u); // } // ... // static void Goo<V>(V v, I<V> iv) // { // iv.M(v, ""); // } // // Obviously inference should succeed here; it should infer that U is string. // // But consider what happens during the inference process on the first argument. // The first thing we will do is say "what's the type of the argument? V. What's // the type of the corresponding formal parameter? The first formal parameter of // I<V>.M<whatever> is of type V. The inference engine will then say "V is a // method type parameter, and therefore we have an inference from V to V". // But *V* is not one of the method type parameters being inferred; the only // method type parameter being inferred here is *U*. // // This is perhaps some evidence that the formal parameters passed in should be // the formal parameters of the *declared* method; in this case, (T, U), not // the formal parameters of the *constructed* method, (V, U). // // However, one might make the argument that no, we could just add a check // to ensure that if we see a method type parameter as a formal parameter type, // then we only perform the inference if the method type parameter is a type // parameter of the method for which inference is being performed. // // Unfortunately, that does not work either: // // Scenario three: // // class C<T> // { // static void M<U>(T t, U u) // { // ... // C<U>.M(u, 123); // ... // } // } // // The *original* formal parameter types are (T, U); the *constructed* formal parameter types // are (U, U), but *those are logically two different U's*. The first U is from the outer caller; // the second U is the U of the recursive call. // // That is, suppose someone called C<string>.M<double>(string, double). The recursive call should be to // C<double>.M<int>(double, int). We should absolutely not make an inference on the first argument // from U to U just because C<U>.M<something>'s first formal parameter is of type U. If we did then // inference would fail, because we'd end up with two bounds on 'U' -- 'U' and 'int'. We only want // the latter bound. // // What these three scenarios show is that for a "normal" inference we need to have the // formal parameters of the *original* method definition, but when making an inference from a lambda // to a delegate, we need to have the *constructed* method signature in order that the formal // parameters *of the delegate* be correct. // // How to solve this problem? // // We solve it by passing in the formal parameters in their *original* form, but also getting // the *fully constructed* type that the method call is on. When constructing the fixed // delegate type for inference from a lambda, we do the appropriate type substitution on // the delegate. ImmutableArray<RefKind> formalParameterRefKinds, // Optional; assume all value if missing. ImmutableArray<BoundExpression> arguments,// Required; in scenarios like method group conversions where there are // no arguments per se we cons up some fake arguments. ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, Extensions extensions = null) { Debug.Assert(!methodTypeParameters.IsDefault); Debug.Assert(methodTypeParameters.Length > 0); Debug.Assert(!formalParameterTypes.IsDefault); Debug.Assert(formalParameterRefKinds.IsDefault || formalParameterRefKinds.Length == formalParameterTypes.Length); Debug.Assert(!arguments.IsDefault); // Early out: if the method has no formal parameters then we know that inference will fail. if (formalParameterTypes.Length == 0) { return new MethodTypeInferenceResult(success: false, inferredTypeArguments: default, hasTypeArgumentInferredFromFunctionType: false); // UNDONE: OPTIMIZATION: We could check to see whether there is a type // UNDONE: parameter which is never used in any formal parameter; if // UNDONE: so then we know ahead of time that inference will fail. } var inferrer = new MethodTypeInferrer( binder.Compilation, conversions, methodTypeParameters, constructedContainingTypeOfMethod, formalParameterTypes, formalParameterRefKinds, arguments, extensions); return inferrer.InferTypeArgs(binder, ref useSiteInfo); } //////////////////////////////////////////////////////////////////////////////// // // Fixed, unfixed and bounded type parameters // // SPEC: During the process of inference each type parameter is either fixed to // SPEC: a particular type or unfixed with an associated set of bounds. Each of // SPEC: the bounds is of some type T. Initially each type parameter is unfixed // SPEC: with an empty set of bounds. private MethodTypeInferrer( CSharpCompilation compilation, ConversionsBase conversions, ImmutableArray<TypeParameterSymbol> methodTypeParameters, NamedTypeSymbol constructedContainingTypeOfMethod, ImmutableArray<TypeWithAnnotations> formalParameterTypes, ImmutableArray<RefKind> formalParameterRefKinds, ImmutableArray<BoundExpression> arguments, Extensions extensions) { _compilation = compilation; _conversions = conversions; _methodTypeParameters = methodTypeParameters; _constructedContainingTypeOfMethod = constructedContainingTypeOfMethod; _formalParameterTypes = formalParameterTypes; _formalParameterRefKinds = formalParameterRefKinds; _arguments = arguments; _extensions = extensions ?? Extensions.Default; _fixedResults = new (TypeWithAnnotations, bool)[methodTypeParameters.Length]; _exactBounds = new HashSet<TypeWithAnnotations>[methodTypeParameters.Length]; _upperBounds = new HashSet<TypeWithAnnotations>[methodTypeParameters.Length]; _lowerBounds = new HashSet<TypeWithAnnotations>[methodTypeParameters.Length]; _nullableAnnotationLowerBounds = new NullableAnnotation[methodTypeParameters.Length]; Debug.Assert(_nullableAnnotationLowerBounds.All(annotation => annotation.IsNotAnnotated())); _dependencies = null; _dependenciesDirty = false; } #if DEBUG internal string Dump() { var sb = new System.Text.StringBuilder(); sb.AppendLine("Method type inference internal state"); sb.AppendFormat("Inferring method type parameters <{0}>\n", string.Join(", ", _methodTypeParameters)); sb.Append("Formal parameter types ("); for (int i = 0; i < _formalParameterTypes.Length; ++i) { if (i != 0) { sb.Append(", "); } sb.Append(GetRefKind(i).ToParameterPrefix()); sb.Append(_formalParameterTypes[i]); } sb.Append("\n"); sb.AppendFormat("Argument types ({0})\n", string.Join(", ", from a in _arguments select a.Type)); if (_dependencies == null) { sb.AppendLine("Dependencies are not yet calculated"); } else { sb.AppendFormat("Dependencies are {0}\n", _dependenciesDirty ? "out of date" : "up to date"); sb.AppendLine("dependency matrix (Not dependent / Direct / Indirect / Unknown):"); for (int i = 0; i < _methodTypeParameters.Length; ++i) { for (int j = 0; j < _methodTypeParameters.Length; ++j) { switch (_dependencies[i, j]) { case Dependency.NotDependent: sb.Append("N"); break; case Dependency.Direct: sb.Append("D"); break; case Dependency.Indirect: sb.Append("I"); break; case Dependency.Unknown: sb.Append("U"); break; } } sb.AppendLine(); } } for (int i = 0; i < _methodTypeParameters.Length; ++i) { sb.AppendFormat("Method type parameter {0}: ", _methodTypeParameters[i].Name); var fixedType = _fixedResults[i].Type; if (!fixedType.HasType) { sb.Append("UNFIXED "); } else { sb.AppendFormat("FIXED to {0} ", fixedType); } sb.AppendFormat("upper bounds: ({0}) ", (_upperBounds[i] == null) ? "" : string.Join(", ", _upperBounds[i])); sb.AppendFormat("lower bounds: ({0}) ", (_lowerBounds[i] == null) ? "" : string.Join(", ", _lowerBounds[i])); sb.AppendFormat("exact bounds: ({0}) ", (_exactBounds[i] == null) ? "" : string.Join(", ", _exactBounds[i])); sb.AppendLine(); } return sb.ToString(); } #endif private RefKind GetRefKind(int index) { Debug.Assert(0 <= index && index < _formalParameterTypes.Length); return _formalParameterRefKinds.IsDefault ? RefKind.None : _formalParameterRefKinds[index]; } private ImmutableArray<TypeWithAnnotations> GetResults(out bool inferredFromFunctionType) { // Anything we didn't infer a type for, give the error type. // Note: the error type will have the same name as the name // of the type parameter we were trying to infer. This will give a // nice user experience where by we will show something like // the following: // // user types: customers.Select( // we show : IE<TResult> IE<Customer>.Select<Customer,TResult>(Func<Customer,TResult> selector) // // Initially we thought we'd just show ?. i.e.: // // IE<?> IE<Customer>.Select<Customer,?>(Func<Customer,?> selector) // // This is nice and concise. However, it falls down if there are multiple // type params that we have left. for (int i = 0; i < _methodTypeParameters.Length; i++) { var fixedResultType = _fixedResults[i].Type; if (fixedResultType.HasType) { if (!fixedResultType.Type.IsErrorType()) { if (_conversions.IncludeNullability && _nullableAnnotationLowerBounds[i].IsAnnotated()) { _fixedResults[i] = _fixedResults[i] with { Type = fixedResultType.AsAnnotated() }; } continue; } var errorTypeName = fixedResultType.Type.Name; if (errorTypeName != null) { continue; } } _fixedResults[i] = (TypeWithAnnotations.Create(new ExtendedErrorTypeSymbol(_constructedContainingTypeOfMethod, _methodTypeParameters[i].Name, 0, null, false)), false); } return GetInferredTypeArguments(out inferredFromFunctionType); } private bool ValidIndex(int index) { return 0 <= index && index < _methodTypeParameters.Length; } private bool IsUnfixed(int methodTypeParameterIndex) { Debug.Assert(ValidIndex(methodTypeParameterIndex)); return !_fixedResults[methodTypeParameterIndex].Type.HasType; } private bool IsUnfixedTypeParameter(TypeWithAnnotations type) { Debug.Assert(type.HasType); if (type.TypeKind != TypeKind.TypeParameter) return false; TypeParameterSymbol typeParameter = (TypeParameterSymbol)type.Type; int ordinal = typeParameter.Ordinal; return ValidIndex(ordinal) && TypeSymbol.Equals(typeParameter, _methodTypeParameters[ordinal], TypeCompareKind.ConsiderEverything2) && IsUnfixed(ordinal); } private bool AllFixed() { for (int methodTypeParameterIndex = 0; methodTypeParameterIndex < _methodTypeParameters.Length; ++methodTypeParameterIndex) { if (IsUnfixed(methodTypeParameterIndex)) { return false; } } return true; } private void AddBound(TypeWithAnnotations addedBound, HashSet<TypeWithAnnotations>[] collectedBounds, TypeWithAnnotations methodTypeParameterWithAnnotations) { Debug.Assert(IsUnfixedTypeParameter(methodTypeParameterWithAnnotations)); var methodTypeParameter = (TypeParameterSymbol)methodTypeParameterWithAnnotations.Type; int methodTypeParameterIndex = methodTypeParameter.Ordinal; if (collectedBounds[methodTypeParameterIndex] == null) { collectedBounds[methodTypeParameterIndex] = new HashSet<TypeWithAnnotations>(TypeWithAnnotations.EqualsComparer.ConsiderEverythingComparer); } collectedBounds[methodTypeParameterIndex].Add(addedBound); } private bool HasBound(int methodTypeParameterIndex) { Debug.Assert(ValidIndex(methodTypeParameterIndex)); return _lowerBounds[methodTypeParameterIndex] != null || _upperBounds[methodTypeParameterIndex] != null || _exactBounds[methodTypeParameterIndex] != null; } private TypeSymbol GetFixedDelegateOrFunctionPointer(TypeSymbol delegateOrFunctionPointerType) { Debug.Assert((object)delegateOrFunctionPointerType != null); Debug.Assert(delegateOrFunctionPointerType.IsDelegateType() || delegateOrFunctionPointerType is FunctionPointerTypeSymbol); // We have a delegate where the input types use no unfixed parameters. Create // a substitution context; we can substitute unfixed parameters for themselves // since they don't actually occur in the inputs. (They may occur in the outputs, // or there may be input parameters fixed to _unfixed_ method type variables. // Both of those scenarios are legal.) var fixedArguments = _methodTypeParameters.SelectAsArray( static (typeParameter, i, self) => self.IsUnfixed(i) ? TypeWithAnnotations.Create(typeParameter) : self._fixedResults[i].Type, this); TypeMap typeMap = new TypeMap(_constructedContainingTypeOfMethod, _methodTypeParameters, fixedArguments); return typeMap.SubstituteType(delegateOrFunctionPointerType).Type; } //////////////////////////////////////////////////////////////////////////////// // // Phases // private MethodTypeInferenceResult InferTypeArgs(Binder binder, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: Type inference takes place in phases. Each phase will try to infer type // SPEC: arguments for more type parameters based on the findings of the previous // SPEC: phase. The first phase makes some initial inferences of bounds, whereas // SPEC: the second phase fixes type parameters to specific types and infers further // SPEC: bounds. The second phase may have to be repeated a number of times. InferTypeArgsFirstPhase(ref useSiteInfo); bool success = InferTypeArgsSecondPhase(binder, ref useSiteInfo); var inferredTypeArguments = GetResults(out bool inferredFromFunctionType); return new MethodTypeInferenceResult(success, inferredTypeArguments, inferredFromFunctionType); } //////////////////////////////////////////////////////////////////////////////// // // The first phase // private void InferTypeArgsFirstPhase(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(!_formalParameterTypes.IsDefault); Debug.Assert(!_arguments.IsDefault); // We expect that we have been handed a list of arguments and a list of the // formal parameter types they correspond to; all the details about named and // optional parameters have already been dealt with. // SPEC: For each of the method arguments Ei: for (int arg = 0, length = this.NumberArgumentsToProcess; arg < length; arg++) { BoundExpression argument = _arguments[arg]; TypeWithAnnotations target = _formalParameterTypes[arg]; ExactOrBoundsKind kind = GetRefKind(arg).IsManagedReference() || target.Type.IsPointerType() ? ExactOrBoundsKind.Exact : ExactOrBoundsKind.LowerBound; MakeExplicitParameterTypeInferences(argument, target, kind, ref useSiteInfo); } } private void MakeExplicitParameterTypeInferences(BoundExpression argument, TypeWithAnnotations target, ExactOrBoundsKind kind, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: * If Ei is an anonymous function, and Ti is a delegate type or expression tree type, // SPEC: an explicit type parameter inference is made from Ei to Ti and // SPEC: an explicit return type inference is made from Ei to Ti. // (We cannot make an output type inference from a method group // at this time because we have no fixed types yet to use for // overload resolution.) // SPEC: * Otherwise, if Ei has a type U then a lower-bound inference // SPEC: or exact inference is made from U to Ti. // SPEC: * Otherwise, no inference is made for this argument if (argument.Kind == BoundKind.UnboundLambda && target.Type.GetDelegateType() is { }) { ExplicitParameterTypeInference(argument, target, ref useSiteInfo); ExplicitReturnTypeInference(argument, target, ref useSiteInfo); } else if (argument.Kind != BoundKind.TupleLiteral || !MakeExplicitParameterTypeInferences((BoundTupleLiteral)argument, target, kind, ref useSiteInfo)) { // Either the argument is not a tuple literal, or we were unable to do the inference from its elements, let's try to infer from argument type if (IsReallyAType(argument.GetTypeOrFunctionType())) { ExactOrBoundsInference(kind, _extensions.GetTypeWithAnnotations(argument), target, ref useSiteInfo); } else if (IsUnfixedTypeParameter(target) && kind is ExactOrBoundsKind.LowerBound) { var ordinal = ((TypeParameterSymbol)target.Type).Ordinal; var typeWithAnnotations = _extensions.GetTypeWithAnnotations(argument); _nullableAnnotationLowerBounds[ordinal] = _nullableAnnotationLowerBounds[ordinal].Join(typeWithAnnotations.NullableAnnotation); } } } private bool MakeExplicitParameterTypeInferences(BoundTupleLiteral argument, TypeWithAnnotations target, ExactOrBoundsKind kind, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // try match up element-wise to the destination tuple (or underlying type) // Example: // if "(a: 1, b: "qq")" is passed as (T, U) arg // then T becomes int and U becomes string if (target.Type.Kind != SymbolKind.NamedType) { // tuples can only match to tuples or tuple underlying types. return false; } var destination = (NamedTypeSymbol)target.Type; var sourceArguments = argument.Arguments; // check if the type is actually compatible type for a tuple of given cardinality if (!destination.IsTupleTypeOfCardinality(sourceArguments.Length)) { // target is not a tuple of appropriate shape return false; } var destTypes = destination.TupleElementTypesWithAnnotations; Debug.Assert(sourceArguments.Length == destTypes.Length); // NOTE: we are losing tuple element names when recursing into argument expressions. // that is ok, because we are inferring type parameters used in the matching elements, // This is not the situation where entire tuple literal is used to infer a single type param for (int i = 0; i < sourceArguments.Length; i++) { var sourceArgument = sourceArguments[i]; var destType = destTypes[i]; MakeExplicitParameterTypeInferences(sourceArgument, destType, kind, ref useSiteInfo); } return true; } //////////////////////////////////////////////////////////////////////////////// // // The second phase // private bool InferTypeArgsSecondPhase(Binder binder, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: The second phase proceeds as follows: // SPEC: * If no unfixed type parameters exist then type inference succeeds. // SPEC: * Otherwise, if there exists one or more arguments Ei with corresponding // SPEC: parameter type Ti such that: // SPEC: o the output type of Ei with type Ti contains at least one unfixed // SPEC: type parameter Xj, and // SPEC: o none of the input types of Ei with type Ti contains any unfixed // SPEC: type parameter Xj, // SPEC: then an output type inference is made from all such Ei to Ti. // SPEC: * Whether or not the previous step actually made an inference, we must // SPEC: now fix at least one type parameter, as follows: // SPEC: * If there exists one or more type parameters Xi such that // SPEC: o Xi is unfixed, and // SPEC: o Xi has a non-empty set of bounds, and // SPEC: o Xi does not depend on any Xj // SPEC: then each such Xi is fixed. If any fixing operation fails then type // SPEC: inference fails. // SPEC: * Otherwise, if there exists one or more type parameters Xi such that // SPEC: o Xi is unfixed, and // SPEC: o Xi has a non-empty set of bounds, and // SPEC: o there is at least one type parameter Xj that depends on Xi // SPEC: then each such Xi is fixed. If any fixing operation fails then // SPEC: type inference fails. // SPEC: * Otherwise, we are unable to make progress and there are unfixed parameters. // SPEC: Type inference fails. // SPEC: * If type inference neither succeeds nor fails then the second phase is // SPEC: repeated until type inference succeeds or fails. (Since each repetition of // SPEC: the second phase either succeeds, fails or fixes an unfixed type parameter, // SPEC: the algorithm must terminate with no more repetitions than the number // SPEC: of type parameters. InitializeDependencies(); while (true) { var res = DoSecondPhase(binder, ref useSiteInfo); Debug.Assert(res != InferenceResult.NoProgress); if (res == InferenceResult.InferenceFailed) { return false; } if (res == InferenceResult.Success) { return true; } // Otherwise, we made some progress last time; do it again. } } private InferenceResult DoSecondPhase(Binder binder, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: * If no unfixed type parameters exist then type inference succeeds. if (AllFixed()) { return InferenceResult.Success; } // SPEC: * Otherwise, if there exists one or more arguments Ei with // SPEC: corresponding parameter type Ti such that: // SPEC: o the output type of Ei with type Ti contains at least one unfixed // SPEC: type parameter Xj, and // SPEC: o none of the input types of Ei with type Ti contains any unfixed // SPEC: type parameter Xj, // SPEC: then an output type inference is made from all such Ei to Ti. MakeOutputTypeInferences(binder, ref useSiteInfo); // SPEC: * Whether or not the previous step actually made an inference, we // SPEC: must now fix at least one type parameter, as follows: // SPEC: * If there exists one or more type parameters Xi such that // SPEC: o Xi is unfixed, and // SPEC: o Xi has a non-empty set of bounds, and // SPEC: o Xi does not depend on any Xj // SPEC: then each such Xi is fixed. If any fixing operation fails then // SPEC: type inference fails. InferenceResult res; res = FixNondependentParameters(ref useSiteInfo); if (res != InferenceResult.NoProgress) { return res; } // SPEC: * Otherwise, if there exists one or more type parameters Xi such that // SPEC: o Xi is unfixed, and // SPEC: o Xi has a non-empty set of bounds, and // SPEC: o there is at least one type parameter Xj that depends on Xi // SPEC: then each such Xi is fixed. If any fixing operation fails then // SPEC: type inference fails. res = FixDependentParameters(ref useSiteInfo); if (res != InferenceResult.NoProgress) { return res; } // SPEC: * Otherwise, we are unable to make progress and there are // SPEC: unfixed parameters. Type inference fails. return InferenceResult.InferenceFailed; } private void MakeOutputTypeInferences(Binder binder, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: Otherwise, for all arguments Ei with corresponding parameter type Ti // SPEC: where the output types contain unfixed type parameters but the input // SPEC: types do not, an output type inference is made from Ei to Ti. for (int arg = 0, length = this.NumberArgumentsToProcess; arg < length; arg++) { var formalType = _formalParameterTypes[arg]; var argument = _arguments[arg]; MakeOutputTypeInferences(binder, argument, formalType, ref useSiteInfo); } } private void MakeOutputTypeInferences(Binder binder, BoundExpression argument, TypeWithAnnotations formalType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (argument.Kind == BoundKind.TupleLiteral && (object)argument.Type == null) { MakeOutputTypeInferences(binder, (BoundTupleLiteral)argument, formalType, ref useSiteInfo); } else { if (HasUnfixedParamInOutputType(argument, formalType.Type) && !HasUnfixedParamInInputType(argument, formalType.Type)) { //UNDONE: if (argument->isTYPEORNAMESPACEERROR() && argumentType->IsErrorType()) //UNDONE: { //UNDONE: argumentType = GetTypeManager().GetErrorSym(); //UNDONE: } OutputTypeInference(binder, argument, formalType, ref useSiteInfo); } } } private void MakeOutputTypeInferences(Binder binder, BoundTupleLiteral argument, TypeWithAnnotations formalType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (formalType.Type.Kind != SymbolKind.NamedType) { // tuples can only match to tuples or tuple underlying types. return; } var destination = (NamedTypeSymbol)formalType.Type; Debug.Assert((object)argument.Type == null, "should not need to dig into elements if tuple has natural type"); var sourceArguments = argument.Arguments; // check if the type is actually compatible type for a tuple of given cardinality if (!destination.IsTupleTypeOfCardinality(sourceArguments.Length)) { return; } var destTypes = destination.TupleElementTypesWithAnnotations; Debug.Assert(sourceArguments.Length == destTypes.Length); for (int i = 0; i < sourceArguments.Length; i++) { var sourceArgument = sourceArguments[i]; var destType = destTypes[i]; MakeOutputTypeInferences(binder, sourceArgument, destType, ref useSiteInfo); } } private InferenceResult FixNondependentParameters(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: * Otherwise, if there exists one or more type parameters Xi such that // SPEC: o Xi is unfixed, and // SPEC: o Xi has a non-empty set of bounds, and // SPEC: o Xi does not depend on any Xj // SPEC: then each such Xi is fixed. return FixParameters((inferrer, index) => !inferrer.DependsOnAny(index), ref useSiteInfo); } private InferenceResult FixDependentParameters(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: * All unfixed type parameters Xi are fixed for which all of the following hold: // SPEC: * There is at least one type parameter Xj that depends on Xi. // SPEC: * Xi has a non-empty set of bounds. return FixParameters((inferrer, index) => inferrer.AnyDependsOn(index), ref useSiteInfo); } private InferenceResult FixParameters( Func<MethodTypeInferrer, int, bool> predicate, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // Dependency is only defined for unfixed parameters. Therefore, fixing // a parameter may cause all of its dependencies to become no longer // dependent on anything. We need to first determine which parameters need to be // fixed, and then fix them all at once. var needsFixing = new bool[_methodTypeParameters.Length]; var result = InferenceResult.NoProgress; for (int param = 0; param < _methodTypeParameters.Length; param++) { if (IsUnfixed(param) && HasBound(param) && predicate(this, param)) { needsFixing[param] = true; result = InferenceResult.MadeProgress; } } for (int param = 0; param < _methodTypeParameters.Length; param++) { // Fix as much as you can, even if there are errors. That will // help with intellisense. if (needsFixing[param]) { if (!Fix(param, ref useSiteInfo)) { result = InferenceResult.InferenceFailed; } } } return result; } //////////////////////////////////////////////////////////////////////////////// // // Input types // private static bool DoesInputTypeContain(BoundExpression argument, TypeSymbol formalParameterType, TypeParameterSymbol typeParameter) { // SPEC: If E is a method group or an anonymous function and T is a delegate // SPEC: type or expression tree type then all the parameter types of T are // SPEC: input types of E with type T. var delegateOrFunctionPointerType = formalParameterType.GetDelegateOrFunctionPointerType(); if ((object)delegateOrFunctionPointerType == null) { return false; // No input types. } var isFunctionPointer = delegateOrFunctionPointerType.IsFunctionPointer(); if ((isFunctionPointer && argument.Kind != BoundKind.UnconvertedAddressOfOperator) || (!isFunctionPointer && argument.Kind is not (BoundKind.UnboundLambda or BoundKind.MethodGroup))) { return false; // No input types. } var parameters = delegateOrFunctionPointerType.DelegateOrFunctionPointerParameters(); if (parameters.IsDefaultOrEmpty) { return false; } foreach (var parameter in parameters) { if (parameter.Type.ContainsTypeParameter(typeParameter)) { return true; } } return false; } private bool HasUnfixedParamInInputType(BoundExpression pSource, TypeSymbol pDest) { for (int iParam = 0; iParam < _methodTypeParameters.Length; iParam++) { if (IsUnfixed(iParam)) { if (DoesInputTypeContain(pSource, pDest, _methodTypeParameters[iParam])) { return true; } } } return false; } //////////////////////////////////////////////////////////////////////////////// // // Output types // private static bool DoesOutputTypeContain(BoundExpression argument, TypeSymbol formalParameterType, TypeParameterSymbol typeParameter) { // SPEC: If E is a method group or an anonymous function and T is a delegate // SPEC: type or expression tree type then the return type of T is an output type // SPEC: of E with type T. var delegateOrFunctionPointerType = formalParameterType.GetDelegateOrFunctionPointerType(); if ((object)delegateOrFunctionPointerType == null) { return false; } var isFunctionPointer = delegateOrFunctionPointerType.IsFunctionPointer(); if ((isFunctionPointer && argument.Kind != BoundKind.UnconvertedAddressOfOperator) || (!isFunctionPointer && argument.Kind is not (BoundKind.UnboundLambda or BoundKind.MethodGroup))) { return false; } MethodSymbol method = delegateOrFunctionPointerType switch { NamedTypeSymbol n => n.DelegateInvokeMethod, FunctionPointerTypeSymbol f => f.Signature, _ => throw ExceptionUtilities.UnexpectedValue(delegateOrFunctionPointerType) }; if ((object)method == null || method.HasUseSiteError) { return false; } var returnType = method.ReturnType; if ((object)returnType == null) { return false; } return returnType.ContainsTypeParameter(typeParameter); } private bool HasUnfixedParamInOutputType(BoundExpression argument, TypeSymbol formalParameterType) { for (int iParam = 0; iParam < _methodTypeParameters.Length; iParam++) { if (IsUnfixed(iParam)) { if (DoesOutputTypeContain(argument, formalParameterType, _methodTypeParameters[iParam])) { return true; } } } return false; } //////////////////////////////////////////////////////////////////////////////// // // Dependence // private bool DependsDirectlyOn(int iParam, int jParam) { Debug.Assert(ValidIndex(iParam)); Debug.Assert(ValidIndex(jParam)); // SPEC: An unfixed type parameter Xi depends directly on an unfixed type // SPEC: parameter Xj if for some argument Ek with type Tk, Xj occurs // SPEC: in an input type of Ek and Xi occurs in an output type of Ek // SPEC: with type Tk. // We compute and record the Depends Directly On relationship once, in // InitializeDependencies, below. // At this point, everything should be unfixed. Debug.Assert(IsUnfixed(iParam)); Debug.Assert(IsUnfixed(jParam)); for (int iArg = 0, length = this.NumberArgumentsToProcess; iArg < length; iArg++) { var formalParameterType = _formalParameterTypes[iArg].Type; var argument = _arguments[iArg]; if (DoesInputTypeContain(argument, formalParameterType, _methodTypeParameters[jParam]) && DoesOutputTypeContain(argument, formalParameterType, _methodTypeParameters[iParam])) { return true; } } return false; } private void InitializeDependencies() { // We track dependencies by a two-d square array that gives the known // relationship between every pair of type parameters. The relationship // is one of: // // * Unknown relationship // * known to be not dependent // * known to depend directly // * known to depend indirectly // // Since dependency is only defined on unfixed type parameters, fixing a type // parameter causes all dependencies involving that parameter to go to // the "known to be not dependent" state. Since dependency is a transitive property, // this means that doing so may require recalculating the indirect dependencies // from the now possibly smaller set of dependencies. // // Therefore, when we detect that the dependency state has possibly changed // due to fixing, we change all "depends indirectly" back into "unknown" and // recalculate from the remaining "depends directly". // // This algorithm thereby yields an extremely bad (but extremely unlikely) worst // case for asymptotic performance. Suppose there are n type parameters. // "DependsTransitivelyOn" below costs O(n) because it must potentially check // all n type parameters to see if there is any k such that Xj => Xk => Xi. // "DeduceDependencies" calls "DependsTransitivelyOn" for each "Unknown" // pair, and there could be O(n^2) such pairs, so DependsTransitivelyOn is // worst-case O(n^3). And we could have to recalculate the dependency graph // after each type parameter is fixed in turn, so that would be O(n) calls to // DependsTransitivelyOn, giving this algorithm a worst case of O(n^4). // // Of course, in reality, n is going to almost always be on the order of // "smaller than 5", and there will not be O(n^2) dependency relationships // between type parameters; it is far more likely that the transitivity chains // will be very short and not branch or loop at all. This is much more likely to // be an O(n^2) algorithm in practice. Debug.Assert(_dependencies == null); _dependencies = new Dependency[_methodTypeParameters.Length, _methodTypeParameters.Length]; int iParam; int jParam; Debug.Assert(0 == (int)Dependency.Unknown); for (iParam = 0; iParam < _methodTypeParameters.Length; ++iParam) { for (jParam = 0; jParam < _methodTypeParameters.Length; ++jParam) { if (DependsDirectlyOn(iParam, jParam)) { _dependencies[iParam, jParam] = Dependency.Direct; } } } DeduceAllDependencies(); } private bool DependsOn(int iParam, int jParam) { Debug.Assert(_dependencies != null); // SPEC: Xj depends on Xi if Xj depends directly on Xi, or if Xi depends // SPEC: directly on Xk and Xk depends on Xj. Thus "depends on" is the // SPEC: transitive but not reflexive closure of "depends directly on". Debug.Assert(0 <= iParam && iParam < _methodTypeParameters.Length); Debug.Assert(0 <= jParam && jParam < _methodTypeParameters.Length); if (_dependenciesDirty) { SetIndirectsToUnknown(); DeduceAllDependencies(); } return 0 != ((_dependencies[iParam, jParam]) & Dependency.DependsMask); } private bool DependsTransitivelyOn(int iParam, int jParam) { Debug.Assert(_dependencies != null); Debug.Assert(ValidIndex(iParam)); Debug.Assert(ValidIndex(jParam)); // Can we find Xk such that Xi depends on Xk and Xk depends on Xj? // If so, then Xi depends indirectly on Xj. (Note that there is // a minor optimization here -- the spec comment above notes that // we want Xi to depend DIRECTLY on Xk, and Xk to depend directly // or indirectly on Xj. But if we already know that Xi depends // directly OR indirectly on Xk and Xk depends on Xj, then that's // good enough.) for (int kParam = 0; kParam < _methodTypeParameters.Length; ++kParam) { if (((_dependencies[iParam, kParam]) & Dependency.DependsMask) != 0 && ((_dependencies[kParam, jParam]) & Dependency.DependsMask) != 0) { return true; } } return false; } private void DeduceAllDependencies() { bool madeProgress; do { madeProgress = DeduceDependencies(); } while (madeProgress); SetUnknownsToNotDependent(); _dependenciesDirty = false; } private bool DeduceDependencies() { Debug.Assert(_dependencies != null); bool madeProgress = false; for (int iParam = 0; iParam < _methodTypeParameters.Length; ++iParam) { for (int jParam = 0; jParam < _methodTypeParameters.Length; ++jParam) { if (_dependencies[iParam, jParam] == Dependency.Unknown) { if (DependsTransitivelyOn(iParam, jParam)) { _dependencies[iParam, jParam] = Dependency.Indirect; madeProgress = true; } } } } return madeProgress; } private void SetUnknownsToNotDependent() { Debug.Assert(_dependencies != null); for (int iParam = 0; iParam < _methodTypeParameters.Length; ++iParam) { for (int jParam = 0; jParam < _methodTypeParameters.Length; ++jParam) { if (_dependencies[iParam, jParam] == Dependency.Unknown) { _dependencies[iParam, jParam] = Dependency.NotDependent; } } } } private void SetIndirectsToUnknown() { Debug.Assert(_dependencies != null); for (int iParam = 0; iParam < _methodTypeParameters.Length; ++iParam) { for (int jParam = 0; jParam < _methodTypeParameters.Length; ++jParam) { if (_dependencies[iParam, jParam] == Dependency.Indirect) { _dependencies[iParam, jParam] = Dependency.Unknown; } } } } //////////////////////////////////////////////////////////////////////////////// // A fixed parameter never depends on anything, nor is depended upon by anything. private void UpdateDependenciesAfterFix(int iParam) { Debug.Assert(ValidIndex(iParam)); if (_dependencies == null) { return; } for (int jParam = 0; jParam < _methodTypeParameters.Length; ++jParam) { _dependencies[iParam, jParam] = Dependency.NotDependent; _dependencies[jParam, iParam] = Dependency.NotDependent; } _dependenciesDirty = true; } private bool DependsOnAny(int iParam) { Debug.Assert(ValidIndex(iParam)); for (int jParam = 0; jParam < _methodTypeParameters.Length; ++jParam) { if (DependsOn(iParam, jParam)) { return true; } } return false; } private bool AnyDependsOn(int iParam) { Debug.Assert(ValidIndex(iParam)); for (int jParam = 0; jParam < _methodTypeParameters.Length; ++jParam) { if (DependsOn(jParam, iParam)) { return true; } } return false; } //////////////////////////////////////////////////////////////////////////////// // // Output type inferences // //////////////////////////////////////////////////////////////////////////////// private void OutputTypeInference(Binder binder, BoundExpression expression, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(expression != null); Debug.Assert(target.HasType); // SPEC: An output type inference is made from an expression E to a type T // SPEC: in the following way: // SPEC: * If E is an anonymous function with inferred return type U and // SPEC: T is a delegate type or expression tree with return type Tb // SPEC: then a lower bound inference is made from U to Tb. if (InferredReturnTypeInference(expression, target, ref useSiteInfo)) { return; } // SPEC: * Otherwise, if E is a method group and T is a delegate type or // SPEC: expression tree type with parameter types T1...Tk and return // SPEC: type Tb and overload resolution of E with the types T1...Tk // SPEC: yields a single method with return type U then a lower-bound // SPEC: inference is made from U to Tb. if (MethodGroupReturnTypeInference(binder, expression, target.Type, ref useSiteInfo)) { return; } // SPEC: * Otherwise, if E is an expression with type U then a lower-bound // SPEC: inference is made from U to T. var sourceType = _extensions.GetTypeWithAnnotations(expression); if (sourceType.HasType) { LowerBoundInference(sourceType, target, ref useSiteInfo); } // SPEC: * Otherwise, no inferences are made. } private bool InferredReturnTypeInference(BoundExpression source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source != null); Debug.Assert(target.HasType); // SPEC: * If E is an anonymous function with inferred return type U and // SPEC: T is a delegate type or expression tree with return type Tb // SPEC: then a lower bound inference is made from U to Tb. var delegateType = target.Type.GetDelegateType(); if ((object)delegateType == null) { return false; } // cannot be hit, because an invalid delegate does not have an unfixed return type // this will be checked earlier. Debug.Assert((object)delegateType.DelegateInvokeMethod != null && !delegateType.DelegateInvokeMethod.HasUseSiteError, "This method should only be called for valid delegate types."); var returnType = delegateType.DelegateInvokeMethod.ReturnTypeWithAnnotations; if (!returnType.HasType || returnType.SpecialType == SpecialType.System_Void) { return false; } var inferredReturnType = InferReturnType(source, delegateType, ref useSiteInfo); if (!inferredReturnType.HasType) { return false; } LowerBoundInference(inferredReturnType, returnType, ref useSiteInfo); return true; } private bool MethodGroupReturnTypeInference(Binder binder, BoundExpression source, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source != null); Debug.Assert((object)target != null); // SPEC: * Otherwise, if E is a method group and T is a delegate type or // SPEC: expression tree type with parameter types T1...Tk and return // SPEC: type Tb and overload resolution of E with the types T1...Tk // SPEC: yields a single method with return type U then a lower-bound // SPEC: inference is made from U to Tb. if (source.Kind is not (BoundKind.MethodGroup or BoundKind.UnconvertedAddressOfOperator)) { return false; } var delegateOrFunctionPointerType = target.GetDelegateOrFunctionPointerType(); if ((object)delegateOrFunctionPointerType == null) { return false; } if (delegateOrFunctionPointerType.IsFunctionPointer() != (source.Kind == BoundKind.UnconvertedAddressOfOperator)) { return false; } // this part of the code is only called if the targetType has an unfixed type argument in the output // type, which is not the case for invalid delegate invoke methods. var (method, isFunctionPointerResolution) = delegateOrFunctionPointerType switch { NamedTypeSymbol n => (n.DelegateInvokeMethod, false), FunctionPointerTypeSymbol f => (f.Signature, true), _ => throw ExceptionUtilities.UnexpectedValue(delegateOrFunctionPointerType), }; Debug.Assert(method is { HasUseSiteError: false }, "This method should only be called for valid delegate or function pointer types"); TypeWithAnnotations sourceReturnType = method.ReturnTypeWithAnnotations; if (!sourceReturnType.HasType || sourceReturnType.SpecialType == SpecialType.System_Void) { return false; } // At this point we are in the second phase; we know that all the input types are fixed. var fixedParameters = GetFixedDelegateOrFunctionPointer(delegateOrFunctionPointerType).DelegateOrFunctionPointerParameters(); if (fixedParameters.IsDefault) { return false; } CallingConventionInfo callingConventionInfo = isFunctionPointerResolution ? new CallingConventionInfo(method.CallingConvention, ((FunctionPointerMethodSymbol)method).GetCallingConventionModifiers()) : default; BoundMethodGroup originalMethodGroup = source as BoundMethodGroup ?? ((BoundUnconvertedAddressOfOperator)source).Operand; var returnType = MethodGroupReturnType(binder, originalMethodGroup, fixedParameters, method.RefKind, isFunctionPointerResolution, ref useSiteInfo, in callingConventionInfo); if (returnType.IsDefault || returnType.IsVoidType()) { return false; } LowerBoundInference(returnType, sourceReturnType, ref useSiteInfo); return true; } private TypeWithAnnotations MethodGroupReturnType( Binder binder, BoundMethodGroup source, ImmutableArray<ParameterSymbol> delegateParameters, RefKind delegateRefKind, bool isFunctionPointerResolution, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, in CallingConventionInfo callingConventionInfo) { var analyzedArguments = AnalyzedArguments.GetInstance(); Conversions.GetDelegateOrFunctionPointerArguments(source.Syntax, analyzedArguments, delegateParameters, binder.Compilation); var resolution = binder.ResolveMethodGroup(source, analyzedArguments, useSiteInfo: ref useSiteInfo, isMethodGroupConversion: true, returnRefKind: delegateRefKind, // Since we are trying to infer the return type, it is not an input to resolving the method group returnType: null, isFunctionPointerResolution: isFunctionPointerResolution, callingConventionInfo: in callingConventionInfo); TypeWithAnnotations type = default; // The resolution could be empty (e.g. if there are no methods in the BoundMethodGroup). if (!resolution.IsEmpty) { var result = resolution.OverloadResolutionResult; if (result.Succeeded) { type = _extensions.GetMethodGroupResultType(source, result.BestResult.Member); } } analyzedArguments.Free(); resolution.Free(); return type; } #nullable enable //////////////////////////////////////////////////////////////////////////////// // // Explicit parameter type inferences // private void ExplicitParameterTypeInference(BoundExpression source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source != null); Debug.Assert(target.HasType); // SPEC: An explicit type parameter type inference is made from an expression // SPEC: E to a type T in the following way. // SPEC: If E is an explicitly typed anonymous function with parameter types // SPEC: U1...Uk and T is a delegate type or expression tree type with // SPEC: parameter types V1...Vk then for each Ui an exact inference is made // SPEC: from Ui to the corresponding Vi. if (source.Kind != BoundKind.UnboundLambda) { return; } UnboundLambda anonymousFunction = (UnboundLambda)source; if (!anonymousFunction.HasExplicitlyTypedParameterList) { return; } var delegateType = target.Type.GetDelegateType(); if (delegateType is null) { return; } var delegateParameters = delegateType.DelegateParameters(); if (delegateParameters.IsDefault) { return; } int size = delegateParameters.Length; if (anonymousFunction.ParameterCount < size) { size = anonymousFunction.ParameterCount; } // SPEC ISSUE: What should we do if there is an out/ref mismatch between an // SPEC ISSUE: anonymous function parameter and a delegate parameter? // SPEC ISSUE: The result will not be applicable no matter what, but should // SPEC ISSUE: we make any inferences? This is going to be an error // SPEC ISSUE: ultimately, but it might make a difference for intellisense or // SPEC ISSUE: other analysis. for (int i = 0; i < size; ++i) { ExactInference(anonymousFunction.ParameterTypeWithAnnotations(i), delegateParameters[i].TypeWithAnnotations, ref useSiteInfo); } } private void ExplicitReturnTypeInference(BoundExpression source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source != null); Debug.Assert(target.HasType); // SPEC: An explicit type return type inference is made from an expression // SPEC: E to a type T in the following way. // SPEC: If E is an anonymous function with explicit return type Ur and // SPEC: T is a delegate type or expression tree type with return type Vr then // SPEC: an exact inference is made from Ur to Vr. if (source.Kind != BoundKind.UnboundLambda) { return; } UnboundLambda anonymousFunction = (UnboundLambda)source; if (!anonymousFunction.HasExplicitReturnType(out _, out TypeWithAnnotations anonymousFunctionReturnType)) { return; } var delegateInvokeMethod = target.Type.GetDelegateType()?.DelegateInvokeMethod(); if (delegateInvokeMethod is null) { return; } ExactInference(anonymousFunctionReturnType, delegateInvokeMethod.ReturnTypeWithAnnotations, ref useSiteInfo); } #nullable disable //////////////////////////////////////////////////////////////////////////////// // // Exact inferences // private void ExactInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: An exact inference from a type U to a type V is made as follows: // SPEC: * Otherwise, if U is the type U1? and V is the type V1? then an // SPEC: exact inference is made from U to V. if (ExactNullableInference(source, target, ref useSiteInfo)) { return; } // SPEC: * If V is one of the unfixed Xi then U is added to the set of // SPEC: exact bounds for Xi. if (ExactTypeParameterInference(source, target)) { return; } // SPEC: * Otherwise, if U is an array type UE[...] and V is an array type VE[...] // SPEC: of the same rank then an exact inference from UE to VE is made. if (ExactArrayInference(source, target, ref useSiteInfo)) { return; } // SPEC: * Otherwise, if V is a constructed type C<V1...Vk> and U is a constructed // SPEC: type C<U1...Uk> then an exact inference is made // SPEC: from each Ui to the corresponding Vi. if (ExactConstructedInference(source, target, ref useSiteInfo)) { return; } // This can be valid via (where T : unmanaged) constraints if (ExactPointerInference(source, target, ref useSiteInfo)) { return; } // SPEC: * Otherwise no inferences are made. } private bool ExactTypeParameterInference(TypeWithAnnotations source, TypeWithAnnotations target) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: * If V is one of the unfixed Xi then U is added to the set of bounds // SPEC: for Xi. if (IsUnfixedTypeParameter(target)) { AddBound(source, _exactBounds, target); return true; } return false; } private bool ExactArrayInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: * Otherwise, if U is an array type UE[...] and V is an array type VE[...] // SPEC: of the same rank then an exact inference from UE to VE is made. if (!source.Type.IsArray() || !target.Type.IsArray()) { return false; } var arraySource = (ArrayTypeSymbol)source.Type; var arrayTarget = (ArrayTypeSymbol)target.Type; if (!arraySource.HasSameShapeAs(arrayTarget)) { return false; } ExactInference(arraySource.ElementTypeWithAnnotations, arrayTarget.ElementTypeWithAnnotations, ref useSiteInfo); return true; } private enum ExactOrBoundsKind { Exact, LowerBound, UpperBound, } private void ExactOrBoundsInference(ExactOrBoundsKind kind, TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { switch (kind) { case ExactOrBoundsKind.Exact: ExactInference(source, target, ref useSiteInfo); break; case ExactOrBoundsKind.LowerBound: LowerBoundInference(source, target, ref useSiteInfo); break; case ExactOrBoundsKind.UpperBound: UpperBoundInference(source, target, ref useSiteInfo); break; } } private bool ExactOrBoundsNullableInference(ExactOrBoundsKind kind, TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); if (source.IsNullableType() && target.IsNullableType()) { ExactOrBoundsInference(kind, ((NamedTypeSymbol)source.Type).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0], ((NamedTypeSymbol)target.Type).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0], ref useSiteInfo); return true; } if (isNullableOnly(source) && isNullableOnly(target)) { ExactOrBoundsInference(kind, source.AsNotNullableReferenceType(), target.AsNotNullableReferenceType(), ref useSiteInfo); return true; } return false; // True if the type is nullable. static bool isNullableOnly(TypeWithAnnotations type) => type.NullableAnnotation.IsAnnotated(); } private bool ExactNullableInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { return ExactOrBoundsNullableInference(ExactOrBoundsKind.Exact, source, target, ref useSiteInfo); } private bool LowerBoundTupleInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // NOTE: we are losing tuple element names when unwrapping tuple types to underlying types. // that is ok, because we are inferring type parameters used in the matching elements, // This is not the situation where entire tuple type used to infer a single type param ImmutableArray<TypeWithAnnotations> sourceTypes; ImmutableArray<TypeWithAnnotations> targetTypes; if (!source.Type.TryGetElementTypesWithAnnotationsIfTupleType(out sourceTypes) || !target.Type.TryGetElementTypesWithAnnotationsIfTupleType(out targetTypes) || sourceTypes.Length != targetTypes.Length) { return false; } for (int i = 0; i < sourceTypes.Length; i++) { LowerBoundInference(sourceTypes[i], targetTypes[i], ref useSiteInfo); } return true; } private bool ExactConstructedInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: * Otherwise, if V is a constructed type C<V1...Vk> and U is a constructed // SPEC: type C<U1...Uk> then an exact inference // SPEC: is made from each Ui to the corresponding Vi. var namedSource = source.Type as NamedTypeSymbol; if ((object)namedSource == null) { return false; } var namedTarget = target.Type as NamedTypeSymbol; if ((object)namedTarget == null) { return false; } if (!TypeSymbol.Equals(namedSource.OriginalDefinition, namedTarget.OriginalDefinition, TypeCompareKind.ConsiderEverything2)) { return false; } ExactTypeArgumentInference(namedSource, namedTarget, ref useSiteInfo); return true; } private bool ExactPointerInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (source.TypeKind == TypeKind.Pointer && target.TypeKind == TypeKind.Pointer) { ExactInference(((PointerTypeSymbol)source.Type).PointedAtTypeWithAnnotations, ((PointerTypeSymbol)target.Type).PointedAtTypeWithAnnotations, ref useSiteInfo); return true; } else if (source.Type is FunctionPointerTypeSymbol { Signature: { ParameterCount: int sourceParameterCount } sourceSignature } && target.Type is FunctionPointerTypeSymbol { Signature: { ParameterCount: int targetParameterCount } targetSignature } && sourceParameterCount == targetParameterCount) { if (!FunctionPointerRefKindsEqual(sourceSignature, targetSignature) || !FunctionPointerCallingConventionsEqual(sourceSignature, targetSignature)) { return false; } for (int i = 0; i < sourceParameterCount; i++) { ExactInference(sourceSignature.ParameterTypesWithAnnotations[i], targetSignature.ParameterTypesWithAnnotations[i], ref useSiteInfo); } ExactInference(sourceSignature.ReturnTypeWithAnnotations, targetSignature.ReturnTypeWithAnnotations, ref useSiteInfo); return true; } return false; } private static bool FunctionPointerCallingConventionsEqual(FunctionPointerMethodSymbol sourceSignature, FunctionPointerMethodSymbol targetSignature) { if (sourceSignature.CallingConvention != targetSignature.CallingConvention) { return false; } return (sourceSignature.GetCallingConventionModifiers(), targetSignature.GetCallingConventionModifiers()) switch { (null, null) => true, ({ } sourceModifiers, { } targetModifiers) when sourceModifiers.SetEquals(targetModifiers) => true, _ => false }; } private static bool FunctionPointerRefKindsEqual(FunctionPointerMethodSymbol sourceSignature, FunctionPointerMethodSymbol targetSignature) { return sourceSignature.RefKind == targetSignature.RefKind && (sourceSignature.ParameterRefKinds.IsDefault, targetSignature.ParameterRefKinds.IsDefault) switch { (true, false) or (false, true) => false, (true, true) => true, _ => sourceSignature.ParameterRefKinds.SequenceEqual(targetSignature.ParameterRefKinds) }; } private void ExactTypeArgumentInference(NamedTypeSymbol source, NamedTypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); Debug.Assert(TypeSymbol.Equals(source.OriginalDefinition, target.OriginalDefinition, TypeCompareKind.ConsiderEverything2)); var sourceTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); var targetTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); source.GetAllTypeArguments(sourceTypeArguments, ref useSiteInfo); target.GetAllTypeArguments(targetTypeArguments, ref useSiteInfo); Debug.Assert(sourceTypeArguments.Count == targetTypeArguments.Count); for (int arg = 0; arg < sourceTypeArguments.Count; ++arg) { ExactInference(sourceTypeArguments[arg], targetTypeArguments[arg], ref useSiteInfo); } sourceTypeArguments.Free(); targetTypeArguments.Free(); } //////////////////////////////////////////////////////////////////////////////// // // Lower-bound inferences // private void LowerBoundInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: A lower-bound inference from a type U to a type V is made as follows: // SPEC: * Otherwise, if V is nullable type V1? and U is nullable type U1? // SPEC: then an exact inference is made from U1 to V1. // SPEC ERROR: The spec should say "lower" here; we can safely make a lower-bound // SPEC ERROR: inference to nullable even though it is a generic struct. That is, // SPEC ERROR: if we have M<T>(T?, T) called with (char?, int) then we can infer // SPEC ERROR: lower bounds of char and int, and choose int. If we make an exact // SPEC ERROR: inference of char then type inference fails. if (LowerBoundNullableInference(source, target, ref useSiteInfo)) { return; } // SPEC: * If V is one of the unfixed Xi then U is added to the set of // SPEC: lower bounds for Xi. if (LowerBoundTypeParameterInference(source, target)) { return; } // SPEC: * Otherwise, if U is an array type Ue[...] and V is either an array // SPEC: type Ve[...] of the same rank, or if U is a one-dimensional array // SPEC: type Ue[] and V is one of IEnumerable<Ve>, ICollection<Ve> or // SPEC: IList<Ve> then // SPEC: * if Ue is known to be a reference type then a lower-bound inference // SPEC: from Ue to Ve is made. // SPEC: * otherwise an exact inference from Ue to Ve is made. if (LowerBoundArrayInference(source.Type, target.Type, ref useSiteInfo)) { return; } // UNDONE: At this point we could also do an inference from non-nullable U // UNDONE: to nullable V. // UNDONE: // UNDONE: We tried implementing lower bound nullable inference as follows: // UNDONE: // UNDONE: * Otherwise, if V is nullable type V1? and U is a non-nullable // UNDONE: struct type then an exact inference is made from U to V1. // UNDONE: // UNDONE: However, this causes an unfortunate interaction with what // UNDONE: looks like a bug in our implementation of section 15.2 of // UNDONE: the specification. Namely, it appears that the code which // UNDONE: checks whether a given method is compatible with // UNDONE: a delegate type assumes that if method type inference succeeds, // UNDONE: then the inferred types are compatible with the delegate types. // UNDONE: This is not necessarily so; the inferred types could be compatible // UNDONE: via a conversion other than reference or identity. // UNDONE: // UNDONE: We should take an action item to investigate this problem. // UNDONE: Until then, we will turn off the proposed lower bound nullable // UNDONE: inference. // if (LowerBoundNullableInference(pSource, pDest)) // { // return; // } if (LowerBoundTupleInference(source, target, ref useSiteInfo)) { return; } // SPEC: Otherwise... many cases for constructed generic types. if (LowerBoundConstructedInference(source.Type, target.Type, ref useSiteInfo)) { return; } if (LowerBoundFunctionPointerTypeInference(source.Type, target.Type, ref useSiteInfo)) { return; } // SPEC: * Otherwise, no inferences are made. } private bool LowerBoundTypeParameterInference(TypeWithAnnotations source, TypeWithAnnotations target) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: * If V is one of the unfixed Xi then U is added to the set of bounds // SPEC: for Xi. if (IsUnfixedTypeParameter(target)) { AddBound(source, _lowerBounds, target); return true; } return false; } private static TypeWithAnnotations GetMatchingElementType(ArrayTypeSymbol source, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); // It might be an array of same rank. if (target.IsArray()) { var arrayTarget = (ArrayTypeSymbol)target; if (!arrayTarget.HasSameShapeAs(source)) { return default; } return arrayTarget.ElementTypeWithAnnotations; } // Or it might be IEnum<T> and source is rank one. if (!source.IsSZArray) { return default; } // Arrays are specified as being convertible to IEnumerable<T>, ICollection<T> and // IList<T>; we also honor their convertibility to IReadOnlyCollection<T> and // IReadOnlyList<T>, and make inferences accordingly. if (!target.IsPossibleArrayGenericInterface()) { return default; } return ((NamedTypeSymbol)target).TypeArgumentWithDefinitionUseSiteDiagnostics(0, ref useSiteInfo); } private bool LowerBoundArrayInference(TypeSymbol source, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); // SPEC: * Otherwise, if U is an array type Ue[...] and V is either an array // SPEC: type Ve[...] of the same rank, or if U is a one-dimensional array // SPEC: type Ue[] and V is one of IEnumerable<Ve>, ICollection<Ve> or // SPEC: IList<Ve> then // SPEC: * if Ue is known to be a reference type then a lower-bound inference // SPEC: from Ue to Ve is made. // SPEC: * otherwise an exact inference from Ue to Ve is made. if (!source.IsArray()) { return false; } var arraySource = (ArrayTypeSymbol)source; var elementSource = arraySource.ElementTypeWithAnnotations; var elementTarget = GetMatchingElementType(arraySource, target, ref useSiteInfo); if (!elementTarget.HasType) { return false; } if (elementSource.Type.IsReferenceType) { LowerBoundInference(elementSource, elementTarget, ref useSiteInfo); } else { ExactInference(elementSource, elementTarget, ref useSiteInfo); } return true; } private bool LowerBoundNullableInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { return ExactOrBoundsNullableInference(ExactOrBoundsKind.LowerBound, source, target, ref useSiteInfo); } private bool LowerBoundConstructedInference(TypeSymbol source, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); var constructedTarget = target as NamedTypeSymbol; if ((object)constructedTarget == null) { return false; } if (constructedTarget.AllTypeArgumentCount() == 0) { return false; } // SPEC: * Otherwise, if V is a constructed class or struct type C<V1...Vk> // SPEC: and U is C<U1...Uk> then an exact inference // SPEC: is made from each Ui to the corresponding Vi. // SPEC: * Otherwise, if V is a constructed interface or delegate type C<V1...Vk> // SPEC: and U is C<U1...Uk> then an exact inference, // SPEC: lower bound inference or upper bound inference // SPEC: is made from each Ui to the corresponding Vi. var constructedSource = source as NamedTypeSymbol; if ((object)constructedSource != null && TypeSymbol.Equals(constructedSource.OriginalDefinition, constructedTarget.OriginalDefinition, TypeCompareKind.ConsiderEverything2)) { if (constructedSource.IsInterface || constructedSource.IsDelegateType()) { LowerBoundTypeArgumentInference(constructedSource, constructedTarget, ref useSiteInfo); } else { ExactTypeArgumentInference(constructedSource, constructedTarget, ref useSiteInfo); } return true; } // SPEC: * Otherwise, if V is a class type C<V1...Vk> and U is a class type which // SPEC: inherits directly or indirectly from C<U1...Uk> then an exact ... // SPEC: * ... and U is a type parameter with effective base class ... // SPEC: * ... and U is a type parameter with an effective base class which inherits ... if (LowerBoundClassInference(source, constructedTarget, ref useSiteInfo)) { return true; } // SPEC: * Otherwise, if V is an interface type C<V1...Vk> and U is a class type // SPEC: or struct type and there is a unique set U1...Uk such that U directly // SPEC: or indirectly implements C<U1...Uk> then an exact ... // SPEC: * ... and U is an interface type ... // SPEC: * ... and U is a type parameter ... if (LowerBoundInterfaceInference(source, constructedTarget, ref useSiteInfo)) { return true; } return false; } private bool LowerBoundClassInference(TypeSymbol source, NamedTypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); if (target.TypeKind != TypeKind.Class) { return false; } // Spec: 7.5.2.9 Lower-bound interfaces // SPEC: * Otherwise, if V is a class type C<V1...Vk> and U is a class type which // SPEC: inherits directly or indirectly from C<U1...Uk> // SPEC: then an exact inference is made from each Ui to the corresponding Vi. // SPEC: * Otherwise, if V is a class type C<V1...Vk> and U is a type parameter // SPEC: with effective base class C<U1...Uk> // SPEC: then an exact inference is made from each Ui to the corresponding Vi. // SPEC: * Otherwise, if V is a class type C<V1...Vk> and U is a type parameter // SPEC: with an effective base class which inherits directly or indirectly from // SPEC: C<U1...Uk> then an exact inference is made // SPEC: from each Ui to the corresponding Vi. NamedTypeSymbol sourceBase = null; if (source.TypeKind == TypeKind.Class) { sourceBase = source.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); } else if (source.TypeKind == TypeKind.TypeParameter) { sourceBase = ((TypeParameterSymbol)source).EffectiveBaseClass(ref useSiteInfo); } while ((object)sourceBase != null) { if (TypeSymbol.Equals(sourceBase.OriginalDefinition, target.OriginalDefinition, TypeCompareKind.ConsiderEverything2)) { ExactTypeArgumentInference(sourceBase, target, ref useSiteInfo); return true; } sourceBase = sourceBase.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); } return false; } private bool LowerBoundInterfaceInference(TypeSymbol source, NamedTypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); if (!target.IsInterface) { return false; } // Spec 7.5.2.9 Lower-bound interfaces // SPEC: * Otherwise, if V [target] is an interface type C<V1...Vk> and U [source] is a class type // SPEC: or struct type and there is a unique set U1...Uk such that U directly // SPEC: or indirectly implements C<U1...Uk> then an // SPEC: exact, upper-bound, or lower-bound inference ... // SPEC: * ... and U is an interface type ... // SPEC: * ... and U is a type parameter ... ImmutableArray<NamedTypeSymbol> allInterfaces; switch (source.TypeKind) { case TypeKind.Struct: case TypeKind.Class: case TypeKind.Interface: allInterfaces = source.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo); break; case TypeKind.TypeParameter: var typeParameter = (TypeParameterSymbol)source; allInterfaces = typeParameter.EffectiveBaseClass(ref useSiteInfo). AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo). Concat(typeParameter.AllEffectiveInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo)); break; default: return false; } // duplicates with only nullability differences can be merged (to avoid an error in type inference) allInterfaces = ModuloReferenceTypeNullabilityDifferences(allInterfaces, VarianceKind.In); NamedTypeSymbol matchingInterface = GetInterfaceInferenceBound(allInterfaces, target); if ((object)matchingInterface == null) { return false; } LowerBoundTypeArgumentInference(matchingInterface, target, ref useSiteInfo); return true; } internal static ImmutableArray<NamedTypeSymbol> ModuloReferenceTypeNullabilityDifferences(ImmutableArray<NamedTypeSymbol> interfaces, VarianceKind variance) { var dictionary = PooledDictionaryIgnoringNullableModifiersForReferenceTypes.GetInstance(); foreach (var @interface in interfaces) { if (dictionary.TryGetValue(@interface, out var found)) { var merged = (NamedTypeSymbol)found.MergeEquivalentTypes(@interface, variance); dictionary[@interface] = merged; } else { dictionary.Add(@interface, @interface); } } var result = dictionary.Count != interfaces.Length ? dictionary.Values.ToImmutableArray() : interfaces; dictionary.Free(); return result; } private void LowerBoundTypeArgumentInference(NamedTypeSymbol source, NamedTypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: The choice of inference for the i-th type argument is made // SPEC: based on the declaration of the i-th type parameter of C, as // SPEC: follows: // SPEC: * if Ui is known to be of reference type and the i-th type parameter // SPEC: was declared as covariant then a lower bound inference is made. // SPEC: * if Ui is known to be of reference type and the i-th type parameter // SPEC: was declared as contravariant then an upper bound inference is made. // SPEC: * otherwise, an exact inference is made. Debug.Assert((object)source != null); Debug.Assert((object)target != null); Debug.Assert(TypeSymbol.Equals(source.OriginalDefinition, target.OriginalDefinition, TypeCompareKind.ConsiderEverything2)); var typeParameters = ArrayBuilder<TypeParameterSymbol>.GetInstance(); var sourceTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); var targetTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); source.OriginalDefinition.GetAllTypeParameters(typeParameters); source.GetAllTypeArguments(sourceTypeArguments, ref useSiteInfo); target.GetAllTypeArguments(targetTypeArguments, ref useSiteInfo); Debug.Assert(typeParameters.Count == sourceTypeArguments.Count); Debug.Assert(typeParameters.Count == targetTypeArguments.Count); for (int arg = 0; arg < sourceTypeArguments.Count; ++arg) { var typeParameter = typeParameters[arg]; var sourceTypeArgument = sourceTypeArguments[arg]; var targetTypeArgument = targetTypeArguments[arg]; if (sourceTypeArgument.Type.IsReferenceType && typeParameter.Variance == VarianceKind.Out) { LowerBoundInference(sourceTypeArgument, targetTypeArgument, ref useSiteInfo); } else if (sourceTypeArgument.Type.IsReferenceType && typeParameter.Variance == VarianceKind.In) { UpperBoundInference(sourceTypeArgument, targetTypeArgument, ref useSiteInfo); } else { ExactInference(sourceTypeArgument, targetTypeArgument, ref useSiteInfo); } } typeParameters.Free(); sourceTypeArguments.Free(); targetTypeArguments.Free(); } #nullable enable private bool LowerBoundFunctionPointerTypeInference(TypeSymbol source, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (source is not FunctionPointerTypeSymbol { Signature: { } sourceSignature } || target is not FunctionPointerTypeSymbol { Signature: { } targetSignature }) { return false; } if (sourceSignature.ParameterCount != targetSignature.ParameterCount) { return false; } if (!FunctionPointerRefKindsEqual(sourceSignature, targetSignature) || !FunctionPointerCallingConventionsEqual(sourceSignature, targetSignature)) { return false; } // Reference parameters are treated as "input" variance by default, and reference return types are treated as out variance by default. // If they have a ref kind or are not reference types, then they are treated as invariant. for (int i = 0; i < sourceSignature.ParameterCount; i++) { var sourceParam = sourceSignature.Parameters[i]; var targetParam = targetSignature.Parameters[i]; if ((sourceParam.Type.IsReferenceType || sourceParam.Type.IsFunctionPointer()) && sourceParam.RefKind == RefKind.None) { UpperBoundInference(sourceParam.TypeWithAnnotations, targetParam.TypeWithAnnotations, ref useSiteInfo); } else { ExactInference(sourceParam.TypeWithAnnotations, targetParam.TypeWithAnnotations, ref useSiteInfo); } } if ((sourceSignature.ReturnType.IsReferenceType || sourceSignature.ReturnType.IsFunctionPointer()) && sourceSignature.RefKind == RefKind.None) { LowerBoundInference(sourceSignature.ReturnTypeWithAnnotations, targetSignature.ReturnTypeWithAnnotations, ref useSiteInfo); } else { ExactInference(sourceSignature.ReturnTypeWithAnnotations, targetSignature.ReturnTypeWithAnnotations, ref useSiteInfo); } return true; } #nullable disable //////////////////////////////////////////////////////////////////////////////// // // Upper-bound inferences // private void UpperBoundInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: An upper-bound inference from a type U to a type V is made as follows: // SPEC: * Otherwise, if V is nullable type V1? and U is nullable type U1? // SPEC: then an exact inference is made from U1 to V1. if (UpperBoundNullableInference(source, target, ref useSiteInfo)) { return; } // SPEC: * If V is one of the unfixed Xi then U is added to the set of // SPEC: upper bounds for Xi. if (UpperBoundTypeParameterInference(source, target)) { return; } // SPEC: * Otherwise, if V is an array type Ve[...] and U is an array // SPEC: type Ue[...] of the same rank, or if V is a one-dimensional array // SPEC: type Ve[] and U is one of IEnumerable<Ue>, ICollection<Ue> or // SPEC: IList<Ue> then // SPEC: * if Ue is known to be a reference type then an upper-bound inference // SPEC: from Ue to Ve is made. // SPEC: * otherwise an exact inference from Ue to Ve is made. if (UpperBoundArrayInference(source, target, ref useSiteInfo)) { return; } Debug.Assert(source.Type.IsReferenceType || source.Type.IsFunctionPointer()); // NOTE: spec would ask us to do the following checks, but since the value types // are trivially handled as exact inference in the callers, we do not have to. //if (ExactTupleInference(source, target, ref useSiteInfo)) //{ // return; //} // SPEC: * Otherwise... cases for constructed types if (UpperBoundConstructedInference(source, target, ref useSiteInfo)) { return; } if (UpperBoundFunctionPointerTypeInference(source.Type, target.Type, ref useSiteInfo)) { return; } // SPEC: * Otherwise, no inferences are made. } private bool UpperBoundTypeParameterInference(TypeWithAnnotations source, TypeWithAnnotations target) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: * If V is one of the unfixed Xi then U is added to the set of upper bounds // SPEC: for Xi. if (IsUnfixedTypeParameter(target)) { AddBound(source, _upperBounds, target); return true; } return false; } private bool UpperBoundArrayInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: * Otherwise, if V is an array type Ve[...] and U is an array // SPEC: type Ue[...] of the same rank, or if V is a one-dimensional array // SPEC: type Ve[] and U is one of IEnumerable<Ue>, ICollection<Ue> or // SPEC: IList<Ue> then // SPEC: * if Ue is known to be a reference type then an upper-bound inference // SPEC: from Ue to Ve is made. // SPEC: * otherwise an exact inference from Ue to Ve is made. if (!target.Type.IsArray()) { return false; } var arrayTarget = (ArrayTypeSymbol)target.Type; var elementTarget = arrayTarget.ElementTypeWithAnnotations; var elementSource = GetMatchingElementType(arrayTarget, source.Type, ref useSiteInfo); if (!elementSource.HasType) { return false; } if (elementSource.Type.IsReferenceType) { UpperBoundInference(elementSource, elementTarget, ref useSiteInfo); } else { ExactInference(elementSource, elementTarget, ref useSiteInfo); } return true; } private bool UpperBoundNullableInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { return ExactOrBoundsNullableInference(ExactOrBoundsKind.UpperBound, source, target, ref useSiteInfo); } private bool UpperBoundConstructedInference(TypeWithAnnotations sourceWithAnnotations, TypeWithAnnotations targetWithAnnotations, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(sourceWithAnnotations.HasType); Debug.Assert(targetWithAnnotations.HasType); var source = sourceWithAnnotations.Type; var target = targetWithAnnotations.Type; var constructedSource = source as NamedTypeSymbol; if ((object)constructedSource == null) { return false; } if (constructedSource.AllTypeArgumentCount() == 0) { return false; } // SPEC: * Otherwise, if V is a constructed type C<V1...Vk> and U is // SPEC: C<U1...Uk> then an exact inference, // SPEC: lower bound inference or upper bound inference // SPEC: is made from each Ui to the corresponding Vi. var constructedTarget = target as NamedTypeSymbol; if ((object)constructedTarget != null && TypeSymbol.Equals(constructedSource.OriginalDefinition, target.OriginalDefinition, TypeCompareKind.ConsiderEverything2)) { if (constructedTarget.IsInterface || constructedTarget.IsDelegateType()) { UpperBoundTypeArgumentInference(constructedSource, constructedTarget, ref useSiteInfo); } else { ExactTypeArgumentInference(constructedSource, constructedTarget, ref useSiteInfo); } return true; } // SPEC: * Otherwise, if U is a class type C<U1...Uk> and V is a class type which // SPEC: inherits directly or indirectly from C<V1...Vk> then an exact ... if (UpperBoundClassInference(constructedSource, target, ref useSiteInfo)) { return true; } // SPEC: * Otherwise, if U is an interface type C<U1...Uk> and V is a class type // SPEC: or struct type and there is a unique set V1...Vk such that V directly // SPEC: or indirectly implements C<V1...Vk> then an exact ... // SPEC: * ... and U is an interface type ... if (UpperBoundInterfaceInference(constructedSource, target, ref useSiteInfo)) { return true; } return false; } private bool UpperBoundClassInference(NamedTypeSymbol source, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); if (source.TypeKind != TypeKind.Class || target.TypeKind != TypeKind.Class) { return false; } // SPEC: * Otherwise, if U is a class type C<U1...Uk> and V is a class type which // SPEC: inherits directly or indirectly from C<V1...Vk> then an exact // SPEC: inference is made from each Ui to the corresponding Vi. var targetBase = target.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); while ((object)targetBase != null) { if (TypeSymbol.Equals(targetBase.OriginalDefinition, source.OriginalDefinition, TypeCompareKind.ConsiderEverything2)) { ExactTypeArgumentInference(source, targetBase, ref useSiteInfo); return true; } targetBase = targetBase.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); } return false; } private bool UpperBoundInterfaceInference(NamedTypeSymbol source, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); if (!source.IsInterface) { return false; } // SPEC: * Otherwise, if U [source] is an interface type C<U1...Uk> and V [target] is a class type // SPEC: or struct type and there is a unique set V1...Vk such that V directly // SPEC: or indirectly implements C<V1...Vk> then an exact ... // SPEC: * ... and U is an interface type ... switch (target.TypeKind) { case TypeKind.Struct: case TypeKind.Class: case TypeKind.Interface: break; default: return false; } ImmutableArray<NamedTypeSymbol> allInterfaces = target.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo); // duplicates with only nullability differences can be merged (to avoid an error in type inference) allInterfaces = ModuloReferenceTypeNullabilityDifferences(allInterfaces, VarianceKind.Out); NamedTypeSymbol bestInterface = GetInterfaceInferenceBound(allInterfaces, source); if ((object)bestInterface == null) { return false; } UpperBoundTypeArgumentInference(source, bestInterface, ref useSiteInfo); return true; } private void UpperBoundTypeArgumentInference(NamedTypeSymbol source, NamedTypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: The choice of inference for the i-th type argument is made // SPEC: based on the declaration of the i-th type parameter of C, as // SPEC: follows: // SPEC: * if Ui is known to be of reference type and the i-th type parameter // SPEC: was declared as covariant then an upper-bound inference is made. // SPEC: * if Ui is known to be of reference type and the i-th type parameter // SPEC: was declared as contravariant then a lower-bound inference is made. // SPEC: * otherwise, an exact inference is made. Debug.Assert((object)source != null); Debug.Assert((object)target != null); Debug.Assert(TypeSymbol.Equals(source.OriginalDefinition, target.OriginalDefinition, TypeCompareKind.ConsiderEverything2)); var typeParameters = ArrayBuilder<TypeParameterSymbol>.GetInstance(); var sourceTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); var targetTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); source.OriginalDefinition.GetAllTypeParameters(typeParameters); source.GetAllTypeArguments(sourceTypeArguments, ref useSiteInfo); target.GetAllTypeArguments(targetTypeArguments, ref useSiteInfo); Debug.Assert(typeParameters.Count == sourceTypeArguments.Count); Debug.Assert(typeParameters.Count == targetTypeArguments.Count); for (int arg = 0; arg < sourceTypeArguments.Count; ++arg) { var typeParameter = typeParameters[arg]; var sourceTypeArgument = sourceTypeArguments[arg]; var targetTypeArgument = targetTypeArguments[arg]; if (sourceTypeArgument.Type.IsReferenceType && typeParameter.Variance == VarianceKind.Out) { UpperBoundInference(sourceTypeArgument, targetTypeArgument, ref useSiteInfo); } else if (sourceTypeArgument.Type.IsReferenceType && typeParameter.Variance == VarianceKind.In) { LowerBoundInference(sourceTypeArgument, targetTypeArgument, ref useSiteInfo); } else { ExactInference(sourceTypeArgument, targetTypeArgument, ref useSiteInfo); } } typeParameters.Free(); sourceTypeArguments.Free(); targetTypeArguments.Free(); } #nullable enable private bool UpperBoundFunctionPointerTypeInference(TypeSymbol source, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (source is not FunctionPointerTypeSymbol { Signature: { } sourceSignature } || target is not FunctionPointerTypeSymbol { Signature: { } targetSignature }) { return false; } if (sourceSignature.ParameterCount != targetSignature.ParameterCount) { return false; } if (!FunctionPointerRefKindsEqual(sourceSignature, targetSignature) || !FunctionPointerCallingConventionsEqual(sourceSignature, targetSignature)) { return false; } // Reference parameters are treated as "input" variance by default, and reference return types are treated as out variance by default. // If they have a ref kind or are not reference types, then they are treated as invariant. for (int i = 0; i < sourceSignature.ParameterCount; i++) { var sourceParam = sourceSignature.Parameters[i]; var targetParam = targetSignature.Parameters[i]; if ((sourceParam.Type.IsReferenceType || sourceParam.Type.IsFunctionPointer()) && sourceParam.RefKind == RefKind.None) { LowerBoundInference(sourceParam.TypeWithAnnotations, targetParam.TypeWithAnnotations, ref useSiteInfo); } else { ExactInference(sourceParam.TypeWithAnnotations, targetParam.TypeWithAnnotations, ref useSiteInfo); } } if ((sourceSignature.ReturnType.IsReferenceType || sourceSignature.ReturnType.IsFunctionPointer()) && sourceSignature.RefKind == RefKind.None) { UpperBoundInference(sourceSignature.ReturnTypeWithAnnotations, targetSignature.ReturnTypeWithAnnotations, ref useSiteInfo); } else { ExactInference(sourceSignature.ReturnTypeWithAnnotations, targetSignature.ReturnTypeWithAnnotations, ref useSiteInfo); } return true; } //////////////////////////////////////////////////////////////////////////////// // // Fixing // private bool Fix(int iParam, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(IsUnfixed(iParam)); var typeParameter = _methodTypeParameters[iParam]; var exact = _exactBounds[iParam]; var lower = _lowerBounds[iParam]; var upper = _upperBounds[iParam]; var best = Fix(_compilation, _conversions, typeParameter, exact, lower, upper, ref useSiteInfo); if (!best.Type.HasType) { return false; } #if DEBUG if (_conversions.IncludeNullability) { // If the first attempt succeeded, the result should be the same as // the second attempt, although perhaps with different nullability. var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var withoutNullability = Fix(_compilation, _conversions.WithNullability(false), typeParameter, exact, lower, upper, ref discardedUseSiteInfo).Type; // https://github.com/dotnet/roslyn/issues/27961 Results may differ by tuple names or dynamic. // See NullableReferenceTypesTests.TypeInference_TupleNameDifferences_01 for example. Debug.Assert(best.Type.Type.Equals(withoutNullability.Type, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); } #endif _fixedResults[iParam] = best; UpdateDependenciesAfterFix(iParam); return true; } private static (TypeWithAnnotations Type, bool FromFunctionType) Fix( CSharpCompilation compilation, ConversionsBase conversions, TypeParameterSymbol typeParameter, HashSet<TypeWithAnnotations>? exact, HashSet<TypeWithAnnotations>? lower, HashSet<TypeWithAnnotations>? upper, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // UNDONE: This method makes a lot of garbage. // SPEC: An unfixed type parameter with a set of bounds is fixed as follows: // SPEC: * The set of candidate types starts out as the set of all types in // SPEC: the bounds. // SPEC: * We then examine each bound in turn. For each exact bound U of Xi, // SPEC: all types which are not identical to U are removed from the candidate set. // Optimization: if we have two or more exact bounds, fixing is impossible. var candidates = new Dictionary<TypeWithAnnotations, TypeWithAnnotations>(EqualsIgnoringDynamicTupleNamesAndNullabilityComparer.Instance); Debug.Assert(!containsFunctionTypes(exact)); Debug.Assert(!containsFunctionTypes(upper)); // Function types are dropped if there are any non-function types. if (containsFunctionTypes(lower) && (containsNonFunctionTypes(lower) || containsNonFunctionTypes(exact) || containsNonFunctionTypes(upper))) { lower = removeFunctionTypes(lower); } // Optimization: if we have one exact bound then we need not add any // inexact bounds; we're just going to remove them anyway. if (exact == null) { if (lower != null) { // Lower bounds represent co-variance. AddAllCandidates(candidates, lower, VarianceKind.Out, conversions); } if (upper != null) { // Upper bounds represent contra-variance. AddAllCandidates(candidates, upper, VarianceKind.In, conversions); } } else { // Exact bounds represent invariance. AddAllCandidates(candidates, exact, VarianceKind.None, conversions); if (candidates.Count >= 2) { return default; } } if (candidates.Count == 0) { return default; } // Don't mutate the collection as we're iterating it. var initialCandidates = ArrayBuilder<TypeWithAnnotations>.GetInstance(); GetAllCandidates(candidates, initialCandidates); // SPEC: For each lower bound U of Xi all types to which there is not an // SPEC: implicit conversion from U are removed from the candidate set. if (lower != null) { MergeOrRemoveCandidates(candidates, lower, initialCandidates, conversions, VarianceKind.Out, ref useSiteInfo); } // SPEC: For each upper bound U of Xi all types from which there is not an // SPEC: implicit conversion to U are removed from the candidate set. if (upper != null) { MergeOrRemoveCandidates(candidates, upper, initialCandidates, conversions, VarianceKind.In, ref useSiteInfo); } initialCandidates.Clear(); GetAllCandidates(candidates, initialCandidates); // SPEC: * If among the remaining candidate types there is a unique type V to // SPEC: which there is an implicit conversion from all the other candidate // SPEC: types, then the parameter is fixed to V. TypeWithAnnotations best = default; foreach (var candidate in initialCandidates) { foreach (var candidate2 in initialCandidates) { if (!candidate.Equals(candidate2, TypeCompareKind.ConsiderEverything) && !ImplicitConversionExists(candidate2, candidate, ref useSiteInfo, conversions.WithNullability(false))) { goto OuterBreak; } } if (!best.HasType) { best = candidate; } else { Debug.Assert(!best.Equals(candidate, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); // best candidate is not unique best = default; break; } OuterBreak: ; } initialCandidates.Free(); bool fromFunctionType = false; if (isFunctionType(best, out var functionType)) { // Realize the type as TDelegate, or Expression<TDelegate> if the type parameter // is constrained to System.Linq.Expressions.Expression. var resultType = functionType.GetInternalDelegateType(); if (hasExpressionTypeConstraint(typeParameter)) { var expressionOfTType = compilation.GetWellKnownType(WellKnownType.System_Linq_Expressions_Expression_T); resultType = expressionOfTType.Construct(resultType); } best = TypeWithAnnotations.Create(resultType, best.NullableAnnotation); fromFunctionType = true; } return (best, fromFunctionType); static bool containsFunctionTypes([NotNullWhen(true)] HashSet<TypeWithAnnotations>? types) { return types?.Any(t => isFunctionType(t, out _)) == true; } static bool containsNonFunctionTypes([NotNullWhen(true)] HashSet<TypeWithAnnotations>? types) { return types?.Any(t => !isFunctionType(t, out _)) == true; } static bool isFunctionType(TypeWithAnnotations type, [NotNullWhen(true)] out FunctionTypeSymbol? functionType) { functionType = type.Type as FunctionTypeSymbol; return functionType is not null; } static bool hasExpressionTypeConstraint(TypeParameterSymbol typeParameter) { var constraintTypes = typeParameter.ConstraintTypesNoUseSiteDiagnostics; return constraintTypes.Any(t => isExpressionType(t.Type)); } static bool isExpressionType(TypeSymbol? type) { while (type is { }) { if (type.IsGenericOrNonGenericExpressionType(out _)) { return true; } type = type.BaseTypeNoUseSiteDiagnostics; } return false; } static HashSet<TypeWithAnnotations>? removeFunctionTypes(HashSet<TypeWithAnnotations> types) { HashSet<TypeWithAnnotations>? updated = null; foreach (var type in types) { if (!isFunctionType(type, out _)) { updated ??= new HashSet<TypeWithAnnotations>(TypeWithAnnotations.EqualsComparer.ConsiderEverythingComparer); updated.Add(type); } } return updated; } } private static bool ImplicitConversionExists(TypeWithAnnotations sourceWithAnnotations, TypeWithAnnotations destinationWithAnnotations, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, ConversionsBase conversions) { var source = sourceWithAnnotations.Type; var destination = destinationWithAnnotations.Type; // SPEC VIOLATION: For the purpose of algorithm in Fix method, dynamic type is not considered convertible to any other type, including object. if (source.IsDynamic() && !destination.IsDynamic()) { return false; } if (!conversions.HasTopLevelNullabilityImplicitConversion(sourceWithAnnotations, destinationWithAnnotations)) { return false; } return conversions.ClassifyImplicitConversionFromType(source, destination, ref useSiteInfo).Exists; } #nullable disable //////////////////////////////////////////////////////////////////////////////// // // Inferred return type // private TypeWithAnnotations InferReturnType(BoundExpression source, NamedTypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)target != null); Debug.Assert(target.IsDelegateType()); Debug.Assert((object)target.DelegateInvokeMethod != null && !target.DelegateInvokeMethod.HasUseSiteError, "This method should only be called for legal delegate types."); Debug.Assert(!target.DelegateInvokeMethod.ReturnsVoid); // We should not be computing the inferred return type unless we are converting // to a delegate type where all the input types are fixed. Debug.Assert(!HasUnfixedParamInInputType(source, target)); // Spec 7.5.2.12: Inferred return type: // The inferred return type of an anonymous function F is used during // type inference and overload resolution. The inferred return type // can only be determined for an anonymous function where all parameter // types are known, either because they are explicitly given, provided // through an anonymous function conversion, or inferred during type // inference on an enclosing generic method invocation. // The inferred return type is determined as follows: // * If the body of F is an expression (that has a type) then the // inferred return type of F is the type of that expression. // * If the body of F is a block and the set of expressions in the // blocks return statements has a best common type T then the // inferred return type of F is T. // * Otherwise, a return type cannot be inferred for F. if (source.Kind != BoundKind.UnboundLambda) { return default; } var anonymousFunction = (UnboundLambda)source; if (anonymousFunction.HasSignature) { // Optimization: // We know that the anonymous function has a parameter list. If it does not // have the same arity as the delegate, then it cannot possibly be applicable. // Rather than have type inference fail, we will simply not make a return // type inference and have type inference continue on. Either inference // will fail, or we will infer a nonapplicable method. Either way, there // is no change to the semantics of overload resolution. var originalDelegateParameters = target.DelegateParameters(); if (originalDelegateParameters.IsDefault) { return default; } if (originalDelegateParameters.Length != anonymousFunction.ParameterCount) { return default; } } var fixedDelegate = (NamedTypeSymbol)GetFixedDelegateOrFunctionPointer(target); var fixedDelegateParameters = fixedDelegate.DelegateParameters(); // Optimization: // Similarly, if we have an entirely fixed delegate and an explicitly typed // anonymous function, then the parameter types had better be identical. // If not, applicability will eventually fail, so there is no semantic // difference caused by failing to make a return type inference. if (anonymousFunction.HasExplicitlyTypedParameterList) { for (int p = 0; p < anonymousFunction.ParameterCount; ++p) { if (!anonymousFunction.ParameterType(p).Equals(fixedDelegateParameters[p].Type, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)) { return default; } } } // Future optimization: We could return default if the delegate has out or ref parameters // and the anonymous function is an implicitly typed lambda. It will not be applicable. // We have an entirely fixed delegate parameter list, which is of the same arity as // the anonymous function parameter list, and possibly exactly the same types if // the anonymous function is explicitly typed. Make an inference from the // delegate parameters to the return type. return anonymousFunction.InferReturnType(_conversions, fixedDelegate, ref useSiteInfo); } /// <summary> /// Return the interface with an original definition matches /// the original definition of the target. If the are no matches, /// or multiple matches, the return value is null. /// </summary> private static NamedTypeSymbol GetInterfaceInferenceBound(ImmutableArray<NamedTypeSymbol> interfaces, NamedTypeSymbol target) { Debug.Assert(target.IsInterface); NamedTypeSymbol matchingInterface = null; foreach (var currentInterface in interfaces) { if (TypeSymbol.Equals(currentInterface.OriginalDefinition, target.OriginalDefinition, TypeCompareKind.ConsiderEverything)) { if ((object)matchingInterface == null) { matchingInterface = currentInterface; } else if (!TypeSymbol.Equals(matchingInterface, currentInterface, TypeCompareKind.ConsiderEverything)) { // Not unique. Bail out. return null; } } } return matchingInterface; } //////////////////////////////////////////////////////////////////////////////// // // Helper methods // //////////////////////////////////////////////////////////////////////////////// // // In error recovery and reporting scenarios we sometimes end up in a situation // like this: // // x.Goo( y=> // // and the question is, "is Goo a valid extension method of x?" If Goo is // generic, then Goo will be something like: // // static Blah Goo<T>(this Bar<T> bar, Func<T, T> f){ ... } // // What we would like to know is: given _only_ the expression x, can we infer // what T is in Bar<T> ? If we can, then for error recovery and reporting // we can provisionally consider Goo to be an extension method of x. If we // cannot deduce this just from x then we should consider Goo to not be an // extension method of x, at least until we have more information. // // Clearly it is pointless to run multiple phases public static ImmutableArray<TypeWithAnnotations> InferTypeArgumentsFromFirstArgument( CSharpCompilation compilation, ConversionsBase conversions, MethodSymbol method, ImmutableArray<BoundExpression> arguments, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)method != null); Debug.Assert(method.Arity > 0); Debug.Assert(!arguments.IsDefault); // We need at least one formal parameter type and at least one argument. if ((method.ParameterCount < 1) || (arguments.Length < 1)) { return default(ImmutableArray<TypeWithAnnotations>); } Debug.Assert(!method.GetParameterType(0).IsDynamic()); var constructedFromMethod = method.ConstructedFrom; var inferrer = new MethodTypeInferrer( compilation, conversions, constructedFromMethod.TypeParameters, constructedFromMethod.ContainingType, constructedFromMethod.GetParameterTypes(), constructedFromMethod.ParameterRefKinds, arguments, extensions: null); if (!inferrer.InferTypeArgumentsFromFirstArgument(ref useSiteInfo)) { return default(ImmutableArray<TypeWithAnnotations>); } return inferrer.GetInferredTypeArguments(out _); } //////////////////////////////////////////////////////////////////////////////// private bool InferTypeArgumentsFromFirstArgument(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(!_formalParameterTypes.IsDefault); Debug.Assert(_formalParameterTypes.Length >= 1); Debug.Assert(!_arguments.IsDefault); Debug.Assert(_arguments.Length >= 1); var dest = _formalParameterTypes[0]; var argument = _arguments[0]; TypeSymbol source = argument.Type; // Rule out lambdas, nulls, and so on. if (!IsReallyAType(source)) { return false; } LowerBoundInference(_extensions.GetTypeWithAnnotations(argument), dest, ref useSiteInfo); // Now check to see that every type parameter used by the first // formal parameter type was successfully inferred. for (int iParam = 0; iParam < _methodTypeParameters.Length; ++iParam) { TypeParameterSymbol pParam = _methodTypeParameters[iParam]; if (!dest.Type.ContainsTypeParameter(pParam)) { continue; } Debug.Assert(IsUnfixed(iParam)); if (!HasBound(iParam) || !Fix(iParam, ref useSiteInfo)) { return false; } } return true; } #nullable enable /// <summary> /// Return the inferred type arguments using null /// for any type arguments that were not inferred. /// </summary> private ImmutableArray<TypeWithAnnotations> GetInferredTypeArguments(out bool inferredFromFunctionType) { var builder = ArrayBuilder<TypeWithAnnotations>.GetInstance(_fixedResults.Length); inferredFromFunctionType = false; foreach (var fixedResult in _fixedResults) { builder.Add(fixedResult.Type); if (fixedResult.FromFunctionType) { inferredFromFunctionType = true; } } return builder.ToImmutableAndFree(); } private static bool IsReallyAType(TypeSymbol? type) { return type is { } && !type.IsErrorType() && !type.IsVoidType(); } private static void GetAllCandidates(Dictionary<TypeWithAnnotations, TypeWithAnnotations> candidates, ArrayBuilder<TypeWithAnnotations> builder) { builder.AddRange(candidates.Values); } private static void AddAllCandidates( Dictionary<TypeWithAnnotations, TypeWithAnnotations> candidates, HashSet<TypeWithAnnotations> bounds, VarianceKind variance, ConversionsBase conversions) { foreach (var candidate in bounds) { var type = candidate; if (!conversions.IncludeNullability) { // https://github.com/dotnet/roslyn/issues/30534: Should preserve // distinct "not computed" state from initial binding. type = type.SetUnknownNullabilityForReferenceTypes(); } AddOrMergeCandidate(candidates, type, variance, conversions); } } private static void AddOrMergeCandidate( Dictionary<TypeWithAnnotations, TypeWithAnnotations> candidates, TypeWithAnnotations newCandidate, VarianceKind variance, ConversionsBase conversions) { Debug.Assert(conversions.IncludeNullability || newCandidate.SetUnknownNullabilityForReferenceTypes().Equals(newCandidate, TypeCompareKind.ConsiderEverything)); if (candidates.TryGetValue(newCandidate, out TypeWithAnnotations oldCandidate)) { MergeAndReplaceIfStillCandidate(candidates, oldCandidate, newCandidate, variance, conversions); } else { candidates.Add(newCandidate, newCandidate); } } private static void MergeOrRemoveCandidates( Dictionary<TypeWithAnnotations, TypeWithAnnotations> candidates, HashSet<TypeWithAnnotations> bounds, ArrayBuilder<TypeWithAnnotations> initialCandidates, ConversionsBase conversions, VarianceKind variance, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(variance == VarianceKind.In || variance == VarianceKind.Out); // SPEC: For each lower (upper) bound U of Xi all types to which there is not an // SPEC: implicit conversion from (to) U are removed from the candidate set. var comparison = conversions.IncludeNullability ? TypeCompareKind.ConsiderEverything : TypeCompareKind.IgnoreNullableModifiersForReferenceTypes; foreach (var bound in bounds) { foreach (var candidate in initialCandidates) { if (bound.Equals(candidate, comparison)) { continue; } TypeWithAnnotations source; TypeWithAnnotations destination; if (variance == VarianceKind.Out) { source = bound; destination = candidate; } else { source = candidate; destination = bound; } if (!ImplicitConversionExists(source, destination, ref useSiteInfo, conversions.WithNullability(false))) { candidates.Remove(candidate); if (conversions.IncludeNullability && candidates.TryGetValue(bound, out var oldBound)) { // merge the nullability from candidate into bound var oldAnnotation = oldBound.NullableAnnotation; var newAnnotation = oldAnnotation.MergeNullableAnnotation(candidate.NullableAnnotation, variance); if (oldAnnotation != newAnnotation) { var newBound = TypeWithAnnotations.Create(oldBound.Type, newAnnotation); candidates[bound] = newBound; } } } else if (bound.Equals(candidate, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)) { // SPEC: 4.7 The Dynamic Type // Type inference (7.5.2) will prefer dynamic over object if both are candidates. // // This rule doesn't have to be implemented explicitly due to special handling of // conversions from dynamic in ImplicitConversionExists helper. // MergeAndReplaceIfStillCandidate(candidates, candidate, bound, variance, conversions); } } } } private static void MergeAndReplaceIfStillCandidate( Dictionary<TypeWithAnnotations, TypeWithAnnotations> candidates, TypeWithAnnotations oldCandidate, TypeWithAnnotations newCandidate, VarianceKind variance, ConversionsBase conversions) { // We make an exception when new candidate is dynamic, for backwards compatibility if (newCandidate.Type.IsDynamic()) { return; } if (candidates.TryGetValue(oldCandidate, out TypeWithAnnotations latest)) { // Note: we're ignoring the variance used merging previous candidates into `latest`. // If that variance is different than `variance`, we might infer the wrong nullability, but in that case, // we assume we'll report a warning when converting the arguments to the inferred parameter types. // (For instance, with F<T>(T x, T y, IIn<T> z) and interface IIn<in T> and interface IIOut<out T>, the // call F(IOut<object?>, IOut<object!>, IIn<IOut<object!>>) should find a nullability mismatch. Instead, // we'll merge the lower bounds IOut<object?> with IOut<object!> (using VarianceKind.Out) to produce // IOut<object?>, then merge that result with upper bound IOut<object!> (using VarianceKind.In) // to produce IOut<object?>. But then conversion of argument IIn<IOut<object!>> to parameter // IIn<IOut<object?>> will generate a warning at that point.) TypeWithAnnotations merged = latest.MergeEquivalentTypes(newCandidate, variance); candidates[oldCandidate] = merged; } } /// <summary> /// This is a comparer that ignores differences in dynamic-ness and tuple names. /// But it has a special case for top-level object vs. dynamic for purpose of method type inference. /// </summary> private sealed class EqualsIgnoringDynamicTupleNamesAndNullabilityComparer : EqualityComparer<TypeWithAnnotations> { internal static readonly EqualsIgnoringDynamicTupleNamesAndNullabilityComparer Instance = new EqualsIgnoringDynamicTupleNamesAndNullabilityComparer(); public override int GetHashCode(TypeWithAnnotations obj) { return obj.Type.GetHashCode(); } public override bool Equals(TypeWithAnnotations x, TypeWithAnnotations y) { // We do a equality test ignoring dynamic and tuple names differences, // but dynamic and object are not considered equal for backwards compatibility. if (x.Type.IsDynamic() ^ y.Type.IsDynamic()) { return false; } return x.Equals(y, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; /* SPEC: Type inference occurs as part of the compile-time processing of a method invocation and takes place before the overload resolution step of the invocation. When a particular method group is specified in a method invocation, and no type arguments are specified as part of the method invocation, type inference is applied to each generic method in the method group. If type inference succeeds, then the inferred type arguments are used to determine the types of formal parameters for subsequent overload resolution. If overload resolution chooses a generic method as the one to invoke then the inferred type arguments are used as the actual type arguments for the invocation. If type inference for a particular method fails, that method does not participate in overload resolution. The failure of type inference, in and of itself, does not cause a compile-time error. However, it often leads to a compile-time error when overload resolution then fails to find any applicable methods. If the supplied number of arguments is different than the number of parameters in the method, then inference immediately fails. Otherwise, assume that the generic method has the following signature: Tr M<X1...Xn>(T1 x1 ... Tm xm) With a method call of the form M(E1...Em) the task of type inference is to find unique type arguments S1...Sn for each of the type parameters X1...Xn so that the call M<S1...Sn>(E1...Em)becomes valid. During the process of inference each type parameter Xi is either fixed to a particular type Si or unfixed with an associated set of bounds. Each of the bounds is some type T. Each bound is classified as an upper bound, lower bound or exact bound. Initially each type variable Xi is unfixed with an empty set of bounds. */ // This file contains the implementation for method type inference on calls (with // arguments, and method type inference on conversion of method groups to delegate // types (which will not have arguments.) namespace Microsoft.CodeAnalysis.CSharp { internal static class PooledDictionaryIgnoringNullableModifiersForReferenceTypes { private static readonly ObjectPool<PooledDictionary<NamedTypeSymbol, NamedTypeSymbol>> s_poolInstance = PooledDictionary<NamedTypeSymbol, NamedTypeSymbol>.CreatePool(Symbols.SymbolEqualityComparer.IgnoringNullable); internal static PooledDictionary<NamedTypeSymbol, NamedTypeSymbol> GetInstance() { var instance = s_poolInstance.Allocate(); Debug.Assert(instance.Count == 0); return instance; } } // Method type inference can fail, but we still might have some best guesses. internal readonly struct MethodTypeInferenceResult { public readonly ImmutableArray<TypeWithAnnotations> InferredTypeArguments; /// <summary> /// At least one type argument was inferred from a function type. /// </summary> public readonly bool HasTypeArgumentInferredFromFunctionType; public readonly bool Success; public MethodTypeInferenceResult( bool success, ImmutableArray<TypeWithAnnotations> inferredTypeArguments, bool hasTypeArgumentInferredFromFunctionType) { this.Success = success; this.InferredTypeArguments = inferredTypeArguments; this.HasTypeArgumentInferredFromFunctionType = hasTypeArgumentInferredFromFunctionType; } } internal sealed class MethodTypeInferrer { internal abstract class Extensions { internal static readonly Extensions Default = new DefaultExtensions(); internal abstract TypeWithAnnotations GetTypeWithAnnotations(BoundExpression expr); internal abstract TypeWithAnnotations GetMethodGroupResultType(BoundMethodGroup group, MethodSymbol method); private sealed class DefaultExtensions : Extensions { internal override TypeWithAnnotations GetTypeWithAnnotations(BoundExpression expr) { return TypeWithAnnotations.Create(expr.GetTypeOrFunctionType()); } internal override TypeWithAnnotations GetMethodGroupResultType(BoundMethodGroup group, MethodSymbol method) { return method.ReturnTypeWithAnnotations; } } } private enum InferenceResult { InferenceFailed, MadeProgress, NoProgress, Success } private enum Dependency { Unknown = 0x00, NotDependent = 0x01, DependsMask = 0x10, Direct = 0x11, Indirect = 0x12 } private readonly CSharpCompilation _compilation; private readonly ConversionsBase _conversions; private readonly ImmutableArray<TypeParameterSymbol> _methodTypeParameters; private readonly NamedTypeSymbol _constructedContainingTypeOfMethod; private readonly ImmutableArray<TypeWithAnnotations> _formalParameterTypes; private readonly ImmutableArray<RefKind> _formalParameterRefKinds; private readonly ImmutableArray<BoundExpression> _arguments; private readonly Extensions _extensions; private readonly (TypeWithAnnotations Type, bool FromFunctionType)[] _fixedResults; private readonly HashSet<TypeWithAnnotations>[] _exactBounds; private readonly HashSet<TypeWithAnnotations>[] _upperBounds; private readonly HashSet<TypeWithAnnotations>[] _lowerBounds; // https://github.com/dotnet/csharplang/blob/main/proposals/csharp-9.0/nullable-reference-types-specification.md#fixing // If the resulting candidate is a reference type and *all* of the exact bounds or *any* of // the lower bounds are nullable reference types, `null` or `default`, then `?` is added to // the resulting candidate, making it a nullable reference type. // // This set of bounds effectively tracks whether a typeless null expression (i.e. null // literal) was used as an argument to a parameter whose type is one of this method's type // parameters. Because such expressions only occur as by-value inputs, we only need to track // the lower bounds, not the exact or upper bounds. private readonly NullableAnnotation[] _nullableAnnotationLowerBounds; private Dependency[,] _dependencies; // Initialized lazily private bool _dependenciesDirty; /// <summary> /// For error recovery, we allow a mismatch between the number of arguments and parameters /// during type inference. This sometimes enables inferring the type for a lambda parameter. /// </summary> private int NumberArgumentsToProcess => System.Math.Min(_arguments.Length, _formalParameterTypes.Length); public static MethodTypeInferenceResult Infer( Binder binder, ConversionsBase conversions, ImmutableArray<TypeParameterSymbol> methodTypeParameters, // We are attempting to build a map from method type parameters // to inferred type arguments. NamedTypeSymbol constructedContainingTypeOfMethod, ImmutableArray<TypeWithAnnotations> formalParameterTypes, // We have some unusual requirements for the types that flow into the inference engine. // Consider the following inference problems: // // Scenario one: // // class C<T> // { // delegate Y FT<X, Y>(T t, X x); // static void M<U, V>(U u, FT<U, V> f); // ... // C<double>.M(123, (t,x)=>t+x); // // From the first argument we infer that U is int. How now must we make an inference on // the second argument? The *declared* type of the formal is C<T>.FT<U,V>. The // actual type at the time of inference is known to be C<double>.FT<int, something> // where "something" is to be determined by inferring the return type of the // lambda by determine the type of "double + int". // // Therefore when we do type inference, if a formal parameter type is a generic delegate // then *its* formal parameter types must be the formal parameter types of the // *constructed* generic delegate C<double>.FT<...>, not C<T>.FT<...>. // // One would therefore suppose that we'd expect the formal parameter types to here // be passed in with the types constructed with the information known from the // call site, not the declared types. // // Contrast that with this scenario: // // Scenario Two: // // interface I<T> // { // void M<U>(T t, U u); // } // ... // static void Goo<V>(V v, I<V> iv) // { // iv.M(v, ""); // } // // Obviously inference should succeed here; it should infer that U is string. // // But consider what happens during the inference process on the first argument. // The first thing we will do is say "what's the type of the argument? V. What's // the type of the corresponding formal parameter? The first formal parameter of // I<V>.M<whatever> is of type V. The inference engine will then say "V is a // method type parameter, and therefore we have an inference from V to V". // But *V* is not one of the method type parameters being inferred; the only // method type parameter being inferred here is *U*. // // This is perhaps some evidence that the formal parameters passed in should be // the formal parameters of the *declared* method; in this case, (T, U), not // the formal parameters of the *constructed* method, (V, U). // // However, one might make the argument that no, we could just add a check // to ensure that if we see a method type parameter as a formal parameter type, // then we only perform the inference if the method type parameter is a type // parameter of the method for which inference is being performed. // // Unfortunately, that does not work either: // // Scenario three: // // class C<T> // { // static void M<U>(T t, U u) // { // ... // C<U>.M(u, 123); // ... // } // } // // The *original* formal parameter types are (T, U); the *constructed* formal parameter types // are (U, U), but *those are logically two different U's*. The first U is from the outer caller; // the second U is the U of the recursive call. // // That is, suppose someone called C<string>.M<double>(string, double). The recursive call should be to // C<double>.M<int>(double, int). We should absolutely not make an inference on the first argument // from U to U just because C<U>.M<something>'s first formal parameter is of type U. If we did then // inference would fail, because we'd end up with two bounds on 'U' -- 'U' and 'int'. We only want // the latter bound. // // What these three scenarios show is that for a "normal" inference we need to have the // formal parameters of the *original* method definition, but when making an inference from a lambda // to a delegate, we need to have the *constructed* method signature in order that the formal // parameters *of the delegate* be correct. // // How to solve this problem? // // We solve it by passing in the formal parameters in their *original* form, but also getting // the *fully constructed* type that the method call is on. When constructing the fixed // delegate type for inference from a lambda, we do the appropriate type substitution on // the delegate. ImmutableArray<RefKind> formalParameterRefKinds, // Optional; assume all value if missing. ImmutableArray<BoundExpression> arguments,// Required; in scenarios like method group conversions where there are // no arguments per se we cons up some fake arguments. ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, Extensions extensions = null) { Debug.Assert(!methodTypeParameters.IsDefault); Debug.Assert(methodTypeParameters.Length > 0); Debug.Assert(!formalParameterTypes.IsDefault); Debug.Assert(formalParameterRefKinds.IsDefault || formalParameterRefKinds.Length == formalParameterTypes.Length); Debug.Assert(!arguments.IsDefault); // Early out: if the method has no formal parameters then we know that inference will fail. if (formalParameterTypes.Length == 0) { return new MethodTypeInferenceResult(success: false, inferredTypeArguments: default, hasTypeArgumentInferredFromFunctionType: false); // UNDONE: OPTIMIZATION: We could check to see whether there is a type // UNDONE: parameter which is never used in any formal parameter; if // UNDONE: so then we know ahead of time that inference will fail. } var inferrer = new MethodTypeInferrer( binder.Compilation, conversions, methodTypeParameters, constructedContainingTypeOfMethod, formalParameterTypes, formalParameterRefKinds, arguments, extensions); return inferrer.InferTypeArgs(binder, ref useSiteInfo); } //////////////////////////////////////////////////////////////////////////////// // // Fixed, unfixed and bounded type parameters // // SPEC: During the process of inference each type parameter is either fixed to // SPEC: a particular type or unfixed with an associated set of bounds. Each of // SPEC: the bounds is of some type T. Initially each type parameter is unfixed // SPEC: with an empty set of bounds. private MethodTypeInferrer( CSharpCompilation compilation, ConversionsBase conversions, ImmutableArray<TypeParameterSymbol> methodTypeParameters, NamedTypeSymbol constructedContainingTypeOfMethod, ImmutableArray<TypeWithAnnotations> formalParameterTypes, ImmutableArray<RefKind> formalParameterRefKinds, ImmutableArray<BoundExpression> arguments, Extensions extensions) { _compilation = compilation; _conversions = conversions; _methodTypeParameters = methodTypeParameters; _constructedContainingTypeOfMethod = constructedContainingTypeOfMethod; _formalParameterTypes = formalParameterTypes; _formalParameterRefKinds = formalParameterRefKinds; _arguments = arguments; _extensions = extensions ?? Extensions.Default; _fixedResults = new (TypeWithAnnotations, bool)[methodTypeParameters.Length]; _exactBounds = new HashSet<TypeWithAnnotations>[methodTypeParameters.Length]; _upperBounds = new HashSet<TypeWithAnnotations>[methodTypeParameters.Length]; _lowerBounds = new HashSet<TypeWithAnnotations>[methodTypeParameters.Length]; _nullableAnnotationLowerBounds = new NullableAnnotation[methodTypeParameters.Length]; Debug.Assert(_nullableAnnotationLowerBounds.All(annotation => annotation.IsNotAnnotated())); _dependencies = null; _dependenciesDirty = false; } #if DEBUG internal string Dump() { var sb = new System.Text.StringBuilder(); sb.AppendLine("Method type inference internal state"); sb.AppendFormat("Inferring method type parameters <{0}>\n", string.Join(", ", _methodTypeParameters)); sb.Append("Formal parameter types ("); for (int i = 0; i < _formalParameterTypes.Length; ++i) { if (i != 0) { sb.Append(", "); } sb.Append(GetRefKind(i).ToParameterPrefix()); sb.Append(_formalParameterTypes[i]); } sb.Append("\n"); sb.AppendFormat("Argument types ({0})\n", string.Join(", ", from a in _arguments select a.Type)); if (_dependencies == null) { sb.AppendLine("Dependencies are not yet calculated"); } else { sb.AppendFormat("Dependencies are {0}\n", _dependenciesDirty ? "out of date" : "up to date"); sb.AppendLine("dependency matrix (Not dependent / Direct / Indirect / Unknown):"); for (int i = 0; i < _methodTypeParameters.Length; ++i) { for (int j = 0; j < _methodTypeParameters.Length; ++j) { switch (_dependencies[i, j]) { case Dependency.NotDependent: sb.Append("N"); break; case Dependency.Direct: sb.Append("D"); break; case Dependency.Indirect: sb.Append("I"); break; case Dependency.Unknown: sb.Append("U"); break; } } sb.AppendLine(); } } for (int i = 0; i < _methodTypeParameters.Length; ++i) { sb.AppendFormat("Method type parameter {0}: ", _methodTypeParameters[i].Name); var fixedType = _fixedResults[i].Type; if (!fixedType.HasType) { sb.Append("UNFIXED "); } else { sb.AppendFormat("FIXED to {0} ", fixedType); } sb.AppendFormat("upper bounds: ({0}) ", (_upperBounds[i] == null) ? "" : string.Join(", ", _upperBounds[i])); sb.AppendFormat("lower bounds: ({0}) ", (_lowerBounds[i] == null) ? "" : string.Join(", ", _lowerBounds[i])); sb.AppendFormat("exact bounds: ({0}) ", (_exactBounds[i] == null) ? "" : string.Join(", ", _exactBounds[i])); sb.AppendLine(); } return sb.ToString(); } #endif private RefKind GetRefKind(int index) { Debug.Assert(0 <= index && index < _formalParameterTypes.Length); return _formalParameterRefKinds.IsDefault ? RefKind.None : _formalParameterRefKinds[index]; } private ImmutableArray<TypeWithAnnotations> GetResults(out bool inferredFromFunctionType) { // Anything we didn't infer a type for, give the error type. // Note: the error type will have the same name as the name // of the type parameter we were trying to infer. This will give a // nice user experience where by we will show something like // the following: // // user types: customers.Select( // we show : IE<TResult> IE<Customer>.Select<Customer,TResult>(Func<Customer,TResult> selector) // // Initially we thought we'd just show ?. i.e.: // // IE<?> IE<Customer>.Select<Customer,?>(Func<Customer,?> selector) // // This is nice and concise. However, it falls down if there are multiple // type params that we have left. for (int i = 0; i < _methodTypeParameters.Length; i++) { var fixedResultType = _fixedResults[i].Type; if (fixedResultType.HasType) { if (!fixedResultType.Type.IsErrorType()) { if (_conversions.IncludeNullability && _nullableAnnotationLowerBounds[i].IsAnnotated()) { _fixedResults[i] = _fixedResults[i] with { Type = fixedResultType.AsAnnotated() }; } continue; } var errorTypeName = fixedResultType.Type.Name; if (errorTypeName != null) { continue; } } _fixedResults[i] = (TypeWithAnnotations.Create(new ExtendedErrorTypeSymbol(_constructedContainingTypeOfMethod, _methodTypeParameters[i].Name, 0, null, false)), false); } return GetInferredTypeArguments(out inferredFromFunctionType); } private bool ValidIndex(int index) { return 0 <= index && index < _methodTypeParameters.Length; } private bool IsUnfixed(int methodTypeParameterIndex) { Debug.Assert(ValidIndex(methodTypeParameterIndex)); return !_fixedResults[methodTypeParameterIndex].Type.HasType; } private bool IsUnfixedTypeParameter(TypeWithAnnotations type) { Debug.Assert(type.HasType); if (type.TypeKind != TypeKind.TypeParameter) return false; TypeParameterSymbol typeParameter = (TypeParameterSymbol)type.Type; int ordinal = typeParameter.Ordinal; return ValidIndex(ordinal) && TypeSymbol.Equals(typeParameter, _methodTypeParameters[ordinal], TypeCompareKind.ConsiderEverything2) && IsUnfixed(ordinal); } private bool AllFixed() { for (int methodTypeParameterIndex = 0; methodTypeParameterIndex < _methodTypeParameters.Length; ++methodTypeParameterIndex) { if (IsUnfixed(methodTypeParameterIndex)) { return false; } } return true; } private void AddBound(TypeWithAnnotations addedBound, HashSet<TypeWithAnnotations>[] collectedBounds, TypeWithAnnotations methodTypeParameterWithAnnotations) { Debug.Assert(IsUnfixedTypeParameter(methodTypeParameterWithAnnotations)); var methodTypeParameter = (TypeParameterSymbol)methodTypeParameterWithAnnotations.Type; int methodTypeParameterIndex = methodTypeParameter.Ordinal; if (collectedBounds[methodTypeParameterIndex] == null) { collectedBounds[methodTypeParameterIndex] = new HashSet<TypeWithAnnotations>(TypeWithAnnotations.EqualsComparer.ConsiderEverythingComparer); } collectedBounds[methodTypeParameterIndex].Add(addedBound); } private bool HasBound(int methodTypeParameterIndex) { Debug.Assert(ValidIndex(methodTypeParameterIndex)); return _lowerBounds[methodTypeParameterIndex] != null || _upperBounds[methodTypeParameterIndex] != null || _exactBounds[methodTypeParameterIndex] != null; } private TypeSymbol GetFixedDelegateOrFunctionPointer(TypeSymbol delegateOrFunctionPointerType) { Debug.Assert((object)delegateOrFunctionPointerType != null); Debug.Assert(delegateOrFunctionPointerType.IsDelegateType() || delegateOrFunctionPointerType is FunctionPointerTypeSymbol); // We have a delegate where the input types use no unfixed parameters. Create // a substitution context; we can substitute unfixed parameters for themselves // since they don't actually occur in the inputs. (They may occur in the outputs, // or there may be input parameters fixed to _unfixed_ method type variables. // Both of those scenarios are legal.) var fixedArguments = _methodTypeParameters.SelectAsArray( static (typeParameter, i, self) => self.IsUnfixed(i) ? TypeWithAnnotations.Create(typeParameter) : self._fixedResults[i].Type, this); TypeMap typeMap = new TypeMap(_constructedContainingTypeOfMethod, _methodTypeParameters, fixedArguments); return typeMap.SubstituteType(delegateOrFunctionPointerType).Type; } //////////////////////////////////////////////////////////////////////////////// // // Phases // private MethodTypeInferenceResult InferTypeArgs(Binder binder, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: Type inference takes place in phases. Each phase will try to infer type // SPEC: arguments for more type parameters based on the findings of the previous // SPEC: phase. The first phase makes some initial inferences of bounds, whereas // SPEC: the second phase fixes type parameters to specific types and infers further // SPEC: bounds. The second phase may have to be repeated a number of times. InferTypeArgsFirstPhase(ref useSiteInfo); bool success = InferTypeArgsSecondPhase(binder, ref useSiteInfo); var inferredTypeArguments = GetResults(out bool inferredFromFunctionType); return new MethodTypeInferenceResult(success, inferredTypeArguments, inferredFromFunctionType); } //////////////////////////////////////////////////////////////////////////////// // // The first phase // private void InferTypeArgsFirstPhase(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(!_formalParameterTypes.IsDefault); Debug.Assert(!_arguments.IsDefault); // We expect that we have been handed a list of arguments and a list of the // formal parameter types they correspond to; all the details about named and // optional parameters have already been dealt with. // SPEC: For each of the method arguments Ei: for (int arg = 0, length = this.NumberArgumentsToProcess; arg < length; arg++) { BoundExpression argument = _arguments[arg]; TypeWithAnnotations target = _formalParameterTypes[arg]; ExactOrBoundsKind kind = GetRefKind(arg).IsManagedReference() || target.Type.IsPointerType() ? ExactOrBoundsKind.Exact : ExactOrBoundsKind.LowerBound; MakeExplicitParameterTypeInferences(argument, target, kind, ref useSiteInfo); } } private void MakeExplicitParameterTypeInferences(BoundExpression argument, TypeWithAnnotations target, ExactOrBoundsKind kind, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: * If Ei is an anonymous function, and Ti is a delegate type or expression tree type, // SPEC: an explicit type parameter inference is made from Ei to Ti and // SPEC: an explicit return type inference is made from Ei to Ti. // (We cannot make an output type inference from a method group // at this time because we have no fixed types yet to use for // overload resolution.) // SPEC: * Otherwise, if Ei has a type U then a lower-bound inference // SPEC: or exact inference is made from U to Ti. // SPEC: * Otherwise, no inference is made for this argument if (argument.Kind == BoundKind.UnboundLambda && target.Type.GetDelegateType() is { }) { ExplicitParameterTypeInference(argument, target, ref useSiteInfo); ExplicitReturnTypeInference(argument, target, ref useSiteInfo); } else if (argument.Kind != BoundKind.TupleLiteral || !MakeExplicitParameterTypeInferences((BoundTupleLiteral)argument, target, kind, ref useSiteInfo)) { // Either the argument is not a tuple literal, or we were unable to do the inference from its elements, let's try to infer from argument type var argumentType = _extensions.GetTypeWithAnnotations(argument); if (IsReallyAType(argumentType.Type)) { ExactOrBoundsInference(kind, argumentType, target, ref useSiteInfo); } else if (IsUnfixedTypeParameter(target) && kind is ExactOrBoundsKind.LowerBound) { var ordinal = ((TypeParameterSymbol)target.Type).Ordinal; _nullableAnnotationLowerBounds[ordinal] = _nullableAnnotationLowerBounds[ordinal].Join(argumentType.NullableAnnotation); } } } private bool MakeExplicitParameterTypeInferences(BoundTupleLiteral argument, TypeWithAnnotations target, ExactOrBoundsKind kind, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // try match up element-wise to the destination tuple (or underlying type) // Example: // if "(a: 1, b: "qq")" is passed as (T, U) arg // then T becomes int and U becomes string if (target.Type.Kind != SymbolKind.NamedType) { // tuples can only match to tuples or tuple underlying types. return false; } var destination = (NamedTypeSymbol)target.Type; var sourceArguments = argument.Arguments; // check if the type is actually compatible type for a tuple of given cardinality if (!destination.IsTupleTypeOfCardinality(sourceArguments.Length)) { // target is not a tuple of appropriate shape return false; } var destTypes = destination.TupleElementTypesWithAnnotations; Debug.Assert(sourceArguments.Length == destTypes.Length); // NOTE: we are losing tuple element names when recursing into argument expressions. // that is ok, because we are inferring type parameters used in the matching elements, // This is not the situation where entire tuple literal is used to infer a single type param for (int i = 0; i < sourceArguments.Length; i++) { var sourceArgument = sourceArguments[i]; var destType = destTypes[i]; MakeExplicitParameterTypeInferences(sourceArgument, destType, kind, ref useSiteInfo); } return true; } //////////////////////////////////////////////////////////////////////////////// // // The second phase // private bool InferTypeArgsSecondPhase(Binder binder, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: The second phase proceeds as follows: // SPEC: * If no unfixed type parameters exist then type inference succeeds. // SPEC: * Otherwise, if there exists one or more arguments Ei with corresponding // SPEC: parameter type Ti such that: // SPEC: o the output type of Ei with type Ti contains at least one unfixed // SPEC: type parameter Xj, and // SPEC: o none of the input types of Ei with type Ti contains any unfixed // SPEC: type parameter Xj, // SPEC: then an output type inference is made from all such Ei to Ti. // SPEC: * Whether or not the previous step actually made an inference, we must // SPEC: now fix at least one type parameter, as follows: // SPEC: * If there exists one or more type parameters Xi such that // SPEC: o Xi is unfixed, and // SPEC: o Xi has a non-empty set of bounds, and // SPEC: o Xi does not depend on any Xj // SPEC: then each such Xi is fixed. If any fixing operation fails then type // SPEC: inference fails. // SPEC: * Otherwise, if there exists one or more type parameters Xi such that // SPEC: o Xi is unfixed, and // SPEC: o Xi has a non-empty set of bounds, and // SPEC: o there is at least one type parameter Xj that depends on Xi // SPEC: then each such Xi is fixed. If any fixing operation fails then // SPEC: type inference fails. // SPEC: * Otherwise, we are unable to make progress and there are unfixed parameters. // SPEC: Type inference fails. // SPEC: * If type inference neither succeeds nor fails then the second phase is // SPEC: repeated until type inference succeeds or fails. (Since each repetition of // SPEC: the second phase either succeeds, fails or fixes an unfixed type parameter, // SPEC: the algorithm must terminate with no more repetitions than the number // SPEC: of type parameters. InitializeDependencies(); while (true) { var res = DoSecondPhase(binder, ref useSiteInfo); Debug.Assert(res != InferenceResult.NoProgress); if (res == InferenceResult.InferenceFailed) { return false; } if (res == InferenceResult.Success) { return true; } // Otherwise, we made some progress last time; do it again. } } private InferenceResult DoSecondPhase(Binder binder, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: * If no unfixed type parameters exist then type inference succeeds. if (AllFixed()) { return InferenceResult.Success; } // SPEC: * Otherwise, if there exists one or more arguments Ei with // SPEC: corresponding parameter type Ti such that: // SPEC: o the output type of Ei with type Ti contains at least one unfixed // SPEC: type parameter Xj, and // SPEC: o none of the input types of Ei with type Ti contains any unfixed // SPEC: type parameter Xj, // SPEC: then an output type inference is made from all such Ei to Ti. MakeOutputTypeInferences(binder, ref useSiteInfo); // SPEC: * Whether or not the previous step actually made an inference, we // SPEC: must now fix at least one type parameter, as follows: // SPEC: * If there exists one or more type parameters Xi such that // SPEC: o Xi is unfixed, and // SPEC: o Xi has a non-empty set of bounds, and // SPEC: o Xi does not depend on any Xj // SPEC: then each such Xi is fixed. If any fixing operation fails then // SPEC: type inference fails. InferenceResult res; res = FixNondependentParameters(ref useSiteInfo); if (res != InferenceResult.NoProgress) { return res; } // SPEC: * Otherwise, if there exists one or more type parameters Xi such that // SPEC: o Xi is unfixed, and // SPEC: o Xi has a non-empty set of bounds, and // SPEC: o there is at least one type parameter Xj that depends on Xi // SPEC: then each such Xi is fixed. If any fixing operation fails then // SPEC: type inference fails. res = FixDependentParameters(ref useSiteInfo); if (res != InferenceResult.NoProgress) { return res; } // SPEC: * Otherwise, we are unable to make progress and there are // SPEC: unfixed parameters. Type inference fails. return InferenceResult.InferenceFailed; } private void MakeOutputTypeInferences(Binder binder, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: Otherwise, for all arguments Ei with corresponding parameter type Ti // SPEC: where the output types contain unfixed type parameters but the input // SPEC: types do not, an output type inference is made from Ei to Ti. for (int arg = 0, length = this.NumberArgumentsToProcess; arg < length; arg++) { var formalType = _formalParameterTypes[arg]; var argument = _arguments[arg]; MakeOutputTypeInferences(binder, argument, formalType, ref useSiteInfo); } } private void MakeOutputTypeInferences(Binder binder, BoundExpression argument, TypeWithAnnotations formalType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (argument.Kind == BoundKind.TupleLiteral && (object)argument.Type == null) { MakeOutputTypeInferences(binder, (BoundTupleLiteral)argument, formalType, ref useSiteInfo); } else { if (HasUnfixedParamInOutputType(argument, formalType.Type) && !HasUnfixedParamInInputType(argument, formalType.Type)) { //UNDONE: if (argument->isTYPEORNAMESPACEERROR() && argumentType->IsErrorType()) //UNDONE: { //UNDONE: argumentType = GetTypeManager().GetErrorSym(); //UNDONE: } OutputTypeInference(binder, argument, formalType, ref useSiteInfo); } } } private void MakeOutputTypeInferences(Binder binder, BoundTupleLiteral argument, TypeWithAnnotations formalType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (formalType.Type.Kind != SymbolKind.NamedType) { // tuples can only match to tuples or tuple underlying types. return; } var destination = (NamedTypeSymbol)formalType.Type; Debug.Assert((object)argument.Type == null, "should not need to dig into elements if tuple has natural type"); var sourceArguments = argument.Arguments; // check if the type is actually compatible type for a tuple of given cardinality if (!destination.IsTupleTypeOfCardinality(sourceArguments.Length)) { return; } var destTypes = destination.TupleElementTypesWithAnnotations; Debug.Assert(sourceArguments.Length == destTypes.Length); for (int i = 0; i < sourceArguments.Length; i++) { var sourceArgument = sourceArguments[i]; var destType = destTypes[i]; MakeOutputTypeInferences(binder, sourceArgument, destType, ref useSiteInfo); } } private InferenceResult FixNondependentParameters(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: * Otherwise, if there exists one or more type parameters Xi such that // SPEC: o Xi is unfixed, and // SPEC: o Xi has a non-empty set of bounds, and // SPEC: o Xi does not depend on any Xj // SPEC: then each such Xi is fixed. return FixParameters((inferrer, index) => !inferrer.DependsOnAny(index), ref useSiteInfo); } private InferenceResult FixDependentParameters(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: * All unfixed type parameters Xi are fixed for which all of the following hold: // SPEC: * There is at least one type parameter Xj that depends on Xi. // SPEC: * Xi has a non-empty set of bounds. return FixParameters((inferrer, index) => inferrer.AnyDependsOn(index), ref useSiteInfo); } private InferenceResult FixParameters( Func<MethodTypeInferrer, int, bool> predicate, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // Dependency is only defined for unfixed parameters. Therefore, fixing // a parameter may cause all of its dependencies to become no longer // dependent on anything. We need to first determine which parameters need to be // fixed, and then fix them all at once. var needsFixing = new bool[_methodTypeParameters.Length]; var result = InferenceResult.NoProgress; for (int param = 0; param < _methodTypeParameters.Length; param++) { if (IsUnfixed(param) && HasBound(param) && predicate(this, param)) { needsFixing[param] = true; result = InferenceResult.MadeProgress; } } for (int param = 0; param < _methodTypeParameters.Length; param++) { // Fix as much as you can, even if there are errors. That will // help with intellisense. if (needsFixing[param]) { if (!Fix(param, ref useSiteInfo)) { result = InferenceResult.InferenceFailed; } } } return result; } //////////////////////////////////////////////////////////////////////////////// // // Input types // private static bool DoesInputTypeContain(BoundExpression argument, TypeSymbol formalParameterType, TypeParameterSymbol typeParameter) { // SPEC: If E is a method group or an anonymous function and T is a delegate // SPEC: type or expression tree type then all the parameter types of T are // SPEC: input types of E with type T. var delegateOrFunctionPointerType = formalParameterType.GetDelegateOrFunctionPointerType(); if ((object)delegateOrFunctionPointerType == null) { return false; // No input types. } var isFunctionPointer = delegateOrFunctionPointerType.IsFunctionPointer(); if ((isFunctionPointer && argument.Kind != BoundKind.UnconvertedAddressOfOperator) || (!isFunctionPointer && argument.Kind is not (BoundKind.UnboundLambda or BoundKind.MethodGroup))) { return false; // No input types. } var parameters = delegateOrFunctionPointerType.DelegateOrFunctionPointerParameters(); if (parameters.IsDefaultOrEmpty) { return false; } foreach (var parameter in parameters) { if (parameter.Type.ContainsTypeParameter(typeParameter)) { return true; } } return false; } private bool HasUnfixedParamInInputType(BoundExpression pSource, TypeSymbol pDest) { for (int iParam = 0; iParam < _methodTypeParameters.Length; iParam++) { if (IsUnfixed(iParam)) { if (DoesInputTypeContain(pSource, pDest, _methodTypeParameters[iParam])) { return true; } } } return false; } //////////////////////////////////////////////////////////////////////////////// // // Output types // private static bool DoesOutputTypeContain(BoundExpression argument, TypeSymbol formalParameterType, TypeParameterSymbol typeParameter) { // SPEC: If E is a method group or an anonymous function and T is a delegate // SPEC: type or expression tree type then the return type of T is an output type // SPEC: of E with type T. var delegateOrFunctionPointerType = formalParameterType.GetDelegateOrFunctionPointerType(); if ((object)delegateOrFunctionPointerType == null) { return false; } var isFunctionPointer = delegateOrFunctionPointerType.IsFunctionPointer(); if ((isFunctionPointer && argument.Kind != BoundKind.UnconvertedAddressOfOperator) || (!isFunctionPointer && argument.Kind is not (BoundKind.UnboundLambda or BoundKind.MethodGroup))) { return false; } MethodSymbol method = delegateOrFunctionPointerType switch { NamedTypeSymbol n => n.DelegateInvokeMethod, FunctionPointerTypeSymbol f => f.Signature, _ => throw ExceptionUtilities.UnexpectedValue(delegateOrFunctionPointerType) }; if ((object)method == null || method.HasUseSiteError) { return false; } var returnType = method.ReturnType; if ((object)returnType == null) { return false; } return returnType.ContainsTypeParameter(typeParameter); } private bool HasUnfixedParamInOutputType(BoundExpression argument, TypeSymbol formalParameterType) { for (int iParam = 0; iParam < _methodTypeParameters.Length; iParam++) { if (IsUnfixed(iParam)) { if (DoesOutputTypeContain(argument, formalParameterType, _methodTypeParameters[iParam])) { return true; } } } return false; } //////////////////////////////////////////////////////////////////////////////// // // Dependence // private bool DependsDirectlyOn(int iParam, int jParam) { Debug.Assert(ValidIndex(iParam)); Debug.Assert(ValidIndex(jParam)); // SPEC: An unfixed type parameter Xi depends directly on an unfixed type // SPEC: parameter Xj if for some argument Ek with type Tk, Xj occurs // SPEC: in an input type of Ek and Xi occurs in an output type of Ek // SPEC: with type Tk. // We compute and record the Depends Directly On relationship once, in // InitializeDependencies, below. // At this point, everything should be unfixed. Debug.Assert(IsUnfixed(iParam)); Debug.Assert(IsUnfixed(jParam)); for (int iArg = 0, length = this.NumberArgumentsToProcess; iArg < length; iArg++) { var formalParameterType = _formalParameterTypes[iArg].Type; var argument = _arguments[iArg]; if (DoesInputTypeContain(argument, formalParameterType, _methodTypeParameters[jParam]) && DoesOutputTypeContain(argument, formalParameterType, _methodTypeParameters[iParam])) { return true; } } return false; } private void InitializeDependencies() { // We track dependencies by a two-d square array that gives the known // relationship between every pair of type parameters. The relationship // is one of: // // * Unknown relationship // * known to be not dependent // * known to depend directly // * known to depend indirectly // // Since dependency is only defined on unfixed type parameters, fixing a type // parameter causes all dependencies involving that parameter to go to // the "known to be not dependent" state. Since dependency is a transitive property, // this means that doing so may require recalculating the indirect dependencies // from the now possibly smaller set of dependencies. // // Therefore, when we detect that the dependency state has possibly changed // due to fixing, we change all "depends indirectly" back into "unknown" and // recalculate from the remaining "depends directly". // // This algorithm thereby yields an extremely bad (but extremely unlikely) worst // case for asymptotic performance. Suppose there are n type parameters. // "DependsTransitivelyOn" below costs O(n) because it must potentially check // all n type parameters to see if there is any k such that Xj => Xk => Xi. // "DeduceDependencies" calls "DependsTransitivelyOn" for each "Unknown" // pair, and there could be O(n^2) such pairs, so DependsTransitivelyOn is // worst-case O(n^3). And we could have to recalculate the dependency graph // after each type parameter is fixed in turn, so that would be O(n) calls to // DependsTransitivelyOn, giving this algorithm a worst case of O(n^4). // // Of course, in reality, n is going to almost always be on the order of // "smaller than 5", and there will not be O(n^2) dependency relationships // between type parameters; it is far more likely that the transitivity chains // will be very short and not branch or loop at all. This is much more likely to // be an O(n^2) algorithm in practice. Debug.Assert(_dependencies == null); _dependencies = new Dependency[_methodTypeParameters.Length, _methodTypeParameters.Length]; int iParam; int jParam; Debug.Assert(0 == (int)Dependency.Unknown); for (iParam = 0; iParam < _methodTypeParameters.Length; ++iParam) { for (jParam = 0; jParam < _methodTypeParameters.Length; ++jParam) { if (DependsDirectlyOn(iParam, jParam)) { _dependencies[iParam, jParam] = Dependency.Direct; } } } DeduceAllDependencies(); } private bool DependsOn(int iParam, int jParam) { Debug.Assert(_dependencies != null); // SPEC: Xj depends on Xi if Xj depends directly on Xi, or if Xi depends // SPEC: directly on Xk and Xk depends on Xj. Thus "depends on" is the // SPEC: transitive but not reflexive closure of "depends directly on". Debug.Assert(0 <= iParam && iParam < _methodTypeParameters.Length); Debug.Assert(0 <= jParam && jParam < _methodTypeParameters.Length); if (_dependenciesDirty) { SetIndirectsToUnknown(); DeduceAllDependencies(); } return 0 != ((_dependencies[iParam, jParam]) & Dependency.DependsMask); } private bool DependsTransitivelyOn(int iParam, int jParam) { Debug.Assert(_dependencies != null); Debug.Assert(ValidIndex(iParam)); Debug.Assert(ValidIndex(jParam)); // Can we find Xk such that Xi depends on Xk and Xk depends on Xj? // If so, then Xi depends indirectly on Xj. (Note that there is // a minor optimization here -- the spec comment above notes that // we want Xi to depend DIRECTLY on Xk, and Xk to depend directly // or indirectly on Xj. But if we already know that Xi depends // directly OR indirectly on Xk and Xk depends on Xj, then that's // good enough.) for (int kParam = 0; kParam < _methodTypeParameters.Length; ++kParam) { if (((_dependencies[iParam, kParam]) & Dependency.DependsMask) != 0 && ((_dependencies[kParam, jParam]) & Dependency.DependsMask) != 0) { return true; } } return false; } private void DeduceAllDependencies() { bool madeProgress; do { madeProgress = DeduceDependencies(); } while (madeProgress); SetUnknownsToNotDependent(); _dependenciesDirty = false; } private bool DeduceDependencies() { Debug.Assert(_dependencies != null); bool madeProgress = false; for (int iParam = 0; iParam < _methodTypeParameters.Length; ++iParam) { for (int jParam = 0; jParam < _methodTypeParameters.Length; ++jParam) { if (_dependencies[iParam, jParam] == Dependency.Unknown) { if (DependsTransitivelyOn(iParam, jParam)) { _dependencies[iParam, jParam] = Dependency.Indirect; madeProgress = true; } } } } return madeProgress; } private void SetUnknownsToNotDependent() { Debug.Assert(_dependencies != null); for (int iParam = 0; iParam < _methodTypeParameters.Length; ++iParam) { for (int jParam = 0; jParam < _methodTypeParameters.Length; ++jParam) { if (_dependencies[iParam, jParam] == Dependency.Unknown) { _dependencies[iParam, jParam] = Dependency.NotDependent; } } } } private void SetIndirectsToUnknown() { Debug.Assert(_dependencies != null); for (int iParam = 0; iParam < _methodTypeParameters.Length; ++iParam) { for (int jParam = 0; jParam < _methodTypeParameters.Length; ++jParam) { if (_dependencies[iParam, jParam] == Dependency.Indirect) { _dependencies[iParam, jParam] = Dependency.Unknown; } } } } //////////////////////////////////////////////////////////////////////////////// // A fixed parameter never depends on anything, nor is depended upon by anything. private void UpdateDependenciesAfterFix(int iParam) { Debug.Assert(ValidIndex(iParam)); if (_dependencies == null) { return; } for (int jParam = 0; jParam < _methodTypeParameters.Length; ++jParam) { _dependencies[iParam, jParam] = Dependency.NotDependent; _dependencies[jParam, iParam] = Dependency.NotDependent; } _dependenciesDirty = true; } private bool DependsOnAny(int iParam) { Debug.Assert(ValidIndex(iParam)); for (int jParam = 0; jParam < _methodTypeParameters.Length; ++jParam) { if (DependsOn(iParam, jParam)) { return true; } } return false; } private bool AnyDependsOn(int iParam) { Debug.Assert(ValidIndex(iParam)); for (int jParam = 0; jParam < _methodTypeParameters.Length; ++jParam) { if (DependsOn(jParam, iParam)) { return true; } } return false; } //////////////////////////////////////////////////////////////////////////////// // // Output type inferences // //////////////////////////////////////////////////////////////////////////////// private void OutputTypeInference(Binder binder, BoundExpression expression, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(expression != null); Debug.Assert(target.HasType); // SPEC: An output type inference is made from an expression E to a type T // SPEC: in the following way: // SPEC: * If E is an anonymous function with inferred return type U and // SPEC: T is a delegate type or expression tree with return type Tb // SPEC: then a lower bound inference is made from U to Tb. if (InferredReturnTypeInference(expression, target, ref useSiteInfo)) { return; } // SPEC: * Otherwise, if E is a method group and T is a delegate type or // SPEC: expression tree type with parameter types T1...Tk and return // SPEC: type Tb and overload resolution of E with the types T1...Tk // SPEC: yields a single method with return type U then a lower-bound // SPEC: inference is made from U to Tb. if (MethodGroupReturnTypeInference(binder, expression, target.Type, ref useSiteInfo)) { return; } // SPEC: * Otherwise, if E is an expression with type U then a lower-bound // SPEC: inference is made from U to T. var sourceType = _extensions.GetTypeWithAnnotations(expression); if (sourceType.HasType) { LowerBoundInference(sourceType, target, ref useSiteInfo); } // SPEC: * Otherwise, no inferences are made. } private bool InferredReturnTypeInference(BoundExpression source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source != null); Debug.Assert(target.HasType); // SPEC: * If E is an anonymous function with inferred return type U and // SPEC: T is a delegate type or expression tree with return type Tb // SPEC: then a lower bound inference is made from U to Tb. var delegateType = target.Type.GetDelegateType(); if ((object)delegateType == null) { return false; } // cannot be hit, because an invalid delegate does not have an unfixed return type // this will be checked earlier. Debug.Assert((object)delegateType.DelegateInvokeMethod != null && !delegateType.DelegateInvokeMethod.HasUseSiteError, "This method should only be called for valid delegate types."); var returnType = delegateType.DelegateInvokeMethod.ReturnTypeWithAnnotations; if (!returnType.HasType || returnType.SpecialType == SpecialType.System_Void) { return false; } var inferredReturnType = InferReturnType(source, delegateType, ref useSiteInfo); if (!inferredReturnType.HasType) { return false; } LowerBoundInference(inferredReturnType, returnType, ref useSiteInfo); return true; } private bool MethodGroupReturnTypeInference(Binder binder, BoundExpression source, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source != null); Debug.Assert((object)target != null); // SPEC: * Otherwise, if E is a method group and T is a delegate type or // SPEC: expression tree type with parameter types T1...Tk and return // SPEC: type Tb and overload resolution of E with the types T1...Tk // SPEC: yields a single method with return type U then a lower-bound // SPEC: inference is made from U to Tb. if (source.Kind is not (BoundKind.MethodGroup or BoundKind.UnconvertedAddressOfOperator)) { return false; } var delegateOrFunctionPointerType = target.GetDelegateOrFunctionPointerType(); if ((object)delegateOrFunctionPointerType == null) { return false; } if (delegateOrFunctionPointerType.IsFunctionPointer() != (source.Kind == BoundKind.UnconvertedAddressOfOperator)) { return false; } // this part of the code is only called if the targetType has an unfixed type argument in the output // type, which is not the case for invalid delegate invoke methods. var (method, isFunctionPointerResolution) = delegateOrFunctionPointerType switch { NamedTypeSymbol n => (n.DelegateInvokeMethod, false), FunctionPointerTypeSymbol f => (f.Signature, true), _ => throw ExceptionUtilities.UnexpectedValue(delegateOrFunctionPointerType), }; Debug.Assert(method is { HasUseSiteError: false }, "This method should only be called for valid delegate or function pointer types"); TypeWithAnnotations sourceReturnType = method.ReturnTypeWithAnnotations; if (!sourceReturnType.HasType || sourceReturnType.SpecialType == SpecialType.System_Void) { return false; } // At this point we are in the second phase; we know that all the input types are fixed. var fixedParameters = GetFixedDelegateOrFunctionPointer(delegateOrFunctionPointerType).DelegateOrFunctionPointerParameters(); if (fixedParameters.IsDefault) { return false; } CallingConventionInfo callingConventionInfo = isFunctionPointerResolution ? new CallingConventionInfo(method.CallingConvention, ((FunctionPointerMethodSymbol)method).GetCallingConventionModifiers()) : default; BoundMethodGroup originalMethodGroup = source as BoundMethodGroup ?? ((BoundUnconvertedAddressOfOperator)source).Operand; var returnType = MethodGroupReturnType(binder, originalMethodGroup, fixedParameters, method.RefKind, isFunctionPointerResolution, ref useSiteInfo, in callingConventionInfo); if (returnType.IsDefault || returnType.IsVoidType()) { return false; } LowerBoundInference(returnType, sourceReturnType, ref useSiteInfo); return true; } private TypeWithAnnotations MethodGroupReturnType( Binder binder, BoundMethodGroup source, ImmutableArray<ParameterSymbol> delegateParameters, RefKind delegateRefKind, bool isFunctionPointerResolution, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, in CallingConventionInfo callingConventionInfo) { var analyzedArguments = AnalyzedArguments.GetInstance(); Conversions.GetDelegateOrFunctionPointerArguments(source.Syntax, analyzedArguments, delegateParameters, binder.Compilation); var resolution = binder.ResolveMethodGroup(source, analyzedArguments, useSiteInfo: ref useSiteInfo, isMethodGroupConversion: true, returnRefKind: delegateRefKind, // Since we are trying to infer the return type, it is not an input to resolving the method group returnType: null, isFunctionPointerResolution: isFunctionPointerResolution, callingConventionInfo: in callingConventionInfo); TypeWithAnnotations type = default; // The resolution could be empty (e.g. if there are no methods in the BoundMethodGroup). if (!resolution.IsEmpty) { var result = resolution.OverloadResolutionResult; if (result.Succeeded) { type = _extensions.GetMethodGroupResultType(source, result.BestResult.Member); } } analyzedArguments.Free(); resolution.Free(); return type; } #nullable enable //////////////////////////////////////////////////////////////////////////////// // // Explicit parameter type inferences // private void ExplicitParameterTypeInference(BoundExpression source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source != null); Debug.Assert(target.HasType); // SPEC: An explicit type parameter type inference is made from an expression // SPEC: E to a type T in the following way. // SPEC: If E is an explicitly typed anonymous function with parameter types // SPEC: U1...Uk and T is a delegate type or expression tree type with // SPEC: parameter types V1...Vk then for each Ui an exact inference is made // SPEC: from Ui to the corresponding Vi. if (source.Kind != BoundKind.UnboundLambda) { return; } UnboundLambda anonymousFunction = (UnboundLambda)source; if (!anonymousFunction.HasExplicitlyTypedParameterList) { return; } var delegateType = target.Type.GetDelegateType(); if (delegateType is null) { return; } var delegateParameters = delegateType.DelegateParameters(); if (delegateParameters.IsDefault) { return; } int size = delegateParameters.Length; if (anonymousFunction.ParameterCount < size) { size = anonymousFunction.ParameterCount; } // SPEC ISSUE: What should we do if there is an out/ref mismatch between an // SPEC ISSUE: anonymous function parameter and a delegate parameter? // SPEC ISSUE: The result will not be applicable no matter what, but should // SPEC ISSUE: we make any inferences? This is going to be an error // SPEC ISSUE: ultimately, but it might make a difference for intellisense or // SPEC ISSUE: other analysis. for (int i = 0; i < size; ++i) { ExactInference(anonymousFunction.ParameterTypeWithAnnotations(i), delegateParameters[i].TypeWithAnnotations, ref useSiteInfo); } } private void ExplicitReturnTypeInference(BoundExpression source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source != null); Debug.Assert(target.HasType); // SPEC: An explicit type return type inference is made from an expression // SPEC: E to a type T in the following way. // SPEC: If E is an anonymous function with explicit return type Ur and // SPEC: T is a delegate type or expression tree type with return type Vr then // SPEC: an exact inference is made from Ur to Vr. if (source.Kind != BoundKind.UnboundLambda) { return; } UnboundLambda anonymousFunction = (UnboundLambda)source; if (!anonymousFunction.HasExplicitReturnType(out _, out TypeWithAnnotations anonymousFunctionReturnType)) { return; } var delegateInvokeMethod = target.Type.GetDelegateType()?.DelegateInvokeMethod(); if (delegateInvokeMethod is null) { return; } ExactInference(anonymousFunctionReturnType, delegateInvokeMethod.ReturnTypeWithAnnotations, ref useSiteInfo); } #nullable disable //////////////////////////////////////////////////////////////////////////////// // // Exact inferences // private void ExactInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: An exact inference from a type U to a type V is made as follows: // SPEC: * Otherwise, if U is the type U1? and V is the type V1? then an // SPEC: exact inference is made from U to V. if (ExactNullableInference(source, target, ref useSiteInfo)) { return; } // SPEC: * If V is one of the unfixed Xi then U is added to the set of // SPEC: exact bounds for Xi. if (ExactTypeParameterInference(source, target)) { return; } // SPEC: * Otherwise, if U is an array type UE[...] and V is an array type VE[...] // SPEC: of the same rank then an exact inference from UE to VE is made. if (ExactArrayInference(source, target, ref useSiteInfo)) { return; } // SPEC: * Otherwise, if V is a constructed type C<V1...Vk> and U is a constructed // SPEC: type C<U1...Uk> then an exact inference is made // SPEC: from each Ui to the corresponding Vi. if (ExactConstructedInference(source, target, ref useSiteInfo)) { return; } // This can be valid via (where T : unmanaged) constraints if (ExactPointerInference(source, target, ref useSiteInfo)) { return; } // SPEC: * Otherwise no inferences are made. } private bool ExactTypeParameterInference(TypeWithAnnotations source, TypeWithAnnotations target) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: * If V is one of the unfixed Xi then U is added to the set of bounds // SPEC: for Xi. if (IsUnfixedTypeParameter(target)) { AddBound(source, _exactBounds, target); return true; } return false; } private bool ExactArrayInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: * Otherwise, if U is an array type UE[...] and V is an array type VE[...] // SPEC: of the same rank then an exact inference from UE to VE is made. if (!source.Type.IsArray() || !target.Type.IsArray()) { return false; } var arraySource = (ArrayTypeSymbol)source.Type; var arrayTarget = (ArrayTypeSymbol)target.Type; if (!arraySource.HasSameShapeAs(arrayTarget)) { return false; } ExactInference(arraySource.ElementTypeWithAnnotations, arrayTarget.ElementTypeWithAnnotations, ref useSiteInfo); return true; } private enum ExactOrBoundsKind { Exact, LowerBound, UpperBound, } private void ExactOrBoundsInference(ExactOrBoundsKind kind, TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { switch (kind) { case ExactOrBoundsKind.Exact: ExactInference(source, target, ref useSiteInfo); break; case ExactOrBoundsKind.LowerBound: LowerBoundInference(source, target, ref useSiteInfo); break; case ExactOrBoundsKind.UpperBound: UpperBoundInference(source, target, ref useSiteInfo); break; } } private bool ExactOrBoundsNullableInference(ExactOrBoundsKind kind, TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); if (source.IsNullableType() && target.IsNullableType()) { ExactOrBoundsInference(kind, ((NamedTypeSymbol)source.Type).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0], ((NamedTypeSymbol)target.Type).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0], ref useSiteInfo); return true; } if (isNullableOnly(source) && isNullableOnly(target)) { ExactOrBoundsInference(kind, source.AsNotNullableReferenceType(), target.AsNotNullableReferenceType(), ref useSiteInfo); return true; } return false; // True if the type is nullable. static bool isNullableOnly(TypeWithAnnotations type) => type.NullableAnnotation.IsAnnotated(); } private bool ExactNullableInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { return ExactOrBoundsNullableInference(ExactOrBoundsKind.Exact, source, target, ref useSiteInfo); } private bool LowerBoundTupleInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // NOTE: we are losing tuple element names when unwrapping tuple types to underlying types. // that is ok, because we are inferring type parameters used in the matching elements, // This is not the situation where entire tuple type used to infer a single type param ImmutableArray<TypeWithAnnotations> sourceTypes; ImmutableArray<TypeWithAnnotations> targetTypes; if (!source.Type.TryGetElementTypesWithAnnotationsIfTupleType(out sourceTypes) || !target.Type.TryGetElementTypesWithAnnotationsIfTupleType(out targetTypes) || sourceTypes.Length != targetTypes.Length) { return false; } for (int i = 0; i < sourceTypes.Length; i++) { LowerBoundInference(sourceTypes[i], targetTypes[i], ref useSiteInfo); } return true; } private bool ExactConstructedInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: * Otherwise, if V is a constructed type C<V1...Vk> and U is a constructed // SPEC: type C<U1...Uk> then an exact inference // SPEC: is made from each Ui to the corresponding Vi. var namedSource = source.Type as NamedTypeSymbol; if ((object)namedSource == null) { return false; } var namedTarget = target.Type as NamedTypeSymbol; if ((object)namedTarget == null) { return false; } if (!TypeSymbol.Equals(namedSource.OriginalDefinition, namedTarget.OriginalDefinition, TypeCompareKind.ConsiderEverything2)) { return false; } ExactTypeArgumentInference(namedSource, namedTarget, ref useSiteInfo); return true; } private bool ExactPointerInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (source.TypeKind == TypeKind.Pointer && target.TypeKind == TypeKind.Pointer) { ExactInference(((PointerTypeSymbol)source.Type).PointedAtTypeWithAnnotations, ((PointerTypeSymbol)target.Type).PointedAtTypeWithAnnotations, ref useSiteInfo); return true; } else if (source.Type is FunctionPointerTypeSymbol { Signature: { ParameterCount: int sourceParameterCount } sourceSignature } && target.Type is FunctionPointerTypeSymbol { Signature: { ParameterCount: int targetParameterCount } targetSignature } && sourceParameterCount == targetParameterCount) { if (!FunctionPointerRefKindsEqual(sourceSignature, targetSignature) || !FunctionPointerCallingConventionsEqual(sourceSignature, targetSignature)) { return false; } for (int i = 0; i < sourceParameterCount; i++) { ExactInference(sourceSignature.ParameterTypesWithAnnotations[i], targetSignature.ParameterTypesWithAnnotations[i], ref useSiteInfo); } ExactInference(sourceSignature.ReturnTypeWithAnnotations, targetSignature.ReturnTypeWithAnnotations, ref useSiteInfo); return true; } return false; } private static bool FunctionPointerCallingConventionsEqual(FunctionPointerMethodSymbol sourceSignature, FunctionPointerMethodSymbol targetSignature) { if (sourceSignature.CallingConvention != targetSignature.CallingConvention) { return false; } return (sourceSignature.GetCallingConventionModifiers(), targetSignature.GetCallingConventionModifiers()) switch { (null, null) => true, ({ } sourceModifiers, { } targetModifiers) when sourceModifiers.SetEquals(targetModifiers) => true, _ => false }; } private static bool FunctionPointerRefKindsEqual(FunctionPointerMethodSymbol sourceSignature, FunctionPointerMethodSymbol targetSignature) { return sourceSignature.RefKind == targetSignature.RefKind && (sourceSignature.ParameterRefKinds.IsDefault, targetSignature.ParameterRefKinds.IsDefault) switch { (true, false) or (false, true) => false, (true, true) => true, _ => sourceSignature.ParameterRefKinds.SequenceEqual(targetSignature.ParameterRefKinds) }; } private void ExactTypeArgumentInference(NamedTypeSymbol source, NamedTypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); Debug.Assert(TypeSymbol.Equals(source.OriginalDefinition, target.OriginalDefinition, TypeCompareKind.ConsiderEverything2)); var sourceTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); var targetTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); source.GetAllTypeArguments(sourceTypeArguments, ref useSiteInfo); target.GetAllTypeArguments(targetTypeArguments, ref useSiteInfo); Debug.Assert(sourceTypeArguments.Count == targetTypeArguments.Count); for (int arg = 0; arg < sourceTypeArguments.Count; ++arg) { ExactInference(sourceTypeArguments[arg], targetTypeArguments[arg], ref useSiteInfo); } sourceTypeArguments.Free(); targetTypeArguments.Free(); } //////////////////////////////////////////////////////////////////////////////// // // Lower-bound inferences // private void LowerBoundInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: A lower-bound inference from a type U to a type V is made as follows: // SPEC: * Otherwise, if V is nullable type V1? and U is nullable type U1? // SPEC: then an exact inference is made from U1 to V1. // SPEC ERROR: The spec should say "lower" here; we can safely make a lower-bound // SPEC ERROR: inference to nullable even though it is a generic struct. That is, // SPEC ERROR: if we have M<T>(T?, T) called with (char?, int) then we can infer // SPEC ERROR: lower bounds of char and int, and choose int. If we make an exact // SPEC ERROR: inference of char then type inference fails. if (LowerBoundNullableInference(source, target, ref useSiteInfo)) { return; } // SPEC: * If V is one of the unfixed Xi then U is added to the set of // SPEC: lower bounds for Xi. if (LowerBoundTypeParameterInference(source, target)) { return; } // SPEC: * Otherwise, if U is an array type Ue[...] and V is either an array // SPEC: type Ve[...] of the same rank, or if U is a one-dimensional array // SPEC: type Ue[] and V is one of IEnumerable<Ve>, ICollection<Ve> or // SPEC: IList<Ve> then // SPEC: * if Ue is known to be a reference type then a lower-bound inference // SPEC: from Ue to Ve is made. // SPEC: * otherwise an exact inference from Ue to Ve is made. if (LowerBoundArrayInference(source.Type, target.Type, ref useSiteInfo)) { return; } // UNDONE: At this point we could also do an inference from non-nullable U // UNDONE: to nullable V. // UNDONE: // UNDONE: We tried implementing lower bound nullable inference as follows: // UNDONE: // UNDONE: * Otherwise, if V is nullable type V1? and U is a non-nullable // UNDONE: struct type then an exact inference is made from U to V1. // UNDONE: // UNDONE: However, this causes an unfortunate interaction with what // UNDONE: looks like a bug in our implementation of section 15.2 of // UNDONE: the specification. Namely, it appears that the code which // UNDONE: checks whether a given method is compatible with // UNDONE: a delegate type assumes that if method type inference succeeds, // UNDONE: then the inferred types are compatible with the delegate types. // UNDONE: This is not necessarily so; the inferred types could be compatible // UNDONE: via a conversion other than reference or identity. // UNDONE: // UNDONE: We should take an action item to investigate this problem. // UNDONE: Until then, we will turn off the proposed lower bound nullable // UNDONE: inference. // if (LowerBoundNullableInference(pSource, pDest)) // { // return; // } if (LowerBoundTupleInference(source, target, ref useSiteInfo)) { return; } // SPEC: Otherwise... many cases for constructed generic types. if (LowerBoundConstructedInference(source.Type, target.Type, ref useSiteInfo)) { return; } if (LowerBoundFunctionPointerTypeInference(source.Type, target.Type, ref useSiteInfo)) { return; } // SPEC: * Otherwise, no inferences are made. } private bool LowerBoundTypeParameterInference(TypeWithAnnotations source, TypeWithAnnotations target) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: * If V is one of the unfixed Xi then U is added to the set of bounds // SPEC: for Xi. if (IsUnfixedTypeParameter(target)) { AddBound(source, _lowerBounds, target); return true; } return false; } private static TypeWithAnnotations GetMatchingElementType(ArrayTypeSymbol source, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); // It might be an array of same rank. if (target.IsArray()) { var arrayTarget = (ArrayTypeSymbol)target; if (!arrayTarget.HasSameShapeAs(source)) { return default; } return arrayTarget.ElementTypeWithAnnotations; } // Or it might be IEnum<T> and source is rank one. if (!source.IsSZArray) { return default; } // Arrays are specified as being convertible to IEnumerable<T>, ICollection<T> and // IList<T>; we also honor their convertibility to IReadOnlyCollection<T> and // IReadOnlyList<T>, and make inferences accordingly. if (!target.IsPossibleArrayGenericInterface()) { return default; } return ((NamedTypeSymbol)target).TypeArgumentWithDefinitionUseSiteDiagnostics(0, ref useSiteInfo); } private bool LowerBoundArrayInference(TypeSymbol source, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); // SPEC: * Otherwise, if U is an array type Ue[...] and V is either an array // SPEC: type Ve[...] of the same rank, or if U is a one-dimensional array // SPEC: type Ue[] and V is one of IEnumerable<Ve>, ICollection<Ve> or // SPEC: IList<Ve> then // SPEC: * if Ue is known to be a reference type then a lower-bound inference // SPEC: from Ue to Ve is made. // SPEC: * otherwise an exact inference from Ue to Ve is made. if (!source.IsArray()) { return false; } var arraySource = (ArrayTypeSymbol)source; var elementSource = arraySource.ElementTypeWithAnnotations; var elementTarget = GetMatchingElementType(arraySource, target, ref useSiteInfo); if (!elementTarget.HasType) { return false; } if (elementSource.Type.IsReferenceType) { LowerBoundInference(elementSource, elementTarget, ref useSiteInfo); } else { ExactInference(elementSource, elementTarget, ref useSiteInfo); } return true; } private bool LowerBoundNullableInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { return ExactOrBoundsNullableInference(ExactOrBoundsKind.LowerBound, source, target, ref useSiteInfo); } private bool LowerBoundConstructedInference(TypeSymbol source, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); var constructedTarget = target as NamedTypeSymbol; if ((object)constructedTarget == null) { return false; } if (constructedTarget.AllTypeArgumentCount() == 0) { return false; } // SPEC: * Otherwise, if V is a constructed class or struct type C<V1...Vk> // SPEC: and U is C<U1...Uk> then an exact inference // SPEC: is made from each Ui to the corresponding Vi. // SPEC: * Otherwise, if V is a constructed interface or delegate type C<V1...Vk> // SPEC: and U is C<U1...Uk> then an exact inference, // SPEC: lower bound inference or upper bound inference // SPEC: is made from each Ui to the corresponding Vi. var constructedSource = source as NamedTypeSymbol; if ((object)constructedSource != null && TypeSymbol.Equals(constructedSource.OriginalDefinition, constructedTarget.OriginalDefinition, TypeCompareKind.ConsiderEverything2)) { if (constructedSource.IsInterface || constructedSource.IsDelegateType()) { LowerBoundTypeArgumentInference(constructedSource, constructedTarget, ref useSiteInfo); } else { ExactTypeArgumentInference(constructedSource, constructedTarget, ref useSiteInfo); } return true; } // SPEC: * Otherwise, if V is a class type C<V1...Vk> and U is a class type which // SPEC: inherits directly or indirectly from C<U1...Uk> then an exact ... // SPEC: * ... and U is a type parameter with effective base class ... // SPEC: * ... and U is a type parameter with an effective base class which inherits ... if (LowerBoundClassInference(source, constructedTarget, ref useSiteInfo)) { return true; } // SPEC: * Otherwise, if V is an interface type C<V1...Vk> and U is a class type // SPEC: or struct type and there is a unique set U1...Uk such that U directly // SPEC: or indirectly implements C<U1...Uk> then an exact ... // SPEC: * ... and U is an interface type ... // SPEC: * ... and U is a type parameter ... if (LowerBoundInterfaceInference(source, constructedTarget, ref useSiteInfo)) { return true; } return false; } private bool LowerBoundClassInference(TypeSymbol source, NamedTypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); if (target.TypeKind != TypeKind.Class) { return false; } // Spec: 7.5.2.9 Lower-bound interfaces // SPEC: * Otherwise, if V is a class type C<V1...Vk> and U is a class type which // SPEC: inherits directly or indirectly from C<U1...Uk> // SPEC: then an exact inference is made from each Ui to the corresponding Vi. // SPEC: * Otherwise, if V is a class type C<V1...Vk> and U is a type parameter // SPEC: with effective base class C<U1...Uk> // SPEC: then an exact inference is made from each Ui to the corresponding Vi. // SPEC: * Otherwise, if V is a class type C<V1...Vk> and U is a type parameter // SPEC: with an effective base class which inherits directly or indirectly from // SPEC: C<U1...Uk> then an exact inference is made // SPEC: from each Ui to the corresponding Vi. NamedTypeSymbol sourceBase = null; if (source.TypeKind == TypeKind.Class) { sourceBase = source.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); } else if (source.TypeKind == TypeKind.TypeParameter) { sourceBase = ((TypeParameterSymbol)source).EffectiveBaseClass(ref useSiteInfo); } while ((object)sourceBase != null) { if (TypeSymbol.Equals(sourceBase.OriginalDefinition, target.OriginalDefinition, TypeCompareKind.ConsiderEverything2)) { ExactTypeArgumentInference(sourceBase, target, ref useSiteInfo); return true; } sourceBase = sourceBase.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); } return false; } private bool LowerBoundInterfaceInference(TypeSymbol source, NamedTypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); if (!target.IsInterface) { return false; } // Spec 7.5.2.9 Lower-bound interfaces // SPEC: * Otherwise, if V [target] is an interface type C<V1...Vk> and U [source] is a class type // SPEC: or struct type and there is a unique set U1...Uk such that U directly // SPEC: or indirectly implements C<U1...Uk> then an // SPEC: exact, upper-bound, or lower-bound inference ... // SPEC: * ... and U is an interface type ... // SPEC: * ... and U is a type parameter ... ImmutableArray<NamedTypeSymbol> allInterfaces; switch (source.TypeKind) { case TypeKind.Struct: case TypeKind.Class: case TypeKind.Interface: allInterfaces = source.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo); break; case TypeKind.TypeParameter: var typeParameter = (TypeParameterSymbol)source; allInterfaces = typeParameter.EffectiveBaseClass(ref useSiteInfo). AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo). Concat(typeParameter.AllEffectiveInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo)); break; default: return false; } // duplicates with only nullability differences can be merged (to avoid an error in type inference) allInterfaces = ModuloReferenceTypeNullabilityDifferences(allInterfaces, VarianceKind.In); NamedTypeSymbol matchingInterface = GetInterfaceInferenceBound(allInterfaces, target); if ((object)matchingInterface == null) { return false; } LowerBoundTypeArgumentInference(matchingInterface, target, ref useSiteInfo); return true; } internal static ImmutableArray<NamedTypeSymbol> ModuloReferenceTypeNullabilityDifferences(ImmutableArray<NamedTypeSymbol> interfaces, VarianceKind variance) { var dictionary = PooledDictionaryIgnoringNullableModifiersForReferenceTypes.GetInstance(); foreach (var @interface in interfaces) { if (dictionary.TryGetValue(@interface, out var found)) { var merged = (NamedTypeSymbol)found.MergeEquivalentTypes(@interface, variance); dictionary[@interface] = merged; } else { dictionary.Add(@interface, @interface); } } var result = dictionary.Count != interfaces.Length ? dictionary.Values.ToImmutableArray() : interfaces; dictionary.Free(); return result; } private void LowerBoundTypeArgumentInference(NamedTypeSymbol source, NamedTypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: The choice of inference for the i-th type argument is made // SPEC: based on the declaration of the i-th type parameter of C, as // SPEC: follows: // SPEC: * if Ui is known to be of reference type and the i-th type parameter // SPEC: was declared as covariant then a lower bound inference is made. // SPEC: * if Ui is known to be of reference type and the i-th type parameter // SPEC: was declared as contravariant then an upper bound inference is made. // SPEC: * otherwise, an exact inference is made. Debug.Assert((object)source != null); Debug.Assert((object)target != null); Debug.Assert(TypeSymbol.Equals(source.OriginalDefinition, target.OriginalDefinition, TypeCompareKind.ConsiderEverything2)); var typeParameters = ArrayBuilder<TypeParameterSymbol>.GetInstance(); var sourceTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); var targetTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); source.OriginalDefinition.GetAllTypeParameters(typeParameters); source.GetAllTypeArguments(sourceTypeArguments, ref useSiteInfo); target.GetAllTypeArguments(targetTypeArguments, ref useSiteInfo); Debug.Assert(typeParameters.Count == sourceTypeArguments.Count); Debug.Assert(typeParameters.Count == targetTypeArguments.Count); for (int arg = 0; arg < sourceTypeArguments.Count; ++arg) { var typeParameter = typeParameters[arg]; var sourceTypeArgument = sourceTypeArguments[arg]; var targetTypeArgument = targetTypeArguments[arg]; if (sourceTypeArgument.Type.IsReferenceType && typeParameter.Variance == VarianceKind.Out) { LowerBoundInference(sourceTypeArgument, targetTypeArgument, ref useSiteInfo); } else if (sourceTypeArgument.Type.IsReferenceType && typeParameter.Variance == VarianceKind.In) { UpperBoundInference(sourceTypeArgument, targetTypeArgument, ref useSiteInfo); } else { ExactInference(sourceTypeArgument, targetTypeArgument, ref useSiteInfo); } } typeParameters.Free(); sourceTypeArguments.Free(); targetTypeArguments.Free(); } #nullable enable private bool LowerBoundFunctionPointerTypeInference(TypeSymbol source, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (source is not FunctionPointerTypeSymbol { Signature: { } sourceSignature } || target is not FunctionPointerTypeSymbol { Signature: { } targetSignature }) { return false; } if (sourceSignature.ParameterCount != targetSignature.ParameterCount) { return false; } if (!FunctionPointerRefKindsEqual(sourceSignature, targetSignature) || !FunctionPointerCallingConventionsEqual(sourceSignature, targetSignature)) { return false; } // Reference parameters are treated as "input" variance by default, and reference return types are treated as out variance by default. // If they have a ref kind or are not reference types, then they are treated as invariant. for (int i = 0; i < sourceSignature.ParameterCount; i++) { var sourceParam = sourceSignature.Parameters[i]; var targetParam = targetSignature.Parameters[i]; if ((sourceParam.Type.IsReferenceType || sourceParam.Type.IsFunctionPointer()) && sourceParam.RefKind == RefKind.None) { UpperBoundInference(sourceParam.TypeWithAnnotations, targetParam.TypeWithAnnotations, ref useSiteInfo); } else { ExactInference(sourceParam.TypeWithAnnotations, targetParam.TypeWithAnnotations, ref useSiteInfo); } } if ((sourceSignature.ReturnType.IsReferenceType || sourceSignature.ReturnType.IsFunctionPointer()) && sourceSignature.RefKind == RefKind.None) { LowerBoundInference(sourceSignature.ReturnTypeWithAnnotations, targetSignature.ReturnTypeWithAnnotations, ref useSiteInfo); } else { ExactInference(sourceSignature.ReturnTypeWithAnnotations, targetSignature.ReturnTypeWithAnnotations, ref useSiteInfo); } return true; } #nullable disable //////////////////////////////////////////////////////////////////////////////// // // Upper-bound inferences // private void UpperBoundInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: An upper-bound inference from a type U to a type V is made as follows: // SPEC: * Otherwise, if V is nullable type V1? and U is nullable type U1? // SPEC: then an exact inference is made from U1 to V1. if (UpperBoundNullableInference(source, target, ref useSiteInfo)) { return; } // SPEC: * If V is one of the unfixed Xi then U is added to the set of // SPEC: upper bounds for Xi. if (UpperBoundTypeParameterInference(source, target)) { return; } // SPEC: * Otherwise, if V is an array type Ve[...] and U is an array // SPEC: type Ue[...] of the same rank, or if V is a one-dimensional array // SPEC: type Ve[] and U is one of IEnumerable<Ue>, ICollection<Ue> or // SPEC: IList<Ue> then // SPEC: * if Ue is known to be a reference type then an upper-bound inference // SPEC: from Ue to Ve is made. // SPEC: * otherwise an exact inference from Ue to Ve is made. if (UpperBoundArrayInference(source, target, ref useSiteInfo)) { return; } Debug.Assert(source.Type.IsReferenceType || source.Type.IsFunctionPointer()); // NOTE: spec would ask us to do the following checks, but since the value types // are trivially handled as exact inference in the callers, we do not have to. //if (ExactTupleInference(source, target, ref useSiteInfo)) //{ // return; //} // SPEC: * Otherwise... cases for constructed types if (UpperBoundConstructedInference(source, target, ref useSiteInfo)) { return; } if (UpperBoundFunctionPointerTypeInference(source.Type, target.Type, ref useSiteInfo)) { return; } // SPEC: * Otherwise, no inferences are made. } private bool UpperBoundTypeParameterInference(TypeWithAnnotations source, TypeWithAnnotations target) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: * If V is one of the unfixed Xi then U is added to the set of upper bounds // SPEC: for Xi. if (IsUnfixedTypeParameter(target)) { AddBound(source, _upperBounds, target); return true; } return false; } private bool UpperBoundArrayInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: * Otherwise, if V is an array type Ve[...] and U is an array // SPEC: type Ue[...] of the same rank, or if V is a one-dimensional array // SPEC: type Ve[] and U is one of IEnumerable<Ue>, ICollection<Ue> or // SPEC: IList<Ue> then // SPEC: * if Ue is known to be a reference type then an upper-bound inference // SPEC: from Ue to Ve is made. // SPEC: * otherwise an exact inference from Ue to Ve is made. if (!target.Type.IsArray()) { return false; } var arrayTarget = (ArrayTypeSymbol)target.Type; var elementTarget = arrayTarget.ElementTypeWithAnnotations; var elementSource = GetMatchingElementType(arrayTarget, source.Type, ref useSiteInfo); if (!elementSource.HasType) { return false; } if (elementSource.Type.IsReferenceType) { UpperBoundInference(elementSource, elementTarget, ref useSiteInfo); } else { ExactInference(elementSource, elementTarget, ref useSiteInfo); } return true; } private bool UpperBoundNullableInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { return ExactOrBoundsNullableInference(ExactOrBoundsKind.UpperBound, source, target, ref useSiteInfo); } private bool UpperBoundConstructedInference(TypeWithAnnotations sourceWithAnnotations, TypeWithAnnotations targetWithAnnotations, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(sourceWithAnnotations.HasType); Debug.Assert(targetWithAnnotations.HasType); var source = sourceWithAnnotations.Type; var target = targetWithAnnotations.Type; var constructedSource = source as NamedTypeSymbol; if ((object)constructedSource == null) { return false; } if (constructedSource.AllTypeArgumentCount() == 0) { return false; } // SPEC: * Otherwise, if V is a constructed type C<V1...Vk> and U is // SPEC: C<U1...Uk> then an exact inference, // SPEC: lower bound inference or upper bound inference // SPEC: is made from each Ui to the corresponding Vi. var constructedTarget = target as NamedTypeSymbol; if ((object)constructedTarget != null && TypeSymbol.Equals(constructedSource.OriginalDefinition, target.OriginalDefinition, TypeCompareKind.ConsiderEverything2)) { if (constructedTarget.IsInterface || constructedTarget.IsDelegateType()) { UpperBoundTypeArgumentInference(constructedSource, constructedTarget, ref useSiteInfo); } else { ExactTypeArgumentInference(constructedSource, constructedTarget, ref useSiteInfo); } return true; } // SPEC: * Otherwise, if U is a class type C<U1...Uk> and V is a class type which // SPEC: inherits directly or indirectly from C<V1...Vk> then an exact ... if (UpperBoundClassInference(constructedSource, target, ref useSiteInfo)) { return true; } // SPEC: * Otherwise, if U is an interface type C<U1...Uk> and V is a class type // SPEC: or struct type and there is a unique set V1...Vk such that V directly // SPEC: or indirectly implements C<V1...Vk> then an exact ... // SPEC: * ... and U is an interface type ... if (UpperBoundInterfaceInference(constructedSource, target, ref useSiteInfo)) { return true; } return false; } private bool UpperBoundClassInference(NamedTypeSymbol source, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); if (source.TypeKind != TypeKind.Class || target.TypeKind != TypeKind.Class) { return false; } // SPEC: * Otherwise, if U is a class type C<U1...Uk> and V is a class type which // SPEC: inherits directly or indirectly from C<V1...Vk> then an exact // SPEC: inference is made from each Ui to the corresponding Vi. var targetBase = target.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); while ((object)targetBase != null) { if (TypeSymbol.Equals(targetBase.OriginalDefinition, source.OriginalDefinition, TypeCompareKind.ConsiderEverything2)) { ExactTypeArgumentInference(source, targetBase, ref useSiteInfo); return true; } targetBase = targetBase.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); } return false; } private bool UpperBoundInterfaceInference(NamedTypeSymbol source, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); if (!source.IsInterface) { return false; } // SPEC: * Otherwise, if U [source] is an interface type C<U1...Uk> and V [target] is a class type // SPEC: or struct type and there is a unique set V1...Vk such that V directly // SPEC: or indirectly implements C<V1...Vk> then an exact ... // SPEC: * ... and U is an interface type ... switch (target.TypeKind) { case TypeKind.Struct: case TypeKind.Class: case TypeKind.Interface: break; default: return false; } ImmutableArray<NamedTypeSymbol> allInterfaces = target.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo); // duplicates with only nullability differences can be merged (to avoid an error in type inference) allInterfaces = ModuloReferenceTypeNullabilityDifferences(allInterfaces, VarianceKind.Out); NamedTypeSymbol bestInterface = GetInterfaceInferenceBound(allInterfaces, source); if ((object)bestInterface == null) { return false; } UpperBoundTypeArgumentInference(source, bestInterface, ref useSiteInfo); return true; } private void UpperBoundTypeArgumentInference(NamedTypeSymbol source, NamedTypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: The choice of inference for the i-th type argument is made // SPEC: based on the declaration of the i-th type parameter of C, as // SPEC: follows: // SPEC: * if Ui is known to be of reference type and the i-th type parameter // SPEC: was declared as covariant then an upper-bound inference is made. // SPEC: * if Ui is known to be of reference type and the i-th type parameter // SPEC: was declared as contravariant then a lower-bound inference is made. // SPEC: * otherwise, an exact inference is made. Debug.Assert((object)source != null); Debug.Assert((object)target != null); Debug.Assert(TypeSymbol.Equals(source.OriginalDefinition, target.OriginalDefinition, TypeCompareKind.ConsiderEverything2)); var typeParameters = ArrayBuilder<TypeParameterSymbol>.GetInstance(); var sourceTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); var targetTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); source.OriginalDefinition.GetAllTypeParameters(typeParameters); source.GetAllTypeArguments(sourceTypeArguments, ref useSiteInfo); target.GetAllTypeArguments(targetTypeArguments, ref useSiteInfo); Debug.Assert(typeParameters.Count == sourceTypeArguments.Count); Debug.Assert(typeParameters.Count == targetTypeArguments.Count); for (int arg = 0; arg < sourceTypeArguments.Count; ++arg) { var typeParameter = typeParameters[arg]; var sourceTypeArgument = sourceTypeArguments[arg]; var targetTypeArgument = targetTypeArguments[arg]; if (sourceTypeArgument.Type.IsReferenceType && typeParameter.Variance == VarianceKind.Out) { UpperBoundInference(sourceTypeArgument, targetTypeArgument, ref useSiteInfo); } else if (sourceTypeArgument.Type.IsReferenceType && typeParameter.Variance == VarianceKind.In) { LowerBoundInference(sourceTypeArgument, targetTypeArgument, ref useSiteInfo); } else { ExactInference(sourceTypeArgument, targetTypeArgument, ref useSiteInfo); } } typeParameters.Free(); sourceTypeArguments.Free(); targetTypeArguments.Free(); } #nullable enable private bool UpperBoundFunctionPointerTypeInference(TypeSymbol source, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (source is not FunctionPointerTypeSymbol { Signature: { } sourceSignature } || target is not FunctionPointerTypeSymbol { Signature: { } targetSignature }) { return false; } if (sourceSignature.ParameterCount != targetSignature.ParameterCount) { return false; } if (!FunctionPointerRefKindsEqual(sourceSignature, targetSignature) || !FunctionPointerCallingConventionsEqual(sourceSignature, targetSignature)) { return false; } // Reference parameters are treated as "input" variance by default, and reference return types are treated as out variance by default. // If they have a ref kind or are not reference types, then they are treated as invariant. for (int i = 0; i < sourceSignature.ParameterCount; i++) { var sourceParam = sourceSignature.Parameters[i]; var targetParam = targetSignature.Parameters[i]; if ((sourceParam.Type.IsReferenceType || sourceParam.Type.IsFunctionPointer()) && sourceParam.RefKind == RefKind.None) { LowerBoundInference(sourceParam.TypeWithAnnotations, targetParam.TypeWithAnnotations, ref useSiteInfo); } else { ExactInference(sourceParam.TypeWithAnnotations, targetParam.TypeWithAnnotations, ref useSiteInfo); } } if ((sourceSignature.ReturnType.IsReferenceType || sourceSignature.ReturnType.IsFunctionPointer()) && sourceSignature.RefKind == RefKind.None) { UpperBoundInference(sourceSignature.ReturnTypeWithAnnotations, targetSignature.ReturnTypeWithAnnotations, ref useSiteInfo); } else { ExactInference(sourceSignature.ReturnTypeWithAnnotations, targetSignature.ReturnTypeWithAnnotations, ref useSiteInfo); } return true; } //////////////////////////////////////////////////////////////////////////////// // // Fixing // private bool Fix(int iParam, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(IsUnfixed(iParam)); var typeParameter = _methodTypeParameters[iParam]; var exact = _exactBounds[iParam]; var lower = _lowerBounds[iParam]; var upper = _upperBounds[iParam]; var best = Fix(_compilation, _conversions, typeParameter, exact, lower, upper, ref useSiteInfo); if (!best.Type.HasType) { return false; } #if DEBUG if (_conversions.IncludeNullability) { // If the first attempt succeeded, the result should be the same as // the second attempt, although perhaps with different nullability. var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var withoutNullability = Fix(_compilation, _conversions.WithNullability(false), typeParameter, exact, lower, upper, ref discardedUseSiteInfo).Type; // https://github.com/dotnet/roslyn/issues/27961 Results may differ by tuple names or dynamic. // See NullableReferenceTypesTests.TypeInference_TupleNameDifferences_01 for example. Debug.Assert(best.Type.Type.Equals(withoutNullability.Type, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); } #endif _fixedResults[iParam] = best; UpdateDependenciesAfterFix(iParam); return true; } private static (TypeWithAnnotations Type, bool FromFunctionType) Fix( CSharpCompilation compilation, ConversionsBase conversions, TypeParameterSymbol typeParameter, HashSet<TypeWithAnnotations>? exact, HashSet<TypeWithAnnotations>? lower, HashSet<TypeWithAnnotations>? upper, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // UNDONE: This method makes a lot of garbage. // SPEC: An unfixed type parameter with a set of bounds is fixed as follows: // SPEC: * The set of candidate types starts out as the set of all types in // SPEC: the bounds. // SPEC: * We then examine each bound in turn. For each exact bound U of Xi, // SPEC: all types which are not identical to U are removed from the candidate set. // Optimization: if we have two or more exact bounds, fixing is impossible. var candidates = new Dictionary<TypeWithAnnotations, TypeWithAnnotations>(EqualsIgnoringDynamicTupleNamesAndNullabilityComparer.Instance); Debug.Assert(!containsFunctionTypes(exact)); Debug.Assert(!containsFunctionTypes(upper)); // Function types are dropped if there are any non-function types. if (containsFunctionTypes(lower) && (containsNonFunctionTypes(lower) || containsNonFunctionTypes(exact) || containsNonFunctionTypes(upper))) { lower = removeFunctionTypes(lower); } // Optimization: if we have one exact bound then we need not add any // inexact bounds; we're just going to remove them anyway. if (exact == null) { if (lower != null) { // Lower bounds represent co-variance. AddAllCandidates(candidates, lower, VarianceKind.Out, conversions); } if (upper != null) { // Upper bounds represent contra-variance. AddAllCandidates(candidates, upper, VarianceKind.In, conversions); } } else { // Exact bounds represent invariance. AddAllCandidates(candidates, exact, VarianceKind.None, conversions); if (candidates.Count >= 2) { return default; } } if (candidates.Count == 0) { return default; } // Don't mutate the collection as we're iterating it. var initialCandidates = ArrayBuilder<TypeWithAnnotations>.GetInstance(); GetAllCandidates(candidates, initialCandidates); // SPEC: For each lower bound U of Xi all types to which there is not an // SPEC: implicit conversion from U are removed from the candidate set. if (lower != null) { MergeOrRemoveCandidates(candidates, lower, initialCandidates, conversions, VarianceKind.Out, ref useSiteInfo); } // SPEC: For each upper bound U of Xi all types from which there is not an // SPEC: implicit conversion to U are removed from the candidate set. if (upper != null) { MergeOrRemoveCandidates(candidates, upper, initialCandidates, conversions, VarianceKind.In, ref useSiteInfo); } initialCandidates.Clear(); GetAllCandidates(candidates, initialCandidates); // SPEC: * If among the remaining candidate types there is a unique type V to // SPEC: which there is an implicit conversion from all the other candidate // SPEC: types, then the parameter is fixed to V. TypeWithAnnotations best = default; foreach (var candidate in initialCandidates) { foreach (var candidate2 in initialCandidates) { if (!candidate.Equals(candidate2, TypeCompareKind.ConsiderEverything) && !ImplicitConversionExists(candidate2, candidate, ref useSiteInfo, conversions.WithNullability(false))) { goto OuterBreak; } } if (!best.HasType) { best = candidate; } else { Debug.Assert(!best.Equals(candidate, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); // best candidate is not unique best = default; break; } OuterBreak: ; } initialCandidates.Free(); bool fromFunctionType = false; if (isFunctionType(best, out var functionType)) { // Realize the type as TDelegate, or Expression<TDelegate> if the type parameter // is constrained to System.Linq.Expressions.Expression. var resultType = functionType.GetInternalDelegateType(); if (hasExpressionTypeConstraint(typeParameter)) { var expressionOfTType = compilation.GetWellKnownType(WellKnownType.System_Linq_Expressions_Expression_T); resultType = expressionOfTType.Construct(resultType); } best = TypeWithAnnotations.Create(resultType, best.NullableAnnotation); fromFunctionType = true; } return (best, fromFunctionType); static bool containsFunctionTypes([NotNullWhen(true)] HashSet<TypeWithAnnotations>? types) { return types?.Any(t => isFunctionType(t, out _)) == true; } static bool containsNonFunctionTypes([NotNullWhen(true)] HashSet<TypeWithAnnotations>? types) { return types?.Any(t => !isFunctionType(t, out _)) == true; } static bool isFunctionType(TypeWithAnnotations type, [NotNullWhen(true)] out FunctionTypeSymbol? functionType) { functionType = type.Type as FunctionTypeSymbol; return functionType is not null; } static bool hasExpressionTypeConstraint(TypeParameterSymbol typeParameter) { var constraintTypes = typeParameter.ConstraintTypesNoUseSiteDiagnostics; return constraintTypes.Any(t => isExpressionType(t.Type)); } static bool isExpressionType(TypeSymbol? type) { while (type is { }) { if (type.IsGenericOrNonGenericExpressionType(out _)) { return true; } type = type.BaseTypeNoUseSiteDiagnostics; } return false; } static HashSet<TypeWithAnnotations>? removeFunctionTypes(HashSet<TypeWithAnnotations> types) { HashSet<TypeWithAnnotations>? updated = null; foreach (var type in types) { if (!isFunctionType(type, out _)) { updated ??= new HashSet<TypeWithAnnotations>(TypeWithAnnotations.EqualsComparer.ConsiderEverythingComparer); updated.Add(type); } } return updated; } } private static bool ImplicitConversionExists(TypeWithAnnotations sourceWithAnnotations, TypeWithAnnotations destinationWithAnnotations, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, ConversionsBase conversions) { var source = sourceWithAnnotations.Type; var destination = destinationWithAnnotations.Type; // SPEC VIOLATION: For the purpose of algorithm in Fix method, dynamic type is not considered convertible to any other type, including object. if (source.IsDynamic() && !destination.IsDynamic()) { return false; } if (!conversions.HasTopLevelNullabilityImplicitConversion(sourceWithAnnotations, destinationWithAnnotations)) { return false; } return conversions.ClassifyImplicitConversionFromTypeWhenNeitherOrBothFunctionTypes(source, destination, ref useSiteInfo).Exists; } #nullable disable //////////////////////////////////////////////////////////////////////////////// // // Inferred return type // private TypeWithAnnotations InferReturnType(BoundExpression source, NamedTypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)target != null); Debug.Assert(target.IsDelegateType()); Debug.Assert((object)target.DelegateInvokeMethod != null && !target.DelegateInvokeMethod.HasUseSiteError, "This method should only be called for legal delegate types."); Debug.Assert(!target.DelegateInvokeMethod.ReturnsVoid); // We should not be computing the inferred return type unless we are converting // to a delegate type where all the input types are fixed. Debug.Assert(!HasUnfixedParamInInputType(source, target)); // Spec 7.5.2.12: Inferred return type: // The inferred return type of an anonymous function F is used during // type inference and overload resolution. The inferred return type // can only be determined for an anonymous function where all parameter // types are known, either because they are explicitly given, provided // through an anonymous function conversion, or inferred during type // inference on an enclosing generic method invocation. // The inferred return type is determined as follows: // * If the body of F is an expression (that has a type) then the // inferred return type of F is the type of that expression. // * If the body of F is a block and the set of expressions in the // blocks return statements has a best common type T then the // inferred return type of F is T. // * Otherwise, a return type cannot be inferred for F. if (source.Kind != BoundKind.UnboundLambda) { return default; } var anonymousFunction = (UnboundLambda)source; if (anonymousFunction.HasSignature) { // Optimization: // We know that the anonymous function has a parameter list. If it does not // have the same arity as the delegate, then it cannot possibly be applicable. // Rather than have type inference fail, we will simply not make a return // type inference and have type inference continue on. Either inference // will fail, or we will infer a nonapplicable method. Either way, there // is no change to the semantics of overload resolution. var originalDelegateParameters = target.DelegateParameters(); if (originalDelegateParameters.IsDefault) { return default; } if (originalDelegateParameters.Length != anonymousFunction.ParameterCount) { return default; } } var fixedDelegate = (NamedTypeSymbol)GetFixedDelegateOrFunctionPointer(target); var fixedDelegateParameters = fixedDelegate.DelegateParameters(); // Optimization: // Similarly, if we have an entirely fixed delegate and an explicitly typed // anonymous function, then the parameter types had better be identical. // If not, applicability will eventually fail, so there is no semantic // difference caused by failing to make a return type inference. if (anonymousFunction.HasExplicitlyTypedParameterList) { for (int p = 0; p < anonymousFunction.ParameterCount; ++p) { if (!anonymousFunction.ParameterType(p).Equals(fixedDelegateParameters[p].Type, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)) { return default; } } } // Future optimization: We could return default if the delegate has out or ref parameters // and the anonymous function is an implicitly typed lambda. It will not be applicable. // We have an entirely fixed delegate parameter list, which is of the same arity as // the anonymous function parameter list, and possibly exactly the same types if // the anonymous function is explicitly typed. Make an inference from the // delegate parameters to the return type. return anonymousFunction.InferReturnType(_conversions, fixedDelegate, ref useSiteInfo); } /// <summary> /// Return the interface with an original definition matches /// the original definition of the target. If the are no matches, /// or multiple matches, the return value is null. /// </summary> private static NamedTypeSymbol GetInterfaceInferenceBound(ImmutableArray<NamedTypeSymbol> interfaces, NamedTypeSymbol target) { Debug.Assert(target.IsInterface); NamedTypeSymbol matchingInterface = null; foreach (var currentInterface in interfaces) { if (TypeSymbol.Equals(currentInterface.OriginalDefinition, target.OriginalDefinition, TypeCompareKind.ConsiderEverything)) { if ((object)matchingInterface == null) { matchingInterface = currentInterface; } else if (!TypeSymbol.Equals(matchingInterface, currentInterface, TypeCompareKind.ConsiderEverything)) { // Not unique. Bail out. return null; } } } return matchingInterface; } //////////////////////////////////////////////////////////////////////////////// // // Helper methods // //////////////////////////////////////////////////////////////////////////////// // // In error recovery and reporting scenarios we sometimes end up in a situation // like this: // // x.Goo( y=> // // and the question is, "is Goo a valid extension method of x?" If Goo is // generic, then Goo will be something like: // // static Blah Goo<T>(this Bar<T> bar, Func<T, T> f){ ... } // // What we would like to know is: given _only_ the expression x, can we infer // what T is in Bar<T> ? If we can, then for error recovery and reporting // we can provisionally consider Goo to be an extension method of x. If we // cannot deduce this just from x then we should consider Goo to not be an // extension method of x, at least until we have more information. // // Clearly it is pointless to run multiple phases public static ImmutableArray<TypeWithAnnotations> InferTypeArgumentsFromFirstArgument( CSharpCompilation compilation, ConversionsBase conversions, MethodSymbol method, ImmutableArray<BoundExpression> arguments, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)method != null); Debug.Assert(method.Arity > 0); Debug.Assert(!arguments.IsDefault); // We need at least one formal parameter type and at least one argument. if ((method.ParameterCount < 1) || (arguments.Length < 1)) { return default(ImmutableArray<TypeWithAnnotations>); } Debug.Assert(!method.GetParameterType(0).IsDynamic()); var constructedFromMethod = method.ConstructedFrom; var inferrer = new MethodTypeInferrer( compilation, conversions, constructedFromMethod.TypeParameters, constructedFromMethod.ContainingType, constructedFromMethod.GetParameterTypes(), constructedFromMethod.ParameterRefKinds, arguments, extensions: null); if (!inferrer.InferTypeArgumentsFromFirstArgument(ref useSiteInfo)) { return default(ImmutableArray<TypeWithAnnotations>); } return inferrer.GetInferredTypeArguments(out _); } //////////////////////////////////////////////////////////////////////////////// private bool InferTypeArgumentsFromFirstArgument(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(!_formalParameterTypes.IsDefault); Debug.Assert(_formalParameterTypes.Length >= 1); Debug.Assert(!_arguments.IsDefault); Debug.Assert(_arguments.Length >= 1); var dest = _formalParameterTypes[0]; var argument = _arguments[0]; TypeSymbol source = argument.Type; // Rule out lambdas, nulls, and so on. if (!IsReallyAType(source)) { return false; } LowerBoundInference(_extensions.GetTypeWithAnnotations(argument), dest, ref useSiteInfo); // Now check to see that every type parameter used by the first // formal parameter type was successfully inferred. for (int iParam = 0; iParam < _methodTypeParameters.Length; ++iParam) { TypeParameterSymbol pParam = _methodTypeParameters[iParam]; if (!dest.Type.ContainsTypeParameter(pParam)) { continue; } Debug.Assert(IsUnfixed(iParam)); if (!HasBound(iParam) || !Fix(iParam, ref useSiteInfo)) { return false; } } return true; } #nullable enable /// <summary> /// Return the inferred type arguments using null /// for any type arguments that were not inferred. /// </summary> private ImmutableArray<TypeWithAnnotations> GetInferredTypeArguments(out bool inferredFromFunctionType) { var builder = ArrayBuilder<TypeWithAnnotations>.GetInstance(_fixedResults.Length); inferredFromFunctionType = false; foreach (var fixedResult in _fixedResults) { builder.Add(fixedResult.Type); if (fixedResult.FromFunctionType) { inferredFromFunctionType = true; } } return builder.ToImmutableAndFree(); } private static bool IsReallyAType(TypeSymbol? type) { return type is { } && !type.IsErrorType() && !type.IsVoidType(); } private static void GetAllCandidates(Dictionary<TypeWithAnnotations, TypeWithAnnotations> candidates, ArrayBuilder<TypeWithAnnotations> builder) { builder.AddRange(candidates.Values); } private static void AddAllCandidates( Dictionary<TypeWithAnnotations, TypeWithAnnotations> candidates, HashSet<TypeWithAnnotations> bounds, VarianceKind variance, ConversionsBase conversions) { foreach (var candidate in bounds) { var type = candidate; if (!conversions.IncludeNullability) { // https://github.com/dotnet/roslyn/issues/30534: Should preserve // distinct "not computed" state from initial binding. type = type.SetUnknownNullabilityForReferenceTypes(); } AddOrMergeCandidate(candidates, type, variance, conversions); } } private static void AddOrMergeCandidate( Dictionary<TypeWithAnnotations, TypeWithAnnotations> candidates, TypeWithAnnotations newCandidate, VarianceKind variance, ConversionsBase conversions) { Debug.Assert(conversions.IncludeNullability || newCandidate.SetUnknownNullabilityForReferenceTypes().Equals(newCandidate, TypeCompareKind.ConsiderEverything)); if (candidates.TryGetValue(newCandidate, out TypeWithAnnotations oldCandidate)) { MergeAndReplaceIfStillCandidate(candidates, oldCandidate, newCandidate, variance, conversions); } else { candidates.Add(newCandidate, newCandidate); } } private static void MergeOrRemoveCandidates( Dictionary<TypeWithAnnotations, TypeWithAnnotations> candidates, HashSet<TypeWithAnnotations> bounds, ArrayBuilder<TypeWithAnnotations> initialCandidates, ConversionsBase conversions, VarianceKind variance, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(variance == VarianceKind.In || variance == VarianceKind.Out); // SPEC: For each lower (upper) bound U of Xi all types to which there is not an // SPEC: implicit conversion from (to) U are removed from the candidate set. var comparison = conversions.IncludeNullability ? TypeCompareKind.ConsiderEverything : TypeCompareKind.IgnoreNullableModifiersForReferenceTypes; foreach (var bound in bounds) { foreach (var candidate in initialCandidates) { if (bound.Equals(candidate, comparison)) { continue; } TypeWithAnnotations source; TypeWithAnnotations destination; if (variance == VarianceKind.Out) { source = bound; destination = candidate; } else { source = candidate; destination = bound; } if (!ImplicitConversionExists(source, destination, ref useSiteInfo, conversions.WithNullability(false))) { candidates.Remove(candidate); if (conversions.IncludeNullability && candidates.TryGetValue(bound, out var oldBound)) { // merge the nullability from candidate into bound var oldAnnotation = oldBound.NullableAnnotation; var newAnnotation = oldAnnotation.MergeNullableAnnotation(candidate.NullableAnnotation, variance); if (oldAnnotation != newAnnotation) { var newBound = TypeWithAnnotations.Create(oldBound.Type, newAnnotation); candidates[bound] = newBound; } } } else if (bound.Equals(candidate, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)) { // SPEC: 4.7 The Dynamic Type // Type inference (7.5.2) will prefer dynamic over object if both are candidates. // // This rule doesn't have to be implemented explicitly due to special handling of // conversions from dynamic in ImplicitConversionExists helper. // MergeAndReplaceIfStillCandidate(candidates, candidate, bound, variance, conversions); } } } } private static void MergeAndReplaceIfStillCandidate( Dictionary<TypeWithAnnotations, TypeWithAnnotations> candidates, TypeWithAnnotations oldCandidate, TypeWithAnnotations newCandidate, VarianceKind variance, ConversionsBase conversions) { // We make an exception when new candidate is dynamic, for backwards compatibility if (newCandidate.Type.IsDynamic()) { return; } if (candidates.TryGetValue(oldCandidate, out TypeWithAnnotations latest)) { // Note: we're ignoring the variance used merging previous candidates into `latest`. // If that variance is different than `variance`, we might infer the wrong nullability, but in that case, // we assume we'll report a warning when converting the arguments to the inferred parameter types. // (For instance, with F<T>(T x, T y, IIn<T> z) and interface IIn<in T> and interface IIOut<out T>, the // call F(IOut<object?>, IOut<object!>, IIn<IOut<object!>>) should find a nullability mismatch. Instead, // we'll merge the lower bounds IOut<object?> with IOut<object!> (using VarianceKind.Out) to produce // IOut<object?>, then merge that result with upper bound IOut<object!> (using VarianceKind.In) // to produce IOut<object?>. But then conversion of argument IIn<IOut<object!>> to parameter // IIn<IOut<object?>> will generate a warning at that point.) TypeWithAnnotations merged = latest.MergeEquivalentTypes(newCandidate, variance); candidates[oldCandidate] = merged; } } /// <summary> /// This is a comparer that ignores differences in dynamic-ness and tuple names. /// But it has a special case for top-level object vs. dynamic for purpose of method type inference. /// </summary> private sealed class EqualsIgnoringDynamicTupleNamesAndNullabilityComparer : EqualityComparer<TypeWithAnnotations> { internal static readonly EqualsIgnoringDynamicTupleNamesAndNullabilityComparer Instance = new EqualsIgnoringDynamicTupleNamesAndNullabilityComparer(); public override int GetHashCode(TypeWithAnnotations obj) { return obj.Type.GetHashCode(); } public override bool Equals(TypeWithAnnotations x, TypeWithAnnotations y) { // We do a equality test ignoring dynamic and tuple names differences, // but dynamic and object are not considered equal for backwards compatibility. if (x.Type.IsDynamic() ^ y.Type.IsDynamic()) { return false; } return x.Equals(y, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes); } } } }
1
dotnet/roslyn
56,416
Do not include function type conversions in user-defined conversions
Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
cston
"2021-09-15T18:16:38Z"
"2021-09-24T23:24:46Z"
bb99d0bc89bde01650d2a694d720d600dd952dcb
3913f352cf066fa485869d866e4753fa721cbe93
Do not include function type conversions in user-defined conversions. Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
./src/Compilers/CSharp/Portable/Binder/UsingStatementBinder.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal sealed class UsingStatementBinder : LockOrUsingBinder { private readonly UsingStatementSyntax _syntax; public UsingStatementBinder(Binder enclosing, UsingStatementSyntax syntax) : base(enclosing) { _syntax = syntax; } protected override ImmutableArray<LocalSymbol> BuildLocals() { ExpressionSyntax expressionSyntax = TargetExpressionSyntax; VariableDeclarationSyntax declarationSyntax = _syntax.Declaration; Debug.Assert((expressionSyntax == null) ^ (declarationSyntax == null)); // Can't have both or neither. if (expressionSyntax != null) { var locals = ArrayBuilder<LocalSymbol>.GetInstance(); ExpressionVariableFinder.FindExpressionVariables(this, locals, expressionSyntax); return locals.ToImmutableAndFree(); } else { var locals = ArrayBuilder<LocalSymbol>.GetInstance(declarationSyntax.Variables.Count); // gather expression-declared variables from invalid array dimensions. eg. using(int[x is var y] z = new int[0]) declarationSyntax.Type.VisitRankSpecifiers((rankSpecifier, args) => { foreach (var size in rankSpecifier.Sizes) { if (size.Kind() != SyntaxKind.OmittedArraySizeExpression) { ExpressionVariableFinder.FindExpressionVariables(args.binder, args.locals, size); } } }, (binder: this, locals: locals)); foreach (VariableDeclaratorSyntax declarator in declarationSyntax.Variables) { locals.Add(MakeLocal(declarationSyntax, declarator, LocalDeclarationKind.UsingVariable)); // also gather expression-declared variables from the bracketed argument lists and the initializers ExpressionVariableFinder.FindExpressionVariables(this, locals, declarator); } return locals.ToImmutableAndFree(); } } protected override ExpressionSyntax TargetExpressionSyntax { get { return _syntax.Expression; } } internal override BoundStatement BindUsingStatementParts(BindingDiagnosticBag diagnostics, Binder originalBinder) { ExpressionSyntax expressionSyntax = TargetExpressionSyntax; VariableDeclarationSyntax declarationSyntax = _syntax.Declaration; bool hasAwait = _syntax.AwaitKeyword.Kind() != default; Debug.Assert((expressionSyntax == null) ^ (declarationSyntax == null)); // Can't have both or neither. var boundUsingStatement = BindUsingStatementOrDeclarationFromParts((CSharpSyntaxNode)expressionSyntax ?? declarationSyntax, _syntax.UsingKeyword, _syntax.AwaitKeyword, originalBinder, this, diagnostics); Debug.Assert(boundUsingStatement is BoundUsingStatement); return boundUsingStatement; } #nullable enable internal static BoundStatement BindUsingStatementOrDeclarationFromParts(SyntaxNode syntax, SyntaxToken usingKeyword, SyntaxToken awaitKeyword, Binder originalBinder, UsingStatementBinder? usingBinderOpt, BindingDiagnosticBag diagnostics) { bool isUsingDeclaration = syntax.Kind() == SyntaxKind.LocalDeclarationStatement; bool isExpression = !isUsingDeclaration && syntax.Kind() != SyntaxKind.VariableDeclaration; bool hasAwait = awaitKeyword != default; Debug.Assert(isUsingDeclaration || usingBinderOpt != null); TypeSymbol disposableInterface = getDisposableInterface(hasAwait); Debug.Assert((object)disposableInterface != null); bool hasErrors = ReportUseSite(disposableInterface, diagnostics, hasAwait ? awaitKeyword : usingKeyword); Conversion iDisposableConversion; ImmutableArray<BoundLocalDeclaration> declarationsOpt = default; BoundMultipleLocalDeclarations? multipleDeclarationsOpt = null; BoundExpression? expressionOpt = null; TypeSymbol? declarationTypeOpt = null; MethodArgumentInfo? patternDisposeInfo; TypeSymbol? awaitableTypeOpt; if (isExpression) { expressionOpt = usingBinderOpt!.BindTargetExpression(diagnostics, originalBinder); hasErrors |= !populateDisposableConversionOrDisposeMethod(fromExpression: true, out iDisposableConversion, out patternDisposeInfo, out awaitableTypeOpt); } else { VariableDeclarationSyntax declarationSyntax = isUsingDeclaration ? ((LocalDeclarationStatementSyntax)syntax).Declaration : (VariableDeclarationSyntax)syntax; originalBinder.BindForOrUsingOrFixedDeclarations(declarationSyntax, LocalDeclarationKind.UsingVariable, diagnostics, out declarationsOpt); Debug.Assert(!declarationsOpt.IsEmpty && declarationsOpt[0].DeclaredTypeOpt != null); multipleDeclarationsOpt = new BoundMultipleLocalDeclarations(declarationSyntax, declarationsOpt); declarationTypeOpt = declarationsOpt[0].DeclaredTypeOpt!.Type; if (declarationTypeOpt.IsDynamic()) { iDisposableConversion = Conversion.ImplicitDynamic; patternDisposeInfo = null; awaitableTypeOpt = null; } else { hasErrors |= !populateDisposableConversionOrDisposeMethod(fromExpression: false, out iDisposableConversion, out patternDisposeInfo, out awaitableTypeOpt); } } BoundAwaitableInfo? awaitOpt = null; if (hasAwait) { // even if we don't have a proper value to await, we'll still report bad usages of `await` originalBinder.ReportBadAwaitDiagnostics(syntax, awaitKeyword.GetLocation(), diagnostics, ref hasErrors); if (awaitableTypeOpt is null) { awaitOpt = new BoundAwaitableInfo(syntax, awaitableInstancePlaceholder: null, isDynamic: true, getAwaiter: null, isCompleted: null, getResult: null) { WasCompilerGenerated = true }; } else { hasErrors |= ReportUseSite(awaitableTypeOpt, diagnostics, awaitKeyword); var placeholder = new BoundAwaitableValuePlaceholder(syntax, valEscape: originalBinder.LocalScopeDepth, awaitableTypeOpt).MakeCompilerGenerated(); awaitOpt = originalBinder.BindAwaitInfo(placeholder, syntax, diagnostics, ref hasErrors); } } // This is not awesome, but its factored. // In the future it might be better to have a separate shared type that we add the info to, and have the callers create the appropriate bound nodes from it if (isUsingDeclaration) { return new BoundUsingLocalDeclarations(syntax, patternDisposeInfo, iDisposableConversion, awaitOpt, declarationsOpt, hasErrors); } else { BoundStatement boundBody = originalBinder.BindPossibleEmbeddedStatement(usingBinderOpt!._syntax.Statement, diagnostics); return new BoundUsingStatement( usingBinderOpt._syntax, usingBinderOpt.Locals, multipleDeclarationsOpt, expressionOpt, iDisposableConversion, boundBody, awaitOpt, patternDisposeInfo, hasErrors); } bool populateDisposableConversionOrDisposeMethod(bool fromExpression, out Conversion iDisposableConversion, out MethodArgumentInfo? patternDisposeInfo, out TypeSymbol? awaitableType) { CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = originalBinder.GetNewCompoundUseSiteInfo(diagnostics); iDisposableConversion = classifyConversion(fromExpression, disposableInterface, ref useSiteInfo); patternDisposeInfo = null; awaitableType = null; diagnostics.Add(syntax, useSiteInfo); if (iDisposableConversion.IsImplicit) { if (hasAwait) { awaitableType = originalBinder.Compilation.GetWellKnownType(WellKnownType.System_Threading_Tasks_ValueTask); } return true; } Debug.Assert(!fromExpression || expressionOpt != null); TypeSymbol? type = fromExpression ? expressionOpt!.Type : declarationTypeOpt; // If this is a ref struct, or we're in a valid asynchronous using, try binding via pattern. // We won't need to try and bind a second time if it fails, as async dispose can't be pattern based (ref structs are not allowed in async methods) if (type is object && (type.IsRefLikeType || hasAwait)) { BoundExpression? receiver = fromExpression ? expressionOpt : new BoundLocal(syntax, declarationsOpt[0].LocalSymbol, null, type) { WasCompilerGenerated = true }; BindingDiagnosticBag patternDiagnostics = originalBinder.Compilation.IsFeatureEnabled(MessageID.IDS_FeatureUsingDeclarations) ? diagnostics : BindingDiagnosticBag.Discarded; MethodSymbol disposeMethod = originalBinder.TryFindDisposePatternMethod(receiver, syntax, hasAwait, patternDiagnostics); if (disposeMethod is object) { MessageID.IDS_FeatureUsingDeclarations.CheckFeatureAvailability(diagnostics, originalBinder.Compilation, syntax.Location); var argumentsBuilder = ArrayBuilder<BoundExpression>.GetInstance(disposeMethod.ParameterCount); ImmutableArray<int> argsToParams = default; bool expanded = disposeMethod.HasParamsParameter(); originalBinder.BindDefaultArguments( // If this is a using statement, then we want to use the whole `using (expr) { }` as the argument location. These arguments // will be represented in the IOperation tree and the "correct" node for them, given that they are an implicit invocation // at the end of the using statement, is on the whole using statement, not on the current expression. usingBinderOpt?._syntax ?? syntax, disposeMethod.Parameters, argumentsBuilder, argumentRefKindsBuilder: null, ref argsToParams, out BitVector defaultArguments, expanded, enableCallerInfo: true, patternDiagnostics); patternDisposeInfo = new MethodArgumentInfo(disposeMethod, argumentsBuilder.ToImmutableAndFree(), argsToParams, defaultArguments, expanded); if (hasAwait) { awaitableType = disposeMethod.ReturnType; } return true; } } if (type is null || !type.IsErrorType()) { // Retry with a different assumption about whether the `using` is async TypeSymbol alternateInterface = getDisposableInterface(!hasAwait); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; Conversion alternateConversion = classifyConversion(fromExpression, alternateInterface, ref discardedUseSiteInfo); bool wrongAsync = alternateConversion.IsImplicit; ErrorCode errorCode = wrongAsync ? (hasAwait ? ErrorCode.ERR_NoConvToIAsyncDispWrongAsync : ErrorCode.ERR_NoConvToIDispWrongAsync) : (hasAwait ? ErrorCode.ERR_NoConvToIAsyncDisp : ErrorCode.ERR_NoConvToIDisp); Error(diagnostics, errorCode, syntax, declarationTypeOpt ?? expressionOpt!.Display); } return false; } Conversion classifyConversion(bool fromExpression, TypeSymbol targetInterface, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { return fromExpression ? originalBinder.Conversions.ClassifyImplicitConversionFromExpression(expressionOpt, targetInterface, ref useSiteInfo) : originalBinder.Conversions.ClassifyImplicitConversionFromType(declarationTypeOpt, targetInterface, ref useSiteInfo); } TypeSymbol getDisposableInterface(bool isAsync) { return isAsync ? originalBinder.Compilation.GetWellKnownType(WellKnownType.System_IAsyncDisposable) : originalBinder.Compilation.GetSpecialType(SpecialType.System_IDisposable); } } internal override ImmutableArray<LocalSymbol> GetDeclaredLocalsForScope(SyntaxNode scopeDesignator) { if (_syntax == scopeDesignator) { return this.Locals; } throw ExceptionUtilities.Unreachable; } internal override ImmutableArray<LocalFunctionSymbol> GetDeclaredLocalFunctionsForScope(CSharpSyntaxNode scopeDesignator) { throw ExceptionUtilities.Unreachable; } internal override SyntaxNode ScopeDesignator { get { return _syntax; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal sealed class UsingStatementBinder : LockOrUsingBinder { private readonly UsingStatementSyntax _syntax; public UsingStatementBinder(Binder enclosing, UsingStatementSyntax syntax) : base(enclosing) { _syntax = syntax; } protected override ImmutableArray<LocalSymbol> BuildLocals() { ExpressionSyntax expressionSyntax = TargetExpressionSyntax; VariableDeclarationSyntax declarationSyntax = _syntax.Declaration; Debug.Assert((expressionSyntax == null) ^ (declarationSyntax == null)); // Can't have both or neither. if (expressionSyntax != null) { var locals = ArrayBuilder<LocalSymbol>.GetInstance(); ExpressionVariableFinder.FindExpressionVariables(this, locals, expressionSyntax); return locals.ToImmutableAndFree(); } else { var locals = ArrayBuilder<LocalSymbol>.GetInstance(declarationSyntax.Variables.Count); // gather expression-declared variables from invalid array dimensions. eg. using(int[x is var y] z = new int[0]) declarationSyntax.Type.VisitRankSpecifiers((rankSpecifier, args) => { foreach (var size in rankSpecifier.Sizes) { if (size.Kind() != SyntaxKind.OmittedArraySizeExpression) { ExpressionVariableFinder.FindExpressionVariables(args.binder, args.locals, size); } } }, (binder: this, locals: locals)); foreach (VariableDeclaratorSyntax declarator in declarationSyntax.Variables) { locals.Add(MakeLocal(declarationSyntax, declarator, LocalDeclarationKind.UsingVariable)); // also gather expression-declared variables from the bracketed argument lists and the initializers ExpressionVariableFinder.FindExpressionVariables(this, locals, declarator); } return locals.ToImmutableAndFree(); } } protected override ExpressionSyntax TargetExpressionSyntax { get { return _syntax.Expression; } } internal override BoundStatement BindUsingStatementParts(BindingDiagnosticBag diagnostics, Binder originalBinder) { ExpressionSyntax expressionSyntax = TargetExpressionSyntax; VariableDeclarationSyntax declarationSyntax = _syntax.Declaration; bool hasAwait = _syntax.AwaitKeyword.Kind() != default; Debug.Assert((expressionSyntax == null) ^ (declarationSyntax == null)); // Can't have both or neither. var boundUsingStatement = BindUsingStatementOrDeclarationFromParts((CSharpSyntaxNode)expressionSyntax ?? declarationSyntax, _syntax.UsingKeyword, _syntax.AwaitKeyword, originalBinder, this, diagnostics); Debug.Assert(boundUsingStatement is BoundUsingStatement); return boundUsingStatement; } #nullable enable internal static BoundStatement BindUsingStatementOrDeclarationFromParts(SyntaxNode syntax, SyntaxToken usingKeyword, SyntaxToken awaitKeyword, Binder originalBinder, UsingStatementBinder? usingBinderOpt, BindingDiagnosticBag diagnostics) { bool isUsingDeclaration = syntax.Kind() == SyntaxKind.LocalDeclarationStatement; bool isExpression = !isUsingDeclaration && syntax.Kind() != SyntaxKind.VariableDeclaration; bool hasAwait = awaitKeyword != default; Debug.Assert(isUsingDeclaration || usingBinderOpt != null); TypeSymbol disposableInterface = getDisposableInterface(hasAwait); Debug.Assert((object)disposableInterface != null); bool hasErrors = ReportUseSite(disposableInterface, diagnostics, hasAwait ? awaitKeyword : usingKeyword); Conversion iDisposableConversion; ImmutableArray<BoundLocalDeclaration> declarationsOpt = default; BoundMultipleLocalDeclarations? multipleDeclarationsOpt = null; BoundExpression? expressionOpt = null; TypeSymbol? declarationTypeOpt = null; MethodArgumentInfo? patternDisposeInfo; TypeSymbol? awaitableTypeOpt; if (isExpression) { expressionOpt = usingBinderOpt!.BindTargetExpression(diagnostics, originalBinder); hasErrors |= !populateDisposableConversionOrDisposeMethod(fromExpression: true, out iDisposableConversion, out patternDisposeInfo, out awaitableTypeOpt); } else { VariableDeclarationSyntax declarationSyntax = isUsingDeclaration ? ((LocalDeclarationStatementSyntax)syntax).Declaration : (VariableDeclarationSyntax)syntax; originalBinder.BindForOrUsingOrFixedDeclarations(declarationSyntax, LocalDeclarationKind.UsingVariable, diagnostics, out declarationsOpt); Debug.Assert(!declarationsOpt.IsEmpty && declarationsOpt[0].DeclaredTypeOpt != null); multipleDeclarationsOpt = new BoundMultipleLocalDeclarations(declarationSyntax, declarationsOpt); declarationTypeOpt = declarationsOpt[0].DeclaredTypeOpt!.Type; if (declarationTypeOpt.IsDynamic()) { iDisposableConversion = Conversion.ImplicitDynamic; patternDisposeInfo = null; awaitableTypeOpt = null; } else { hasErrors |= !populateDisposableConversionOrDisposeMethod(fromExpression: false, out iDisposableConversion, out patternDisposeInfo, out awaitableTypeOpt); } } BoundAwaitableInfo? awaitOpt = null; if (hasAwait) { // even if we don't have a proper value to await, we'll still report bad usages of `await` originalBinder.ReportBadAwaitDiagnostics(syntax, awaitKeyword.GetLocation(), diagnostics, ref hasErrors); if (awaitableTypeOpt is null) { awaitOpt = new BoundAwaitableInfo(syntax, awaitableInstancePlaceholder: null, isDynamic: true, getAwaiter: null, isCompleted: null, getResult: null) { WasCompilerGenerated = true }; } else { hasErrors |= ReportUseSite(awaitableTypeOpt, diagnostics, awaitKeyword); var placeholder = new BoundAwaitableValuePlaceholder(syntax, valEscape: originalBinder.LocalScopeDepth, awaitableTypeOpt).MakeCompilerGenerated(); awaitOpt = originalBinder.BindAwaitInfo(placeholder, syntax, diagnostics, ref hasErrors); } } // This is not awesome, but its factored. // In the future it might be better to have a separate shared type that we add the info to, and have the callers create the appropriate bound nodes from it if (isUsingDeclaration) { return new BoundUsingLocalDeclarations(syntax, patternDisposeInfo, iDisposableConversion, awaitOpt, declarationsOpt, hasErrors); } else { BoundStatement boundBody = originalBinder.BindPossibleEmbeddedStatement(usingBinderOpt!._syntax.Statement, diagnostics); return new BoundUsingStatement( usingBinderOpt._syntax, usingBinderOpt.Locals, multipleDeclarationsOpt, expressionOpt, iDisposableConversion, boundBody, awaitOpt, patternDisposeInfo, hasErrors); } bool populateDisposableConversionOrDisposeMethod(bool fromExpression, out Conversion iDisposableConversion, out MethodArgumentInfo? patternDisposeInfo, out TypeSymbol? awaitableType) { CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = originalBinder.GetNewCompoundUseSiteInfo(diagnostics); iDisposableConversion = classifyConversion(fromExpression, disposableInterface, ref useSiteInfo); patternDisposeInfo = null; awaitableType = null; diagnostics.Add(syntax, useSiteInfo); if (iDisposableConversion.IsImplicit) { if (hasAwait) { awaitableType = originalBinder.Compilation.GetWellKnownType(WellKnownType.System_Threading_Tasks_ValueTask); } return true; } Debug.Assert(!fromExpression || expressionOpt != null); TypeSymbol? type = fromExpression ? expressionOpt!.Type : declarationTypeOpt; // If this is a ref struct, or we're in a valid asynchronous using, try binding via pattern. // We won't need to try and bind a second time if it fails, as async dispose can't be pattern based (ref structs are not allowed in async methods) if (type is object && (type.IsRefLikeType || hasAwait)) { BoundExpression? receiver = fromExpression ? expressionOpt : new BoundLocal(syntax, declarationsOpt[0].LocalSymbol, null, type) { WasCompilerGenerated = true }; BindingDiagnosticBag patternDiagnostics = originalBinder.Compilation.IsFeatureEnabled(MessageID.IDS_FeatureUsingDeclarations) ? diagnostics : BindingDiagnosticBag.Discarded; MethodSymbol disposeMethod = originalBinder.TryFindDisposePatternMethod(receiver, syntax, hasAwait, patternDiagnostics); if (disposeMethod is object) { MessageID.IDS_FeatureUsingDeclarations.CheckFeatureAvailability(diagnostics, originalBinder.Compilation, syntax.Location); var argumentsBuilder = ArrayBuilder<BoundExpression>.GetInstance(disposeMethod.ParameterCount); ImmutableArray<int> argsToParams = default; bool expanded = disposeMethod.HasParamsParameter(); originalBinder.BindDefaultArguments( // If this is a using statement, then we want to use the whole `using (expr) { }` as the argument location. These arguments // will be represented in the IOperation tree and the "correct" node for them, given that they are an implicit invocation // at the end of the using statement, is on the whole using statement, not on the current expression. usingBinderOpt?._syntax ?? syntax, disposeMethod.Parameters, argumentsBuilder, argumentRefKindsBuilder: null, ref argsToParams, out BitVector defaultArguments, expanded, enableCallerInfo: true, patternDiagnostics); patternDisposeInfo = new MethodArgumentInfo(disposeMethod, argumentsBuilder.ToImmutableAndFree(), argsToParams, defaultArguments, expanded); if (hasAwait) { awaitableType = disposeMethod.ReturnType; } return true; } } if (type is null || !type.IsErrorType()) { // Retry with a different assumption about whether the `using` is async TypeSymbol alternateInterface = getDisposableInterface(!hasAwait); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; Conversion alternateConversion = classifyConversion(fromExpression, alternateInterface, ref discardedUseSiteInfo); bool wrongAsync = alternateConversion.IsImplicit; ErrorCode errorCode = wrongAsync ? (hasAwait ? ErrorCode.ERR_NoConvToIAsyncDispWrongAsync : ErrorCode.ERR_NoConvToIDispWrongAsync) : (hasAwait ? ErrorCode.ERR_NoConvToIAsyncDisp : ErrorCode.ERR_NoConvToIDisp); Error(diagnostics, errorCode, syntax, declarationTypeOpt ?? expressionOpt!.Display); } return false; } Conversion classifyConversion(bool fromExpression, TypeSymbol targetInterface, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var conversions = originalBinder.Conversions; if (fromExpression) { Debug.Assert(expressionOpt is { }); return conversions.ClassifyImplicitConversionFromExpression(expressionOpt, targetInterface, ref useSiteInfo); } else { Debug.Assert(declarationTypeOpt is { }); return conversions.ClassifyImplicitConversionFromType(declarationTypeOpt, targetInterface, ref useSiteInfo); } } TypeSymbol getDisposableInterface(bool isAsync) { return isAsync ? originalBinder.Compilation.GetWellKnownType(WellKnownType.System_IAsyncDisposable) : originalBinder.Compilation.GetSpecialType(SpecialType.System_IDisposable); } } internal override ImmutableArray<LocalSymbol> GetDeclaredLocalsForScope(SyntaxNode scopeDesignator) { if (_syntax == scopeDesignator) { return this.Locals; } throw ExceptionUtilities.Unreachable; } internal override ImmutableArray<LocalFunctionSymbol> GetDeclaredLocalFunctionsForScope(CSharpSyntaxNode scopeDesignator) { throw ExceptionUtilities.Unreachable; } internal override SyntaxNode ScopeDesignator { get { return _syntax; } } } }
1
dotnet/roslyn
56,416
Do not include function type conversions in user-defined conversions
Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
cston
"2021-09-15T18:16:38Z"
"2021-09-24T23:24:46Z"
bb99d0bc89bde01650d2a694d720d600dd952dcb
3913f352cf066fa485869d866e4753fa721cbe93
Do not include function type conversions in user-defined conversions. Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
./src/Compilers/CSharp/Portable/FlowAnalysis/NullableWalker.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// Nullability flow analysis. /// </summary> [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] internal sealed partial class NullableWalker : LocalDataFlowPass<NullableWalker.LocalState, NullableWalker.LocalFunctionState> { /// <summary> /// Used to copy variable slots and types from the NullableWalker for the containing method /// or lambda to the NullableWalker created for a nested lambda or local function. /// </summary> internal sealed class VariableState { // Consider referencing the Variables instance directly from the original NullableWalker // rather than cloning. (Items are added to the collections but never replaced so the // collections are lazily populated but otherwise immutable. We'd probably want a // clone when analyzing from speculative semantic model though.) internal readonly VariablesSnapshot Variables; // The nullable state of all variables captured at the point where the function or lambda appeared. internal readonly LocalStateSnapshot VariableNullableStates; internal VariableState(VariablesSnapshot variables, LocalStateSnapshot variableNullableStates) { Variables = variables; VariableNullableStates = variableNullableStates; } } /// <summary> /// Data recorded for a particular analysis run. /// </summary> internal readonly struct Data { /// <summary> /// Number of entries tracked during analysis. /// </summary> internal readonly int TrackedEntries; /// <summary> /// True if analysis was required; false if analysis was optional and results dropped. /// </summary> internal readonly bool RequiredAnalysis; internal Data(int trackedEntries, bool requiredAnalysis) { TrackedEntries = trackedEntries; RequiredAnalysis = requiredAnalysis; } } /// <summary> /// Represents the result of visiting an expression. /// Contains a result type which tells us whether the expression may be null, /// and an l-value type which tells us whether we can assign null to the expression. /// </summary> [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] private readonly struct VisitResult { public readonly TypeWithState RValueType; public readonly TypeWithAnnotations LValueType; public VisitResult(TypeWithState rValueType, TypeWithAnnotations lValueType) { RValueType = rValueType; LValueType = lValueType; // https://github.com/dotnet/roslyn/issues/34993: Doesn't hold true for Tuple_Assignment_10. See if we can make it hold true //Debug.Assert((RValueType.Type is null && LValueType.TypeSymbol is null) || // RValueType.Type.Equals(LValueType.TypeSymbol, TypeCompareKind.ConsiderEverything | TypeCompareKind.AllIgnoreOptions)); } public VisitResult(TypeSymbol? type, NullableAnnotation annotation, NullableFlowState state) { RValueType = TypeWithState.Create(type, state); LValueType = TypeWithAnnotations.Create(type, annotation); Debug.Assert(TypeSymbol.Equals(RValueType.Type, LValueType.Type, TypeCompareKind.ConsiderEverything)); } internal string GetDebuggerDisplay() => $"{{LValue: {LValueType.GetDebuggerDisplay()}, RValue: {RValueType.GetDebuggerDisplay()}}}"; } /// <summary> /// Represents the result of visiting an argument expression. /// In addition to storing the <see cref="VisitResult"/>, also stores the <see cref="LocalState"/> /// for reanalyzing a lambda. /// </summary> [DebuggerDisplay("{VisitResult.GetDebuggerDisplay(), nq}")] private readonly struct VisitArgumentResult { public readonly VisitResult VisitResult; public readonly Optional<LocalState> StateForLambda; public TypeWithState RValueType => VisitResult.RValueType; public TypeWithAnnotations LValueType => VisitResult.LValueType; public VisitArgumentResult(VisitResult visitResult, Optional<LocalState> stateForLambda) { VisitResult = visitResult; StateForLambda = stateForLambda; } } private Variables _variables; /// <summary> /// Binder for symbol being analyzed. /// </summary> private readonly Binder _binder; /// <summary> /// Conversions with nullability and unknown matching any. /// </summary> private readonly Conversions _conversions; /// <summary> /// 'true' if non-nullable member warnings should be issued at return points. /// One situation where this is 'false' is when we are analyzing field initializers and there is a constructor symbol in the type. /// </summary> private readonly bool _useConstructorExitWarnings; /// <summary> /// If true, the parameter types and nullability from _delegateInvokeMethod is used for /// initial parameter state. If false, the signature of CurrentSymbol is used instead. /// </summary> private bool _useDelegateInvokeParameterTypes; /// <summary> /// If true, the return type and nullability from _delegateInvokeMethod is used. /// If false, the signature of CurrentSymbol is used instead. /// </summary> private bool _useDelegateInvokeReturnType; /// <summary> /// Method signature used for return or parameter types. Distinct from CurrentSymbol signature /// when CurrentSymbol is a lambda and type is inferred from MethodTypeInferrer. /// </summary> private MethodSymbol? _delegateInvokeMethod; /// <summary> /// Return statements and the result types from analyzing the returned expressions. Used when inferring lambda return type in MethodTypeInferrer. /// </summary> private ArrayBuilder<(BoundReturnStatement, TypeWithAnnotations)>? _returnTypesOpt; /// <summary> /// Invalid type, used only to catch Visit methods that do not set /// _result.Type. See VisitExpressionWithoutStackGuard. /// </summary> private static readonly TypeWithState _invalidType = TypeWithState.Create(ErrorTypeSymbol.UnknownResultType, NullableFlowState.NotNull); /// <summary> /// Contains the map of expressions to inferred nullabilities and types used by the optional rewriter phase of the /// compiler. /// </summary> private readonly ImmutableDictionary<BoundExpression, (NullabilityInfo Info, TypeSymbol? Type)>.Builder? _analyzedNullabilityMapOpt; /// <summary> /// Manages creating snapshots of the walker as appropriate. Null if we're not taking snapshots of /// this walker. /// </summary> private readonly SnapshotManager.Builder? _snapshotBuilderOpt; // https://github.com/dotnet/roslyn/issues/35043: remove this when all expression are supported private bool _disableNullabilityAnalysis; /// <summary> /// State of method group receivers, used later when analyzing the conversion to a delegate. /// (Could be replaced by _analyzedNullabilityMapOpt if that map is always available.) /// </summary> private PooledDictionary<BoundExpression, TypeWithState>? _methodGroupReceiverMapOpt; /// <summary> /// State of awaitable expressions, for substitution in placeholders within GetAwaiter calls. /// </summary> private PooledDictionary<BoundAwaitableValuePlaceholder, (BoundExpression AwaitableExpression, VisitResult Result)>? _awaitablePlaceholdersOpt; /// <summary> /// Variables instances for each lambda or local function defined within the analyzed region. /// </summary> private PooledDictionary<MethodSymbol, Variables>? _nestedFunctionVariables; private PooledDictionary<BoundExpression, ImmutableArray<(LocalState State, TypeWithState ResultType, bool EndReachable)>>? _conditionalInfoForConversionOpt; /// <summary> /// Map from a target-typed conditional expression (such as a target-typed conditional or switch) to the nullable state on each branch. This /// is then used by VisitConversion to properly set the state before each branch when visiting a conversion applied to such a construct. These /// states will be the state after visiting the underlying arm value, but before visiting the conversion on top of the arm value. /// </summary> private PooledDictionary<BoundExpression, ImmutableArray<(LocalState State, TypeWithState ResultType, bool EndReachable)>> ConditionalInfoForConversion => _conditionalInfoForConversionOpt ??= PooledDictionary<BoundExpression, ImmutableArray<(LocalState, TypeWithState, bool)>>.GetInstance(); /// <summary> /// True if we're analyzing speculative code. This turns off some initialization steps /// that would otherwise be taken. /// </summary> private readonly bool _isSpeculative; /// <summary> /// True if this walker was created using an initial state. /// </summary> private readonly bool _hasInitialState; #if DEBUG /// <summary> /// Contains the expressions that should not be inserted into <see cref="_analyzedNullabilityMapOpt"/>. /// </summary> private static readonly ImmutableArray<BoundKind> s_skippedExpressions = ImmutableArray.Create(BoundKind.ArrayInitialization, BoundKind.ObjectInitializerExpression, BoundKind.CollectionInitializerExpression, BoundKind.DynamicCollectionElementInitializer); #endif /// <summary> /// The result and l-value type of the last visited expression. /// </summary> private VisitResult _visitResult; /// <summary> /// The visit result of the receiver for the current conditional access. /// /// For example: A conditional invocation uses a placeholder as a receiver. By storing the /// visit result from the actual receiver ahead of time, we can give this placeholder a correct result. /// </summary> private VisitResult _currentConditionalReceiverVisitResult; /// <summary> /// The result type represents the state of the last visited expression. /// </summary> private TypeWithState ResultType { get => _visitResult.RValueType; } private void SetResultType(BoundExpression? expression, TypeWithState type, bool updateAnalyzedNullability = true) { SetResult(expression, resultType: type, lvalueType: type.ToTypeWithAnnotations(compilation), updateAnalyzedNullability: updateAnalyzedNullability); } /// <summary> /// Force the inference of the LValueResultType from ResultType. /// </summary> private void UseRvalueOnly(BoundExpression? expression) { SetResult(expression, ResultType, ResultType.ToTypeWithAnnotations(compilation), isLvalue: false); } private TypeWithAnnotations LvalueResultType { get => _visitResult.LValueType; } private void SetLvalueResultType(BoundExpression? expression, TypeWithAnnotations type) { SetResult(expression, resultType: type.ToTypeWithState(), lvalueType: type); } /// <summary> /// Force the inference of the ResultType from LValueResultType. /// </summary> private void UseLvalueOnly(BoundExpression? expression) { SetResult(expression, LvalueResultType.ToTypeWithState(), LvalueResultType, isLvalue: true); } private void SetInvalidResult() => SetResult(expression: null, _invalidType, _invalidType.ToTypeWithAnnotations(compilation), updateAnalyzedNullability: false); private void SetResult(BoundExpression? expression, TypeWithState resultType, TypeWithAnnotations lvalueType, bool updateAnalyzedNullability = true, bool? isLvalue = null) { _visitResult = new VisitResult(resultType, lvalueType); if (updateAnalyzedNullability) { SetAnalyzedNullability(expression, _visitResult, isLvalue); } } private bool ShouldMakeNotNullRvalue(BoundExpression node) => node.IsSuppressed || node.HasAnyErrors || !IsReachable(); /// <summary> /// Sets the analyzed nullability of the expression to be the given result. /// </summary> private void SetAnalyzedNullability(BoundExpression? expr, VisitResult result, bool? isLvalue = null) { if (expr == null || _disableNullabilityAnalysis) return; #if DEBUG // https://github.com/dotnet/roslyn/issues/34993: This assert is essential for ensuring that we aren't // changing the observable results of GetTypeInfo beyond nullability information. //Debug.Assert(AreCloseEnough(expr.Type, result.RValueType.Type), // $"Cannot change the type of {expr} from {expr.Type} to {result.RValueType.Type}"); #endif if (_analyzedNullabilityMapOpt != null) { // https://github.com/dotnet/roslyn/issues/34993: enable and verify these assertions #if false if (_analyzedNullabilityMapOpt.TryGetValue(expr, out var existing)) { if (!(result.RValueType.State == NullableFlowState.NotNull && ShouldMakeNotNullRvalue(expr, State.Reachable))) { switch (isLvalue) { case true: Debug.Assert(existing.Info.Annotation == result.LValueType.NullableAnnotation.ToPublicAnnotation(), $"Tried to update the nullability of {expr} from {existing.Info.Annotation} to {result.LValueType.NullableAnnotation}"); break; case false: Debug.Assert(existing.Info.FlowState == result.RValueType.State, $"Tried to update the nullability of {expr} from {existing.Info.FlowState} to {result.RValueType.State}"); break; case null: Debug.Assert(existing.Info.Equals((NullabilityInfo)result), $"Tried to update the nullability of {expr} from ({existing.Info.Annotation}, {existing.Info.FlowState}) to ({result.LValueType.NullableAnnotation}, {result.RValueType.State})"); break; } } } #endif _analyzedNullabilityMapOpt[expr] = (new NullabilityInfo(result.LValueType.ToPublicAnnotation(), result.RValueType.State.ToPublicFlowState()), // https://github.com/dotnet/roslyn/issues/35046 We're dropping the result if the type doesn't match up completely // with the existing type expr.Type?.Equals(result.RValueType.Type, TypeCompareKind.AllIgnoreOptions) == true ? result.RValueType.Type : expr.Type); } } /// <summary> /// Placeholder locals, e.g. for objects being constructed. /// </summary> private PooledDictionary<object, PlaceholderLocal>? _placeholderLocalsOpt; /// <summary> /// For methods with annotations, we'll need to visit the arguments twice. /// Once for diagnostics and once for result state (but disabling diagnostics). /// </summary> private bool _disableDiagnostics = false; /// <summary> /// Whether we are going to read the currently visited expression. /// </summary> private bool _expressionIsRead = true; /// <summary> /// Used to allow <see cref="MakeSlot(BoundExpression)"/> to substitute the correct slot for a <see cref="BoundConditionalReceiver"/> when /// it's encountered. /// </summary> private int _lastConditionalAccessSlot = -1; private bool IsAnalyzingAttribute => methodMainNode.Kind == BoundKind.Attribute; protected override void Free() { _nestedFunctionVariables?.Free(); _awaitablePlaceholdersOpt?.Free(); _methodGroupReceiverMapOpt?.Free(); _placeholderLocalsOpt?.Free(); _variables.Free(); Debug.Assert(_conditionalInfoForConversionOpt is null or { Count: 0 }); _conditionalInfoForConversionOpt?.Free(); base.Free(); } private NullableWalker( CSharpCompilation compilation, Symbol? symbol, bool useConstructorExitWarnings, bool useDelegateInvokeParameterTypes, bool useDelegateInvokeReturnType, MethodSymbol? delegateInvokeMethodOpt, BoundNode node, Binder binder, Conversions conversions, Variables? variables, ArrayBuilder<(BoundReturnStatement, TypeWithAnnotations)>? returnTypesOpt, ImmutableDictionary<BoundExpression, (NullabilityInfo, TypeSymbol?)>.Builder? analyzedNullabilityMapOpt, SnapshotManager.Builder? snapshotBuilderOpt, bool isSpeculative = false) : base(compilation, symbol, node, EmptyStructTypeCache.CreatePrecise(), trackUnassignments: true) { Debug.Assert(!useDelegateInvokeParameterTypes || delegateInvokeMethodOpt is object); _variables = variables ?? Variables.Create(symbol); _binder = binder; _conversions = (Conversions)conversions.WithNullability(true); _useConstructorExitWarnings = useConstructorExitWarnings; _useDelegateInvokeParameterTypes = useDelegateInvokeParameterTypes; _useDelegateInvokeReturnType = useDelegateInvokeReturnType; _delegateInvokeMethod = delegateInvokeMethodOpt; _analyzedNullabilityMapOpt = analyzedNullabilityMapOpt; _returnTypesOpt = returnTypesOpt; _snapshotBuilderOpt = snapshotBuilderOpt; _isSpeculative = isSpeculative; _hasInitialState = variables is { }; } public string GetDebuggerDisplay() { if (this.IsConditionalState) { return $"{{{GetType().Name} WhenTrue:{Dump(StateWhenTrue)} WhenFalse:{Dump(StateWhenFalse)}{"}"}"; } else { return $"{{{GetType().Name} {Dump(State)}{"}"}"; } } // For purpose of nullability analysis, awaits create pending branches, so async usings and foreachs do too public sealed override bool AwaitUsingAndForeachAddsPendingBranch => true; protected override void EnsureSufficientExecutionStack(int recursionDepth) { if (recursionDepth > StackGuard.MaxUncheckedRecursionDepth && compilation.NullableAnalysisData is { MaxRecursionDepth: var depth } && depth > 0 && recursionDepth > depth) { throw new InsufficientExecutionStackException(); } base.EnsureSufficientExecutionStack(recursionDepth); } protected override bool ConvertInsufficientExecutionStackExceptionToCancelledByStackGuardException() { return true; } protected override bool TryGetVariable(VariableIdentifier identifier, out int slot) { return _variables.TryGetValue(identifier, out slot); } protected override int AddVariable(VariableIdentifier identifier) { return _variables.Add(identifier); } protected override ImmutableArray<PendingBranch> Scan(ref bool badRegion) { if (_returnTypesOpt != null) { _returnTypesOpt.Clear(); } this.Diagnostics.Clear(); this.regionPlace = RegionPlace.Before; if (!_isSpeculative) { ParameterSymbol methodThisParameter = MethodThisParameter; EnterParameters(); // assign parameters if (methodThisParameter is object) { EnterParameter(methodThisParameter, methodThisParameter.TypeWithAnnotations); } makeNotNullMembersMaybeNull(); // We need to create a snapshot even of the first node, because we want to have the state of the initial parameters. _snapshotBuilderOpt?.TakeIncrementalSnapshot(methodMainNode, State); } ImmutableArray<PendingBranch> pendingReturns = base.Scan(ref badRegion); if ((_symbol as MethodSymbol)?.IsConstructor() != true || _useConstructorExitWarnings) { EnforceDoesNotReturn(syntaxOpt: null); enforceMemberNotNull(syntaxOpt: null, this.State); enforceNotNull(null, this.State); foreach (var pendingReturn in pendingReturns) { enforceMemberNotNull(syntaxOpt: pendingReturn.Branch.Syntax, pendingReturn.State); if (pendingReturn.Branch is BoundReturnStatement returnStatement) { enforceNotNull(returnStatement.Syntax, pendingReturn.State); enforceNotNullWhenForPendingReturn(pendingReturn, returnStatement); enforceMemberNotNullWhenForPendingReturn(pendingReturn, returnStatement); } } } return pendingReturns; void enforceMemberNotNull(SyntaxNode? syntaxOpt, LocalState state) { if (!state.Reachable) { return; } var method = _symbol as MethodSymbol; if (method is object) { if (method.IsConstructor()) { Debug.Assert(_useConstructorExitWarnings); var thisSlot = 0; if (method.RequiresInstanceReceiver) { method.TryGetThisParameter(out var thisParameter); Debug.Assert(thisParameter is object); thisSlot = GetOrCreateSlot(thisParameter); } // https://github.com/dotnet/roslyn/issues/46718: give diagnostics on return points, not constructor signature var exitLocation = method.DeclaringSyntaxReferences.IsEmpty ? null : method.Locations.FirstOrDefault(); foreach (var member in method.ContainingType.GetMembersUnordered()) { checkMemberStateOnConstructorExit(method, member, state, thisSlot, exitLocation); } } else { do { foreach (var memberName in method.NotNullMembers) { enforceMemberNotNullOnMember(syntaxOpt, state, method, memberName); } method = method.OverriddenMethod; } while (method != null); } } } void checkMemberStateOnConstructorExit(MethodSymbol constructor, Symbol member, LocalState state, int thisSlot, Location? exitLocation) { var isStatic = !constructor.RequiresInstanceReceiver(); if (member.IsStatic != isStatic) { return; } // This is not required for correctness, but in the case where the member has // an initializer, we know we've assigned to the member and // have given any applicable warnings about a bad value going in. // Therefore we skip this check when the member has an initializer to reduce noise. if (HasInitializer(member)) { return; } TypeWithAnnotations fieldType; FieldSymbol? field; Symbol symbol; switch (member) { case FieldSymbol f: fieldType = f.TypeWithAnnotations; field = f; symbol = (Symbol?)(f.AssociatedSymbol as PropertySymbol) ?? f; break; case EventSymbol e: fieldType = e.TypeWithAnnotations; field = e.AssociatedField; symbol = e; if (field is null) { return; } break; default: return; } if (field.IsConst) { return; } if (fieldType.Type.IsValueType || fieldType.Type.IsErrorType()) { return; } var annotations = symbol.GetFlowAnalysisAnnotations(); if ((annotations & FlowAnalysisAnnotations.AllowNull) != 0) { // We assume that if a member has AllowNull then the user // does not care that we exit at a point where the member might be null. return; } fieldType = ApplyUnconditionalAnnotations(fieldType, annotations); if (!fieldType.NullableAnnotation.IsNotAnnotated()) { return; } var slot = GetOrCreateSlot(symbol, thisSlot); if (slot < 0) { return; } var memberState = state[slot]; var badState = fieldType.Type.IsPossiblyNullableReferenceTypeTypeParameter() && (annotations & FlowAnalysisAnnotations.NotNull) == 0 ? NullableFlowState.MaybeDefault : NullableFlowState.MaybeNull; if (memberState >= badState) // is 'memberState' as bad as or worse than 'badState'? { Diagnostics.Add(ErrorCode.WRN_UninitializedNonNullableField, exitLocation ?? symbol.Locations.FirstOrNone(), symbol.Kind.Localize(), symbol.Name); } } void enforceMemberNotNullOnMember(SyntaxNode? syntaxOpt, LocalState state, MethodSymbol method, string memberName) { foreach (var member in method.ContainingType.GetMembers(memberName)) { if (memberHasBadState(member, state)) { // Member '{name}' must have a non-null value when exiting. Diagnostics.Add(ErrorCode.WRN_MemberNotNull, syntaxOpt?.GetLocation() ?? methodMainNode.Syntax.GetLastToken().GetLocation(), member.Name); } } } void enforceMemberNotNullWhenForPendingReturn(PendingBranch pendingReturn, BoundReturnStatement returnStatement) { if (pendingReturn.IsConditionalState) { if (returnStatement.ExpressionOpt is { ConstantValue: { IsBoolean: true, BooleanValue: bool value } }) { enforceMemberNotNullWhen(returnStatement.Syntax, sense: value, pendingReturn.State); return; } if (!pendingReturn.StateWhenTrue.Reachable || !pendingReturn.StateWhenFalse.Reachable) { return; } if (_symbol is MethodSymbol method) { foreach (var memberName in method.NotNullWhenTrueMembers) { enforceMemberNotNullWhenIfAffected(returnStatement.Syntax, sense: true, method.ContainingType.GetMembers(memberName), pendingReturn.StateWhenTrue, pendingReturn.StateWhenFalse); } foreach (var memberName in method.NotNullWhenFalseMembers) { enforceMemberNotNullWhenIfAffected(returnStatement.Syntax, sense: false, method.ContainingType.GetMembers(memberName), pendingReturn.StateWhenFalse, pendingReturn.StateWhenTrue); } } } else if (returnStatement.ExpressionOpt is { ConstantValue: { IsBoolean: true, BooleanValue: bool value } }) { enforceMemberNotNullWhen(returnStatement.Syntax, sense: value, pendingReturn.State); } } void enforceMemberNotNullWhenIfAffected(SyntaxNode? syntaxOpt, bool sense, ImmutableArray<Symbol> members, LocalState state, LocalState otherState) { foreach (var member in members) { // For non-constant values, only complain if we were able to analyze a difference for this member between two branches if (memberHasBadState(member, state) != memberHasBadState(member, otherState)) { reportMemberIfBadConditionalState(syntaxOpt, sense, member, state); } } } void enforceMemberNotNullWhen(SyntaxNode? syntaxOpt, bool sense, LocalState state) { if (_symbol is MethodSymbol method) { var notNullMembers = sense ? method.NotNullWhenTrueMembers : method.NotNullWhenFalseMembers; foreach (var memberName in notNullMembers) { foreach (var member in method.ContainingType.GetMembers(memberName)) { reportMemberIfBadConditionalState(syntaxOpt, sense, member, state); } } } } void reportMemberIfBadConditionalState(SyntaxNode? syntaxOpt, bool sense, Symbol member, LocalState state) { if (memberHasBadState(member, state)) { // Member '{name}' must have a non-null value when exiting with '{sense}'. Diagnostics.Add(ErrorCode.WRN_MemberNotNullWhen, syntaxOpt?.GetLocation() ?? methodMainNode.Syntax.GetLastToken().GetLocation(), member.Name, sense ? "true" : "false"); } } bool memberHasBadState(Symbol member, LocalState state) { switch (member.Kind) { case SymbolKind.Field: case SymbolKind.Property: if (getSlotForFieldOrPropertyOrEvent(member) is int memberSlot && memberSlot > 0) { var parameterState = state[memberSlot]; return !parameterState.IsNotNull(); } else { return false; } case SymbolKind.Event: case SymbolKind.Method: break; } return false; } void makeNotNullMembersMaybeNull() { if (_symbol is MethodSymbol method) { if (method.IsConstructor()) { if (needsDefaultInitialStateForMembers()) { foreach (var member in method.ContainingType.GetMembersUnordered()) { if (member.IsStatic != method.IsStatic) { continue; } var memberToInitialize = member; switch (member) { case PropertySymbol: // skip any manually implemented properties. continue; case FieldSymbol { IsConst: true }: continue; case FieldSymbol { AssociatedSymbol: PropertySymbol prop }: // this is a property where assigning 'default' causes us to simply update // the state to the output state of the property // thus we skip setting an initial state for it here if (IsPropertyOutputMoreStrictThanInput(prop)) { continue; } // We want to initialize auto-property state to the default state, but not computed properties. memberToInitialize = prop; break; default: break; } var memberSlot = getSlotForFieldOrPropertyOrEvent(memberToInitialize); if (memberSlot > 0) { var type = memberToInitialize.GetTypeOrReturnType(); if (!type.NullableAnnotation.IsOblivious()) { this.State[memberSlot] = type.Type.IsPossiblyNullableReferenceTypeTypeParameter() ? NullableFlowState.MaybeDefault : NullableFlowState.MaybeNull; } } } } } else { do { makeMembersMaybeNull(method, method.NotNullMembers); makeMembersMaybeNull(method, method.NotNullWhenTrueMembers); makeMembersMaybeNull(method, method.NotNullWhenFalseMembers); method = method.OverriddenMethod; } while (method != null); } } bool needsDefaultInitialStateForMembers() { if (_hasInitialState) { return false; } // We don't use a default initial state for value type instance constructors without `: this()` because // any usages of uninitialized fields will get definite assignment errors anyway. if (!method.HasThisConstructorInitializer(out _) && (!method.ContainingType.IsValueType || method.IsStatic)) { return true; } return method.IncludeFieldInitializersInBody(); } } void makeMembersMaybeNull(MethodSymbol method, ImmutableArray<string> members) { foreach (var memberName in members) { makeMemberMaybeNull(method, memberName); } } void makeMemberMaybeNull(MethodSymbol method, string memberName) { var type = method.ContainingType; foreach (var member in type.GetMembers(memberName)) { if (getSlotForFieldOrPropertyOrEvent(member) is int memberSlot && memberSlot > 0) { this.State[memberSlot] = NullableFlowState.MaybeNull; } } } void enforceNotNullWhenForPendingReturn(PendingBranch pendingReturn, BoundReturnStatement returnStatement) { var parameters = this.MethodParameters; if (!parameters.IsEmpty) { if (pendingReturn.IsConditionalState) { if (returnStatement.ExpressionOpt is { ConstantValue: { IsBoolean: true, BooleanValue: bool value } }) { enforceParameterNotNullWhen(returnStatement.Syntax, parameters, sense: value, stateWhen: pendingReturn.State); return; } if (!pendingReturn.StateWhenTrue.Reachable || !pendingReturn.StateWhenFalse.Reachable) { return; } foreach (var parameter in parameters) { // For non-constant values, only complain if we were able to analyze a difference for this parameter between two branches if (GetOrCreateSlot(parameter) is > 0 and var slot && pendingReturn.StateWhenTrue[slot] != pendingReturn.StateWhenFalse[slot]) { reportParameterIfBadConditionalState(returnStatement.Syntax, parameter, sense: true, stateWhen: pendingReturn.StateWhenTrue); reportParameterIfBadConditionalState(returnStatement.Syntax, parameter, sense: false, stateWhen: pendingReturn.StateWhenFalse); } } } else if (returnStatement.ExpressionOpt is { ConstantValue: { IsBoolean: true, BooleanValue: bool value } }) { // example: return (bool)true; enforceParameterNotNullWhen(returnStatement.Syntax, parameters, sense: value, stateWhen: pendingReturn.State); return; } } } void reportParameterIfBadConditionalState(SyntaxNode syntax, ParameterSymbol parameter, bool sense, LocalState stateWhen) { if (parameterHasBadConditionalState(parameter, sense, stateWhen)) { // Parameter '{name}' must have a non-null value when exiting with '{sense}'. Diagnostics.Add(ErrorCode.WRN_ParameterConditionallyDisallowsNull, syntax.Location, parameter.Name, sense ? "true" : "false"); } } void enforceNotNull(SyntaxNode? syntaxOpt, LocalState state) { if (!state.Reachable) { return; } foreach (var parameter in this.MethodParameters) { var slot = GetOrCreateSlot(parameter); if (slot <= 0) { continue; } var annotations = parameter.FlowAnalysisAnnotations; var hasNotNull = (annotations & FlowAnalysisAnnotations.NotNull) == FlowAnalysisAnnotations.NotNull; var parameterState = state[slot]; if (hasNotNull && parameterState.MayBeNull()) { // Parameter '{name}' must have a non-null value when exiting. Diagnostics.Add(ErrorCode.WRN_ParameterDisallowsNull, syntaxOpt?.GetLocation() ?? methodMainNode.Syntax.GetLastToken().GetLocation(), parameter.Name); } else { EnforceNotNullIfNotNull(syntaxOpt, state, this.MethodParameters, parameter.NotNullIfParameterNotNull, parameterState, parameter); } } } void enforceParameterNotNullWhen(SyntaxNode syntax, ImmutableArray<ParameterSymbol> parameters, bool sense, LocalState stateWhen) { if (!stateWhen.Reachable) { return; } foreach (var parameter in parameters) { reportParameterIfBadConditionalState(syntax, parameter, sense, stateWhen); } } bool parameterHasBadConditionalState(ParameterSymbol parameter, bool sense, LocalState stateWhen) { var refKind = parameter.RefKind; if (refKind != RefKind.Out && refKind != RefKind.Ref) { return false; } var slot = GetOrCreateSlot(parameter); if (slot > 0) { var parameterState = stateWhen[slot]; // On a parameter marked with MaybeNullWhen, we would have not reported an assignment warning. // We should only check if an assignment warning would have been warranted ignoring the MaybeNullWhen. FlowAnalysisAnnotations annotations = parameter.FlowAnalysisAnnotations; if (sense) { bool hasNotNullWhenTrue = (annotations & FlowAnalysisAnnotations.NotNull) == FlowAnalysisAnnotations.NotNullWhenTrue; bool hasMaybeNullWhenFalse = (annotations & FlowAnalysisAnnotations.MaybeNull) == FlowAnalysisAnnotations.MaybeNullWhenFalse; return (hasNotNullWhenTrue && parameterState.MayBeNull()) || (hasMaybeNullWhenFalse && ShouldReportNullableAssignment(parameter.TypeWithAnnotations, parameterState)); } else { bool hasNotNullWhenFalse = (annotations & FlowAnalysisAnnotations.NotNull) == FlowAnalysisAnnotations.NotNullWhenFalse; bool hasMaybeNullWhenTrue = (annotations & FlowAnalysisAnnotations.MaybeNull) == FlowAnalysisAnnotations.MaybeNullWhenTrue; return (hasNotNullWhenFalse && parameterState.MayBeNull()) || (hasMaybeNullWhenTrue && ShouldReportNullableAssignment(parameter.TypeWithAnnotations, parameterState)); } } return false; } int getSlotForFieldOrPropertyOrEvent(Symbol member) { if (member.Kind != SymbolKind.Field && member.Kind != SymbolKind.Property && member.Kind != SymbolKind.Event) { return -1; } int containingSlot = 0; if (!member.IsStatic) { if (MethodThisParameter is null) { return -1; } containingSlot = GetOrCreateSlot(MethodThisParameter); if (containingSlot < 0) { return -1; } Debug.Assert(containingSlot > 0); } return GetOrCreateSlot(member, containingSlot); } } private void EnforceNotNullIfNotNull(SyntaxNode? syntaxOpt, LocalState state, ImmutableArray<ParameterSymbol> parameters, ImmutableHashSet<string> inputParamNames, NullableFlowState outputState, ParameterSymbol? outputParam) { if (inputParamNames.IsEmpty || outputState.IsNotNull()) { return; } foreach (var inputParam in parameters) { if (inputParamNames.Contains(inputParam.Name) && GetOrCreateSlot(inputParam) is > 0 and int inputSlot && state[inputSlot].IsNotNull()) { var location = syntaxOpt?.GetLocation() ?? methodMainNode.Syntax.GetLastToken().GetLocation(); if (outputParam is object) { // Parameter '{0}' must have a non-null value when exiting because parameter '{1}' is non-null. Diagnostics.Add(ErrorCode.WRN_ParameterNotNullIfNotNull, location, outputParam.Name, inputParam.Name); } else if (CurrentSymbol is MethodSymbol { IsAsync: false }) { // Return value must be non-null because parameter '{0}' is non-null. Diagnostics.Add(ErrorCode.WRN_ReturnNotNullIfNotNull, location, inputParam.Name); } break; } } } private void EnforceDoesNotReturn(SyntaxNode? syntaxOpt) { // DoesNotReturn is only supported in member methods if (CurrentSymbol is MethodSymbol { ContainingSymbol: TypeSymbol _ } method && ((method.FlowAnalysisAnnotations & FlowAnalysisAnnotations.DoesNotReturn) == FlowAnalysisAnnotations.DoesNotReturn) && this.IsReachable()) { // A method marked [DoesNotReturn] should not return. ReportDiagnostic(ErrorCode.WRN_ShouldNotReturn, syntaxOpt?.GetLocation() ?? methodMainNode.Syntax.GetLastToken().GetLocation()); } } /// <summary> /// Analyzes a method body if settings indicate we should. /// </summary> internal static void AnalyzeIfNeeded( CSharpCompilation compilation, MethodSymbol method, BoundNode node, DiagnosticBag diagnostics, bool useConstructorExitWarnings, VariableState? initialNullableState, bool getFinalNullableState, out VariableState? finalNullableState) { if (!HasRequiredLanguageVersion(compilation) || !compilation.IsNullableAnalysisEnabledIn(method)) { if (compilation.IsNullableAnalysisEnabledAlways) { // Once we address https://github.com/dotnet/roslyn/issues/46579 we should also always pass `getFinalNullableState: true` in debug mode. // We will likely always need to write a 'null' out for the out parameter in this code path, though, because // we don't want to introduce behavior differences between debug and release builds Analyze(compilation, method, node, new DiagnosticBag(), useConstructorExitWarnings: false, initialNullableState: null, getFinalNullableState: false, out _, requiresAnalysis: false); } finalNullableState = null; return; } Analyze(compilation, method, node, diagnostics, useConstructorExitWarnings, initialNullableState, getFinalNullableState, out finalNullableState); } private static void Analyze( CSharpCompilation compilation, MethodSymbol method, BoundNode node, DiagnosticBag diagnostics, bool useConstructorExitWarnings, VariableState? initialNullableState, bool getFinalNullableState, out VariableState? finalNullableState, bool requiresAnalysis = true) { if (method.IsImplicitlyDeclared && !method.IsImplicitConstructor && !method.IsScriptInitializer) { finalNullableState = null; return; } Debug.Assert(node.SyntaxTree is object); var binder = method is SynthesizedSimpleProgramEntryPointSymbol entryPoint ? entryPoint.GetBodyBinder(ignoreAccessibility: false) : compilation.GetBinderFactory(node.SyntaxTree).GetBinder(node.Syntax); var conversions = binder.Conversions; Analyze(compilation, method, node, binder, conversions, diagnostics, useConstructorExitWarnings, useDelegateInvokeParameterTypes: false, useDelegateInvokeReturnType: false, delegateInvokeMethodOpt: null, initialState: initialNullableState, analyzedNullabilityMapOpt: null, snapshotBuilderOpt: null, returnTypesOpt: null, getFinalNullableState, finalNullableState: out finalNullableState, requiresAnalysis); } /// <summary> /// Gets the "after initializers state" which should be used at the beginning of nullable analysis /// of certain constructors. Only used for semantic model and debug verification. /// </summary> internal static VariableState? GetAfterInitializersState(CSharpCompilation compilation, Symbol? symbol) { if (symbol is MethodSymbol method && method.IncludeFieldInitializersInBody() && method.ContainingType is SourceMemberContainerTypeSymbol containingType) { var unusedDiagnostics = DiagnosticBag.GetInstance(); Binder.ProcessedFieldInitializers initializers = default; Binder.BindFieldInitializers(compilation, null, method.IsStatic ? containingType.StaticInitializers : containingType.InstanceInitializers, BindingDiagnosticBag.Discarded, ref initializers); NullableWalker.AnalyzeIfNeeded( compilation, method, InitializerRewriter.RewriteConstructor(initializers.BoundInitializers, method), unusedDiagnostics, useConstructorExitWarnings: false, initialNullableState: null, getFinalNullableState: true, out var afterInitializersState); unusedDiagnostics.Free(); return afterInitializersState; } return null; } /// <summary> /// Analyzes a set of bound nodes, recording updated nullability information. This method is only /// used when nullable is explicitly enabled for all methods but disabled otherwise to verify that /// correct semantic information is being recorded for all bound nodes. The results are thrown away. /// </summary> internal static void AnalyzeWithoutRewrite( CSharpCompilation compilation, Symbol? symbol, BoundNode node, Binder binder, DiagnosticBag diagnostics, bool createSnapshots) { _ = AnalyzeWithSemanticInfo(compilation, symbol, node, binder, initialState: GetAfterInitializersState(compilation, symbol), diagnostics, createSnapshots, requiresAnalysis: false); } /// <summary> /// Analyzes a set of bound nodes, recording updated nullability information, and returns an /// updated BoundNode with the information populated. /// </summary> internal static BoundNode AnalyzeAndRewrite( CSharpCompilation compilation, Symbol? symbol, BoundNode node, Binder binder, VariableState? initialState, DiagnosticBag diagnostics, bool createSnapshots, out SnapshotManager? snapshotManager, ref ImmutableDictionary<Symbol, Symbol>? remappedSymbols) { ImmutableDictionary<BoundExpression, (NullabilityInfo, TypeSymbol?)> analyzedNullabilitiesMap; (snapshotManager, analyzedNullabilitiesMap) = AnalyzeWithSemanticInfo(compilation, symbol, node, binder, initialState, diagnostics, createSnapshots, requiresAnalysis: true); return Rewrite(analyzedNullabilitiesMap, snapshotManager, node, ref remappedSymbols); } private static (SnapshotManager?, ImmutableDictionary<BoundExpression, (NullabilityInfo, TypeSymbol?)>) AnalyzeWithSemanticInfo( CSharpCompilation compilation, Symbol? symbol, BoundNode node, Binder binder, VariableState? initialState, DiagnosticBag diagnostics, bool createSnapshots, bool requiresAnalysis) { var analyzedNullabilities = ImmutableDictionary.CreateBuilder<BoundExpression, (NullabilityInfo, TypeSymbol?)>(EqualityComparer<BoundExpression>.Default, NullabilityInfoTypeComparer.Instance); // Attributes don't have a symbol, which is what SnapshotBuilder uses as an index for maintaining global state. // Until we have a workaround for this, disable snapshots for null symbols. // https://github.com/dotnet/roslyn/issues/36066 var snapshotBuilder = createSnapshots && symbol != null ? new SnapshotManager.Builder() : null; Analyze( compilation, symbol, node, binder, binder.Conversions, diagnostics, useConstructorExitWarnings: true, useDelegateInvokeParameterTypes: false, useDelegateInvokeReturnType: false, delegateInvokeMethodOpt: null, initialState, analyzedNullabilities, snapshotBuilder, returnTypesOpt: null, getFinalNullableState: false, out _, requiresAnalysis); var analyzedNullabilitiesMap = analyzedNullabilities.ToImmutable(); var snapshotManager = snapshotBuilder?.ToManagerAndFree(); #if DEBUG // https://github.com/dotnet/roslyn/issues/34993 Enable for all calls if (isNullableAnalysisEnabledAnywhere(compilation)) { DebugVerifier.Verify(analyzedNullabilitiesMap, snapshotManager, node); } static bool isNullableAnalysisEnabledAnywhere(CSharpCompilation compilation) { if (compilation.Options.NullableContextOptions != NullableContextOptions.Disable) { return true; } return compilation.SyntaxTrees.Any(tree => ((CSharpSyntaxTree)tree).IsNullableAnalysisEnabled(new Text.TextSpan(0, tree.Length)) == true); } #endif return (snapshotManager, analyzedNullabilitiesMap); } internal static BoundNode AnalyzeAndRewriteSpeculation( int position, BoundNode node, Binder binder, SnapshotManager originalSnapshots, out SnapshotManager newSnapshots, ref ImmutableDictionary<Symbol, Symbol>? remappedSymbols) { var analyzedNullabilities = ImmutableDictionary.CreateBuilder<BoundExpression, (NullabilityInfo, TypeSymbol?)>(EqualityComparer<BoundExpression>.Default, NullabilityInfoTypeComparer.Instance); var newSnapshotBuilder = new SnapshotManager.Builder(); var (variables, localState) = originalSnapshots.GetSnapshot(position); var symbol = variables.Symbol; var walker = new NullableWalker( binder.Compilation, symbol, useConstructorExitWarnings: false, useDelegateInvokeParameterTypes: false, useDelegateInvokeReturnType: false, delegateInvokeMethodOpt: null, node, binder, binder.Conversions, Variables.Create(variables), returnTypesOpt: null, analyzedNullabilities, newSnapshotBuilder, isSpeculative: true); try { Analyze(walker, symbol, diagnostics: null, LocalState.Create(localState), snapshotBuilderOpt: newSnapshotBuilder); } finally { walker.Free(); } var analyzedNullabilitiesMap = analyzedNullabilities.ToImmutable(); newSnapshots = newSnapshotBuilder.ToManagerAndFree(); #if DEBUG DebugVerifier.Verify(analyzedNullabilitiesMap, newSnapshots, node); #endif return Rewrite(analyzedNullabilitiesMap, newSnapshots, node, ref remappedSymbols); } private static BoundNode Rewrite(ImmutableDictionary<BoundExpression, (NullabilityInfo, TypeSymbol?)> updatedNullabilities, SnapshotManager? snapshotManager, BoundNode node, ref ImmutableDictionary<Symbol, Symbol>? remappedSymbols) { var remappedSymbolsBuilder = ImmutableDictionary.CreateBuilder<Symbol, Symbol>(Symbols.SymbolEqualityComparer.ConsiderEverything, Symbols.SymbolEqualityComparer.ConsiderEverything); if (remappedSymbols is object) { // When we're rewriting for the speculative model, there will be a set of originally-mapped symbols, and we need to // use them in addition to any symbols found during this pass of the walker. remappedSymbolsBuilder.AddRange(remappedSymbols); } var rewriter = new NullabilityRewriter(updatedNullabilities, snapshotManager, remappedSymbolsBuilder); var rewrittenNode = rewriter.Visit(node); remappedSymbols = remappedSymbolsBuilder.ToImmutable(); return rewrittenNode; } private static bool HasRequiredLanguageVersion(CSharpCompilation compilation) { return compilation.LanguageVersion >= MessageID.IDS_FeatureNullableReferenceTypes.RequiredVersion(); } /// <summary> /// Returns true if the nullable analysis is needed for the region represented by <paramref name="syntaxNode"/>. /// The syntax node is used to determine the overall nullable context for the region. /// </summary> internal static bool NeedsAnalysis(CSharpCompilation compilation, SyntaxNode syntaxNode) { return HasRequiredLanguageVersion(compilation) && (compilation.IsNullableAnalysisEnabledIn(syntaxNode) || compilation.IsNullableAnalysisEnabledAlways); } /// <summary>Analyzes a node in a "one-off" context, such as for attributes or parameter default values.</summary> /// <remarks><paramref name="syntax"/> is the syntax span used to determine the overall nullable context.</remarks> internal static void AnalyzeIfNeeded( Binder binder, BoundNode node, SyntaxNode syntax, DiagnosticBag diagnostics) { bool requiresAnalysis = true; var compilation = binder.Compilation; if (!HasRequiredLanguageVersion(compilation) || !compilation.IsNullableAnalysisEnabledIn(syntax)) { if (!compilation.IsNullableAnalysisEnabledAlways) { return; } diagnostics = new DiagnosticBag(); requiresAnalysis = false; } Analyze( compilation, symbol: null, node, binder, binder.Conversions, diagnostics, useConstructorExitWarnings: false, useDelegateInvokeParameterTypes: false, useDelegateInvokeReturnType: false, delegateInvokeMethodOpt: null, initialState: null, analyzedNullabilityMapOpt: null, snapshotBuilderOpt: null, returnTypesOpt: null, getFinalNullableState: false, out _, requiresAnalysis); } internal static void Analyze( CSharpCompilation compilation, BoundLambda lambda, Conversions conversions, DiagnosticBag diagnostics, MethodSymbol? delegateInvokeMethodOpt, VariableState initialState, ArrayBuilder<(BoundReturnStatement, TypeWithAnnotations)>? returnTypesOpt) { var symbol = lambda.Symbol; var variables = Variables.Create(initialState.Variables).CreateNestedMethodScope(symbol); UseDelegateInvokeParameterAndReturnTypes(lambda, delegateInvokeMethodOpt, out bool useDelegateInvokeParameterTypes, out bool useDelegateInvokeReturnType); var walker = new NullableWalker( compilation, symbol, useConstructorExitWarnings: false, useDelegateInvokeParameterTypes: useDelegateInvokeParameterTypes, useDelegateInvokeReturnType: useDelegateInvokeReturnType, delegateInvokeMethodOpt: delegateInvokeMethodOpt, lambda.Body, lambda.Binder, conversions, variables, returnTypesOpt, analyzedNullabilityMapOpt: null, snapshotBuilderOpt: null); try { var localState = LocalState.Create(initialState.VariableNullableStates).CreateNestedMethodState(variables); Analyze(walker, symbol, diagnostics, localState, snapshotBuilderOpt: null); } finally { walker.Free(); } } private static void Analyze( CSharpCompilation compilation, Symbol? symbol, BoundNode node, Binder binder, Conversions conversions, DiagnosticBag diagnostics, bool useConstructorExitWarnings, bool useDelegateInvokeParameterTypes, bool useDelegateInvokeReturnType, MethodSymbol? delegateInvokeMethodOpt, VariableState? initialState, ImmutableDictionary<BoundExpression, (NullabilityInfo, TypeSymbol?)>.Builder? analyzedNullabilityMapOpt, SnapshotManager.Builder? snapshotBuilderOpt, ArrayBuilder<(BoundReturnStatement, TypeWithAnnotations)>? returnTypesOpt, bool getFinalNullableState, out VariableState? finalNullableState, bool requiresAnalysis = true) { Debug.Assert(diagnostics != null); var walker = new NullableWalker(compilation, symbol, useConstructorExitWarnings, useDelegateInvokeParameterTypes, useDelegateInvokeReturnType, delegateInvokeMethodOpt, node, binder, conversions, initialState is null ? null : Variables.Create(initialState.Variables), returnTypesOpt, analyzedNullabilityMapOpt, snapshotBuilderOpt); finalNullableState = null; try { Analyze(walker, symbol, diagnostics, initialState is null ? (Optional<LocalState>)default : LocalState.Create(initialState.VariableNullableStates), snapshotBuilderOpt, requiresAnalysis); if (getFinalNullableState) { Debug.Assert(!walker.IsConditionalState); finalNullableState = GetVariableState(walker._variables, walker.State); } } finally { walker.Free(); } } private static void Analyze( NullableWalker walker, Symbol? symbol, DiagnosticBag? diagnostics, Optional<LocalState> initialState, SnapshotManager.Builder? snapshotBuilderOpt, bool requiresAnalysis = true) { Debug.Assert(snapshotBuilderOpt is null || symbol is object); var previousSlot = snapshotBuilderOpt?.EnterNewWalker(symbol!) ?? -1; try { bool badRegion = false; ImmutableArray<PendingBranch> returns = walker.Analyze(ref badRegion, initialState); diagnostics?.AddRange(walker.Diagnostics); Debug.Assert(!badRegion); } catch (CancelledByStackGuardException ex) when (diagnostics != null) { ex.AddAnError(diagnostics); } finally { snapshotBuilderOpt?.ExitWalker(walker.SaveSharedState(), previousSlot); } walker.RecordNullableAnalysisData(symbol, requiresAnalysis); } private void RecordNullableAnalysisData(Symbol? symbol, bool requiredAnalysis) { if (compilation.NullableAnalysisData?.Data is { } state) { var key = (object?)symbol ?? methodMainNode.Syntax; if (state.TryGetValue(key, out var result)) { Debug.Assert(result.RequiredAnalysis == requiredAnalysis); } else { state.TryAdd(key, new Data(_variables.GetTotalVariableCount(), requiredAnalysis)); } } } private SharedWalkerState SaveSharedState() { return new SharedWalkerState(_variables.CreateSnapshot()); } private void TakeIncrementalSnapshot(BoundNode? node) { Debug.Assert(!IsConditionalState); _snapshotBuilderOpt?.TakeIncrementalSnapshot(node, State); } private void SetUpdatedSymbol(BoundNode node, Symbol originalSymbol, Symbol updatedSymbol) { if (_snapshotBuilderOpt is null) { return; } var lambdaIsExactMatch = false; if (node is BoundLambda boundLambda && originalSymbol is LambdaSymbol l && updatedSymbol is NamedTypeSymbol n) { if (!AreLambdaAndNewDelegateSimilar(l, n)) { return; } lambdaIsExactMatch = updatedSymbol.Equals(boundLambda.Type!.GetDelegateType(), TypeCompareKind.ConsiderEverything); } #if DEBUG Debug.Assert(node is object); Debug.Assert(AreCloseEnough(originalSymbol, updatedSymbol), $"Attempting to set {node.Syntax} from {originalSymbol.ToDisplayString()} to {updatedSymbol.ToDisplayString()}"); #endif if (lambdaIsExactMatch || Symbol.Equals(originalSymbol, updatedSymbol, TypeCompareKind.ConsiderEverything)) { // If the symbol is reset, remove the updated symbol so we don't needlessly update the // bound node later on. We do this unconditionally, as Remove will just return false // if the key wasn't in the dictionary. _snapshotBuilderOpt.RemoveSymbolIfPresent(node, originalSymbol); } else { _snapshotBuilderOpt.SetUpdatedSymbol(node, originalSymbol, updatedSymbol); } } protected override void Normalize(ref LocalState state) { if (!state.Reachable) return; state.Normalize(this, _variables); } private NullableFlowState GetDefaultState(ref LocalState state, int slot) { Debug.Assert(slot > 0); if (!state.Reachable) return NullableFlowState.NotNull; var variable = _variables[slot]; var symbol = variable.Symbol; switch (symbol.Kind) { case SymbolKind.Local: { var local = (LocalSymbol)symbol; if (!_variables.TryGetType(local, out TypeWithAnnotations localType)) { localType = local.TypeWithAnnotations; } return localType.ToTypeWithState().State; } case SymbolKind.Parameter: { var parameter = (ParameterSymbol)symbol; if (!_variables.TryGetType(parameter, out TypeWithAnnotations parameterType)) { parameterType = parameter.TypeWithAnnotations; } return GetParameterState(parameterType, parameter.FlowAnalysisAnnotations).State; } case SymbolKind.Field: case SymbolKind.Property: case SymbolKind.Event: return GetDefaultState(symbol); case SymbolKind.ErrorType: return NullableFlowState.NotNull; default: throw ExceptionUtilities.UnexpectedValue(symbol.Kind); } } protected override bool TryGetReceiverAndMember(BoundExpression expr, out BoundExpression? receiver, [NotNullWhen(true)] out Symbol? member) { receiver = null; member = null; switch (expr.Kind) { case BoundKind.FieldAccess: { var fieldAccess = (BoundFieldAccess)expr; var fieldSymbol = fieldAccess.FieldSymbol; member = fieldSymbol; if (fieldSymbol.IsFixedSizeBuffer) { return false; } if (fieldSymbol.IsStatic) { return true; } receiver = fieldAccess.ReceiverOpt; break; } case BoundKind.EventAccess: { var eventAccess = (BoundEventAccess)expr; var eventSymbol = eventAccess.EventSymbol; // https://github.com/dotnet/roslyn/issues/29901 Use AssociatedField for field-like events? member = eventSymbol; if (eventSymbol.IsStatic) { return true; } receiver = eventAccess.ReceiverOpt; break; } case BoundKind.PropertyAccess: { var propAccess = (BoundPropertyAccess)expr; var propSymbol = propAccess.PropertySymbol; member = propSymbol; if (propSymbol.IsStatic) { return true; } receiver = propAccess.ReceiverOpt; break; } } Debug.Assert(member?.RequiresInstanceReceiver() ?? true); return member is object && receiver is object && receiver.Kind != BoundKind.TypeExpression && receiver.Type is object; } protected override int MakeSlot(BoundExpression node) { int result = makeSlot(node); #if DEBUG if (result != -1) { // Check that the slot represents a value of an equivalent type to the node TypeSymbol slotType = NominalSlotType(result); TypeSymbol? nodeType = node.Type; var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var conversionsWithoutNullability = this.compilation.Conversions; Debug.Assert(node.HasErrors || nodeType!.IsErrorType() || conversionsWithoutNullability.HasIdentityOrImplicitReferenceConversion(slotType, nodeType, ref discardedUseSiteInfo) || conversionsWithoutNullability.HasBoxingConversion(slotType, nodeType, ref discardedUseSiteInfo)); } #endif return result; int makeSlot(BoundExpression node) { switch (node.Kind) { case BoundKind.ThisReference: case BoundKind.BaseReference: { var method = getTopLevelMethod(_symbol as MethodSymbol); var thisParameter = method?.ThisParameter; return thisParameter is object ? GetOrCreateSlot(thisParameter) : -1; } case BoundKind.Conversion: { int slot = getPlaceholderSlot(node); if (slot > 0) { return slot; } var conv = (BoundConversion)node; switch (conv.Conversion.Kind) { case ConversionKind.ExplicitNullable: { var operand = conv.Operand; var operandType = operand.Type; var convertedType = conv.Type; if (AreNullableAndUnderlyingTypes(operandType, convertedType, out _)) { // Explicit conversion of Nullable<T> to T is equivalent to Nullable<T>.Value. // For instance, in the following, when evaluating `((A)a).B` we need to recognize // the nullability of `(A)a` (not nullable) and the slot (the slot for `a.Value`). // struct A { B? B; } // struct B { } // if (a?.B != null) _ = ((A)a).B.Value; // no warning int containingSlot = MakeSlot(operand); return containingSlot < 0 ? -1 : GetNullableOfTValueSlot(operandType, containingSlot, out _); } } break; case ConversionKind.Identity: case ConversionKind.DefaultLiteral: case ConversionKind.ImplicitReference: case ConversionKind.ImplicitTupleLiteral: case ConversionKind.Boxing: // No need to create a slot for the boxed value (in the Boxing case) since assignment already // clones slots and there is not another scenario where creating a slot is observable. return MakeSlot(conv.Operand); } } break; case BoundKind.DefaultLiteral: case BoundKind.DefaultExpression: case BoundKind.ObjectCreationExpression: case BoundKind.DynamicObjectCreationExpression: case BoundKind.AnonymousObjectCreationExpression: case BoundKind.NewT: case BoundKind.TupleLiteral: case BoundKind.ConvertedTupleLiteral: return getPlaceholderSlot(node); case BoundKind.ConditionalAccess: return getPlaceholderSlot(node); case BoundKind.ConditionalReceiver: return _lastConditionalAccessSlot; default: { int slot = getPlaceholderSlot(node); return (slot > 0) ? slot : base.MakeSlot(node); } } return -1; } int getPlaceholderSlot(BoundExpression expr) { if (_placeholderLocalsOpt != null && _placeholderLocalsOpt.TryGetValue(expr, out var placeholder)) { return GetOrCreateSlot(placeholder); } return -1; } static MethodSymbol? getTopLevelMethod(MethodSymbol? method) { while (method is object) { var container = method.ContainingSymbol; if (container.Kind == SymbolKind.NamedType) { return method; } method = container as MethodSymbol; } return null; } } protected override int GetOrCreateSlot(Symbol symbol, int containingSlot = 0, bool forceSlotEvenIfEmpty = false, bool createIfMissing = true) { if (containingSlot > 0 && !IsSlotMember(containingSlot, symbol)) return -1; return base.GetOrCreateSlot(symbol, containingSlot, forceSlotEvenIfEmpty, createIfMissing); } private void VisitAndUnsplitAll<T>(ImmutableArray<T> nodes) where T : BoundNode { if (nodes.IsDefault) { return; } foreach (var node in nodes) { Visit(node); Unsplit(); } } private void VisitWithoutDiagnostics(BoundNode? node) { var previousDiagnostics = _disableDiagnostics; _disableDiagnostics = true; Visit(node); _disableDiagnostics = previousDiagnostics; } protected override void VisitRvalue(BoundExpression? node, bool isKnownToBeAnLvalue = false) { Visit(node); VisitRvalueEpilogue(node); } /// <summary> /// The contents of this method, particularly <see cref="UseRvalueOnly"/>, are problematic when /// inlined. The methods themselves are small but they end up allocating significantly larger /// frames due to the use of biggish value types within them. The <see cref="VisitRvalue"/> method /// is used on a hot path for fluent calls and this size change is enough that it causes us /// to exceed our thresholds in EndToEndTests.OverflowOnFluentCall. /// </summary> [MethodImpl(MethodImplOptions.NoInlining)] private void VisitRvalueEpilogue(BoundExpression? node) { Unsplit(); UseRvalueOnly(node); // drop lvalue part } private TypeWithState VisitRvalueWithState(BoundExpression? node) { VisitRvalue(node); return ResultType; } private TypeWithAnnotations VisitLvalueWithAnnotations(BoundExpression node) { VisitLValue(node); Unsplit(); return LvalueResultType; } private static object GetTypeAsDiagnosticArgument(TypeSymbol? typeOpt) { return typeOpt ?? (object)"<null>"; } private static object GetParameterAsDiagnosticArgument(ParameterSymbol? parameterOpt) { return parameterOpt is null ? (object)"" : new FormattedSymbol(parameterOpt, SymbolDisplayFormat.ShortFormat); } private static object GetContainingSymbolAsDiagnosticArgument(ParameterSymbol? parameterOpt) { var containingSymbol = parameterOpt?.ContainingSymbol; return containingSymbol is null ? (object)"" : new FormattedSymbol(containingSymbol, SymbolDisplayFormat.MinimallyQualifiedFormat); } private enum AssignmentKind { Assignment, Return, Argument, ForEachIterationVariable } /// <summary> /// Should we warn for assigning this state into this type? /// /// This should often be checked together with <seealso cref="IsDisallowedNullAssignment(TypeWithState, FlowAnalysisAnnotations)"/> /// It catches putting a `null` into a `[DisallowNull]int?` for example, which cannot simply be represented as a non-nullable target type. /// </summary> private static bool ShouldReportNullableAssignment(TypeWithAnnotations type, NullableFlowState state) { if (!type.HasType || type.Type.IsValueType) { return false; } switch (type.NullableAnnotation) { case NullableAnnotation.Oblivious: case NullableAnnotation.Annotated: return false; } switch (state) { case NullableFlowState.NotNull: return false; case NullableFlowState.MaybeNull: if (type.Type.IsTypeParameterDisallowingAnnotationInCSharp8() && !(type.Type is TypeParameterSymbol { IsNotNullable: true })) { return false; } break; } return true; } /// <summary> /// Reports top-level nullability problem in assignment. /// Any conversion of the value should have been applied. /// </summary> private void ReportNullableAssignmentIfNecessary( BoundExpression? value, TypeWithAnnotations targetType, TypeWithState valueType, bool useLegacyWarnings, AssignmentKind assignmentKind = AssignmentKind.Assignment, ParameterSymbol? parameterOpt = null, Location? location = null) { // Callers should apply any conversions before calling this method // (see https://github.com/dotnet/roslyn/issues/39867). if (targetType.HasType && !targetType.Type.Equals(valueType.Type, TypeCompareKind.AllIgnoreOptions)) { return; } if (value == null || // This prevents us from giving undesired warnings for synthesized arguments for optional parameters, // but allows us to give warnings for synthesized assignments to record properties and for parameter default values at the declaration site. (value.WasCompilerGenerated && assignmentKind == AssignmentKind.Argument) || !ShouldReportNullableAssignment(targetType, valueType.State)) { return; } location ??= value.Syntax.GetLocation(); var unwrappedValue = SkipReferenceConversions(value); if (unwrappedValue.IsSuppressed) { return; } if (value.ConstantValue?.IsNull == true && !useLegacyWarnings) { // Report warning converting null literal to non-nullable reference type. // target (e.g.: `object F() => null;` or calling `void F(object y)` with `F(null)`). ReportDiagnostic(assignmentKind == AssignmentKind.Return ? ErrorCode.WRN_NullReferenceReturn : ErrorCode.WRN_NullAsNonNullable, location); } else if (assignmentKind == AssignmentKind.Argument) { ReportDiagnostic(ErrorCode.WRN_NullReferenceArgument, location, GetParameterAsDiagnosticArgument(parameterOpt), GetContainingSymbolAsDiagnosticArgument(parameterOpt)); LearnFromNonNullTest(value, ref State); } else if (useLegacyWarnings) { if (isMaybeDefaultValue(valueType) && !allowUnconstrainedTypeParameterAnnotations(compilation)) { // No W warning reported assigning or casting [MaybeNull]T value to T // because there is no syntax for declaring the target type as [MaybeNull]T. return; } ReportNonSafetyDiagnostic(location); } else { ReportDiagnostic(assignmentKind == AssignmentKind.Return ? ErrorCode.WRN_NullReferenceReturn : ErrorCode.WRN_NullReferenceAssignment, location); } static bool isMaybeDefaultValue(TypeWithState valueType) { return valueType.Type?.TypeKind == TypeKind.TypeParameter && valueType.State == NullableFlowState.MaybeDefault; } static bool allowUnconstrainedTypeParameterAnnotations(CSharpCompilation compilation) { // Check IDS_FeatureDefaultTypeParameterConstraint feature since `T?` and `where ... : default` // are treated as a single feature, even though the errors reported for the two cases are distinct. var requiredVersion = MessageID.IDS_FeatureDefaultTypeParameterConstraint.RequiredVersion(); return requiredVersion <= compilation.LanguageVersion; } } internal static bool AreParameterAnnotationsCompatible( RefKind refKind, TypeWithAnnotations overriddenType, FlowAnalysisAnnotations overriddenAnnotations, TypeWithAnnotations overridingType, FlowAnalysisAnnotations overridingAnnotations, bool forRef = false) { // We've already checked types and annotations, let's check nullability attributes as well // Return value is treated as an `out` parameter (or `ref` if it is a `ref` return) if (refKind == RefKind.Ref) { // ref variables are invariant return AreParameterAnnotationsCompatible(RefKind.None, overriddenType, overriddenAnnotations, overridingType, overridingAnnotations, forRef: true) && AreParameterAnnotationsCompatible(RefKind.Out, overriddenType, overriddenAnnotations, overridingType, overridingAnnotations); } if (refKind == RefKind.None || refKind == RefKind.In) { // pre-condition attributes // Check whether we can assign a value from overridden parameter to overriding var valueState = GetParameterState(overriddenType, overriddenAnnotations); if (isBadAssignment(valueState, overridingType, overridingAnnotations)) { return false; } // unconditional post-condition attributes on inputs bool overridingHasNotNull = (overridingAnnotations & FlowAnalysisAnnotations.NotNull) == FlowAnalysisAnnotations.NotNull; bool overriddenHasNotNull = (overriddenAnnotations & FlowAnalysisAnnotations.NotNull) == FlowAnalysisAnnotations.NotNull; if (overriddenHasNotNull && !overridingHasNotNull && !forRef) { // Overriding doesn't conform to contract of overridden (ie. promise not to return if parameter is null) return false; } bool overridingHasMaybeNull = (overridingAnnotations & FlowAnalysisAnnotations.MaybeNull) == FlowAnalysisAnnotations.MaybeNull; bool overriddenHasMaybeNull = (overriddenAnnotations & FlowAnalysisAnnotations.MaybeNull) == FlowAnalysisAnnotations.MaybeNull; if (overriddenHasMaybeNull && !overridingHasMaybeNull && !forRef) { // Overriding doesn't conform to contract of overridden (ie. promise to only return if parameter is null) return false; } } if (refKind == RefKind.Out) { // post-condition attributes (`Maybe/NotNull` and `Maybe/NotNullWhen`) if (!canAssignOutputValueWhen(true) || !canAssignOutputValueWhen(false)) { return false; } } return true; bool canAssignOutputValueWhen(bool sense) { var valueWhen = ApplyUnconditionalAnnotations( overridingType.ToTypeWithState(), makeUnconditionalAnnotation(overridingAnnotations, sense)); var destAnnotationsWhen = ToInwardAnnotations(makeUnconditionalAnnotation(overriddenAnnotations, sense)); if (isBadAssignment(valueWhen, overriddenType, destAnnotationsWhen)) { // Can't assign value from overriding to overridden in 'sense' case return false; } return true; } static bool isBadAssignment(TypeWithState valueState, TypeWithAnnotations destinationType, FlowAnalysisAnnotations destinationAnnotations) { if (ShouldReportNullableAssignment( ApplyLValueAnnotations(destinationType, destinationAnnotations), valueState.State)) { return true; } if (IsDisallowedNullAssignment(valueState, destinationAnnotations)) { return true; } return false; } // Convert both conditional annotations to unconditional ones or nothing static FlowAnalysisAnnotations makeUnconditionalAnnotation(FlowAnalysisAnnotations annotations, bool sense) { if (sense) { var unconditionalAnnotationWhenTrue = makeUnconditionalAnnotationCore(annotations, FlowAnalysisAnnotations.NotNullWhenTrue, FlowAnalysisAnnotations.NotNull); return makeUnconditionalAnnotationCore(unconditionalAnnotationWhenTrue, FlowAnalysisAnnotations.MaybeNullWhenTrue, FlowAnalysisAnnotations.MaybeNull); } var unconditionalAnnotationWhenFalse = makeUnconditionalAnnotationCore(annotations, FlowAnalysisAnnotations.NotNullWhenFalse, FlowAnalysisAnnotations.NotNull); return makeUnconditionalAnnotationCore(unconditionalAnnotationWhenFalse, FlowAnalysisAnnotations.MaybeNullWhenFalse, FlowAnalysisAnnotations.MaybeNull); } // Convert Maybe/NotNullWhen into Maybe/NotNull or nothing static FlowAnalysisAnnotations makeUnconditionalAnnotationCore(FlowAnalysisAnnotations annotations, FlowAnalysisAnnotations conditionalAnnotation, FlowAnalysisAnnotations replacementAnnotation) { if ((annotations & conditionalAnnotation) != 0) { return annotations | replacementAnnotation; } return annotations & ~replacementAnnotation; } } private static bool IsDefaultValue(BoundExpression expr) { switch (expr.Kind) { case BoundKind.Conversion: { var conversion = (BoundConversion)expr; var conversionKind = conversion.Conversion.Kind; return (conversionKind == ConversionKind.DefaultLiteral || conversionKind == ConversionKind.NullLiteral) && IsDefaultValue(conversion.Operand); } case BoundKind.DefaultLiteral: case BoundKind.DefaultExpression: return true; default: return false; } } private void ReportNullabilityMismatchInAssignment(SyntaxNode syntaxNode, object sourceType, object destinationType) { ReportDiagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, syntaxNode, sourceType, destinationType); } private void ReportNullabilityMismatchInAssignment(Location location, object sourceType, object destinationType) { ReportDiagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, location, sourceType, destinationType); } /// <summary> /// Update tracked value on assignment. /// </summary> private void TrackNullableStateForAssignment( BoundExpression? valueOpt, TypeWithAnnotations targetType, int targetSlot, TypeWithState valueType, int valueSlot = -1) { Debug.Assert(!IsConditionalState); if (this.State.Reachable) { if (!targetType.HasType) { return; } if (targetSlot <= 0 || targetSlot == valueSlot) { return; } if (!this.State.HasValue(targetSlot)) Normalize(ref this.State); var newState = valueType.State; SetStateAndTrackForFinally(ref this.State, targetSlot, newState); InheritDefaultState(targetType.Type, targetSlot); // https://github.com/dotnet/roslyn/issues/33428: Can the areEquivalentTypes check be removed // if InheritNullableStateOfMember asserts the member is valid for target and value? if (areEquivalentTypes(targetType, valueType)) { if (targetType.Type.IsReferenceType || targetType.TypeKind == TypeKind.TypeParameter || targetType.IsNullableType()) { if (valueSlot > 0) { InheritNullableStateOfTrackableType(targetSlot, valueSlot, skipSlot: targetSlot); } } else if (EmptyStructTypeCache.IsTrackableStructType(targetType.Type)) { InheritNullableStateOfTrackableStruct(targetType.Type, targetSlot, valueSlot, isDefaultValue: !(valueOpt is null) && IsDefaultValue(valueOpt), skipSlot: targetSlot); } } } static bool areEquivalentTypes(TypeWithAnnotations target, TypeWithState assignedValue) => target.Type.Equals(assignedValue.Type, TypeCompareKind.AllIgnoreOptions); } private void ReportNonSafetyDiagnostic(Location location) { ReportDiagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, location); } private void ReportDiagnostic(ErrorCode errorCode, SyntaxNode syntaxNode, params object[] arguments) { ReportDiagnostic(errorCode, syntaxNode.GetLocation(), arguments); } private void ReportDiagnostic(ErrorCode errorCode, Location location, params object[] arguments) { Debug.Assert(ErrorFacts.NullableWarnings.Contains(MessageProvider.Instance.GetIdForErrorCode((int)errorCode))); if (IsReachable() && !_disableDiagnostics) { Diagnostics.Add(errorCode, location, arguments); } } private void InheritNullableStateOfTrackableStruct(TypeSymbol targetType, int targetSlot, int valueSlot, bool isDefaultValue, int skipSlot = -1) { Debug.Assert(targetSlot > 0); Debug.Assert(EmptyStructTypeCache.IsTrackableStructType(targetType)); if (skipSlot < 0) { skipSlot = targetSlot; } if (!isDefaultValue && valueSlot > 0) { InheritNullableStateOfTrackableType(targetSlot, valueSlot, skipSlot); } else { foreach (var field in _emptyStructTypeCache.GetStructInstanceFields(targetType)) { InheritNullableStateOfMember(targetSlot, valueSlot, field, isDefaultValue: isDefaultValue, skipSlot); } } } private bool IsSlotMember(int slot, Symbol possibleMember) { TypeSymbol possibleBase = possibleMember.ContainingType; TypeSymbol possibleDerived = NominalSlotType(slot); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var conversionsWithoutNullability = _conversions.WithNullability(false); return conversionsWithoutNullability.HasIdentityOrImplicitReferenceConversion(possibleDerived, possibleBase, ref discardedUseSiteInfo) || conversionsWithoutNullability.HasBoxingConversion(possibleDerived, possibleBase, ref discardedUseSiteInfo); } // 'skipSlot' is the original target slot that should be skipped in case of cycles. private void InheritNullableStateOfMember(int targetContainerSlot, int valueContainerSlot, Symbol member, bool isDefaultValue, int skipSlot) { Debug.Assert(targetContainerSlot > 0); Debug.Assert(skipSlot > 0); // Ensure member is valid for target and value. if (!IsSlotMember(targetContainerSlot, member)) return; TypeWithAnnotations fieldOrPropertyType = member.GetTypeOrReturnType(); if (fieldOrPropertyType.Type.IsReferenceType || fieldOrPropertyType.TypeKind == TypeKind.TypeParameter || fieldOrPropertyType.IsNullableType()) { int targetMemberSlot = GetOrCreateSlot(member, targetContainerSlot); if (targetMemberSlot > 0) { NullableFlowState value = isDefaultValue ? NullableFlowState.MaybeNull : fieldOrPropertyType.ToTypeWithState().State; int valueMemberSlot = -1; if (valueContainerSlot > 0) { valueMemberSlot = VariableSlot(member, valueContainerSlot); if (valueMemberSlot == skipSlot) { return; } value = this.State.HasValue(valueMemberSlot) ? this.State[valueMemberSlot] : NullableFlowState.NotNull; } SetStateAndTrackForFinally(ref this.State, targetMemberSlot, value); if (valueMemberSlot > 0) { InheritNullableStateOfTrackableType(targetMemberSlot, valueMemberSlot, skipSlot); } } } else if (EmptyStructTypeCache.IsTrackableStructType(fieldOrPropertyType.Type)) { int targetMemberSlot = GetOrCreateSlot(member, targetContainerSlot); if (targetMemberSlot > 0) { int valueMemberSlot = (valueContainerSlot > 0) ? GetOrCreateSlot(member, valueContainerSlot) : -1; if (valueMemberSlot == skipSlot) { return; } InheritNullableStateOfTrackableStruct(fieldOrPropertyType.Type, targetMemberSlot, valueMemberSlot, isDefaultValue: isDefaultValue, skipSlot); } } } private TypeSymbol NominalSlotType(int slot) { return _variables[slot].Symbol.GetTypeOrReturnType().Type; } /// <summary> /// Whenever assigning a variable, and that variable is not declared at the point the state is being set, /// and the new state is not <see cref="NullableFlowState.NotNull"/>, this method should be called to perform the /// state setting and to ensure the mutation is visible outside the finally block when the mutation occurs in a /// finally block. /// </summary> private void SetStateAndTrackForFinally(ref LocalState state, int slot, NullableFlowState newState) { state[slot] = newState; if (newState != NullableFlowState.NotNull && NonMonotonicState.HasValue) { var tryState = NonMonotonicState.Value; if (tryState.HasVariable(slot)) { tryState[slot] = newState.Join(tryState[slot]); NonMonotonicState = tryState; } } } protected override void JoinTryBlockState(ref LocalState self, ref LocalState other) { var tryState = other.GetStateForVariables(self.Id); Join(ref self, ref tryState); } private void InheritDefaultState(TypeSymbol targetType, int targetSlot) { Debug.Assert(targetSlot > 0); // Reset the state of any members of the target. var members = ArrayBuilder<(VariableIdentifier, int)>.GetInstance(); _variables.GetMembers(members, targetSlot); foreach (var (variable, slot) in members) { var symbol = AsMemberOfType(targetType, variable.Symbol); SetStateAndTrackForFinally(ref this.State, slot, GetDefaultState(symbol)); InheritDefaultState(symbol.GetTypeOrReturnType().Type, slot); } members.Free(); } private NullableFlowState GetDefaultState(Symbol symbol) => ApplyUnconditionalAnnotations(symbol.GetTypeOrReturnType().ToTypeWithState(), GetRValueAnnotations(symbol)).State; private void InheritNullableStateOfTrackableType(int targetSlot, int valueSlot, int skipSlot) { Debug.Assert(targetSlot > 0); Debug.Assert(valueSlot > 0); // Clone the state for members that have been set on the value. var members = ArrayBuilder<(VariableIdentifier, int)>.GetInstance(); _variables.GetMembers(members, valueSlot); foreach (var (variable, slot) in members) { var member = variable.Symbol; Debug.Assert(member.Kind == SymbolKind.Field || member.Kind == SymbolKind.Property || member.Kind == SymbolKind.Event); InheritNullableStateOfMember(targetSlot, valueSlot, member, isDefaultValue: false, skipSlot); } members.Free(); } protected override LocalState TopState() { var state = LocalState.ReachableState(_variables); state.PopulateAll(this); return state; } protected override LocalState UnreachableState() { return LocalState.UnreachableState(_variables); } protected override LocalState ReachableBottomState() { // Create a reachable state in which all variables are known to be non-null. return LocalState.ReachableState(_variables); } private void EnterParameters() { if (!(CurrentSymbol is MethodSymbol methodSymbol)) { return; } if (methodSymbol is SynthesizedRecordConstructor) { if (_hasInitialState) { // A record primary constructor's parameters are entered before analyzing initializers. // On the second pass, the correct parameter states (potentially modified by initializers) // are contained in the initial state. return; } } else if (methodSymbol.IsConstructor()) { if (!_hasInitialState) { // For most constructors, we only enter parameters after analyzing initializers. return; } } // The partial definition part may include optional parameters whose default values we want to simulate assigning at the beginning of the method methodSymbol = methodSymbol.PartialDefinitionPart ?? methodSymbol; var methodParameters = methodSymbol.Parameters; var signatureParameters = (_useDelegateInvokeParameterTypes ? _delegateInvokeMethod! : methodSymbol).Parameters; // save a state representing the possibility that parameter default values were not assigned to the parameters. var parameterDefaultsNotAssignedState = State.Clone(); for (int i = 0; i < methodParameters.Length; i++) { var parameter = methodParameters[i]; // In error scenarios, the method can potentially have more parameters than the signature. If so, use the parameter type for those // errored parameters var parameterType = i >= signatureParameters.Length ? parameter.TypeWithAnnotations : signatureParameters[i].TypeWithAnnotations; EnterParameter(parameter, parameterType); } Join(ref State, ref parameterDefaultsNotAssignedState); } private void EnterParameter(ParameterSymbol parameter, TypeWithAnnotations parameterType) { _variables.SetType(parameter, parameterType); if (parameter.RefKind != RefKind.Out) { int slot = GetOrCreateSlot(parameter); Debug.Assert(!IsConditionalState); if (slot > 0) { var state = GetParameterState(parameterType, parameter.FlowAnalysisAnnotations).State; this.State[slot] = state; if (EmptyStructTypeCache.IsTrackableStructType(parameterType.Type)) { InheritNullableStateOfTrackableStruct( parameterType.Type, slot, valueSlot: -1, isDefaultValue: parameter.ExplicitDefaultConstantValue?.IsNull == true); } } } } public override BoundNode? VisitParameterEqualsValue(BoundParameterEqualsValue equalsValue) { var parameter = equalsValue.Parameter; var parameterAnnotations = GetParameterAnnotations(parameter); var parameterLValueType = ApplyLValueAnnotations(parameter.TypeWithAnnotations, parameterAnnotations); var resultType = VisitOptionalImplicitConversion( equalsValue.Value, parameterLValueType, useLegacyWarnings: false, trackMembers: false, assignmentKind: AssignmentKind.Assignment); // If the LHS has annotations, we perform an additional check for nullable value types CheckDisallowedNullAssignment(resultType, parameterAnnotations, equalsValue.Value.Syntax.Location); return null; } internal static TypeWithState GetParameterState(TypeWithAnnotations parameterType, FlowAnalysisAnnotations parameterAnnotations) { if ((parameterAnnotations & FlowAnalysisAnnotations.AllowNull) != 0) { return TypeWithState.Create(parameterType.Type, NullableFlowState.MaybeDefault); } if ((parameterAnnotations & FlowAnalysisAnnotations.DisallowNull) != 0) { return TypeWithState.Create(parameterType.Type, NullableFlowState.NotNull); } return parameterType.ToTypeWithState(); } public sealed override BoundNode? VisitReturnStatement(BoundReturnStatement node) { Debug.Assert(!IsConditionalState); var expr = node.ExpressionOpt; if (expr == null) { EnforceDoesNotReturn(node.Syntax); PendingBranches.Add(new PendingBranch(node, this.State, label: null)); SetUnreachable(); return null; } // Should not convert to method return type when inferring return type (when _returnTypesOpt != null). if (_returnTypesOpt == null && TryGetReturnType(out TypeWithAnnotations returnType, out FlowAnalysisAnnotations returnAnnotations)) { if (node.RefKind == RefKind.None && returnType.Type.SpecialType == SpecialType.System_Boolean) { // visit the expression without unsplitting, then check parameters marked with flow analysis attributes Visit(expr); } else { TypeWithState returnState; if (node.RefKind == RefKind.None) { returnState = VisitOptionalImplicitConversion(expr, returnType, useLegacyWarnings: false, trackMembers: false, AssignmentKind.Return); } else { // return ref expr; returnState = VisitRefExpression(expr, returnType); } // If the return has annotations, we perform an additional check for nullable value types CheckDisallowedNullAssignment(returnState, ToInwardAnnotations(returnAnnotations), node.Syntax.Location, boundValueOpt: expr); } } else { var result = VisitRvalueWithState(expr); if (_returnTypesOpt != null) { _returnTypesOpt.Add((node, result.ToTypeWithAnnotations(compilation))); } } EnforceDoesNotReturn(node.Syntax); if (IsConditionalState) { var joinedState = this.StateWhenTrue.Clone(); Join(ref joinedState, ref this.StateWhenFalse); PendingBranches.Add(new PendingBranch(node, joinedState, label: null, this.IsConditionalState, this.StateWhenTrue, this.StateWhenFalse)); } else { PendingBranches.Add(new PendingBranch(node, this.State, label: null)); } Unsplit(); if (CurrentSymbol is MethodSymbol method) { EnforceNotNullIfNotNull(node.Syntax, this.State, method.Parameters, method.ReturnNotNullIfParameterNotNull, ResultType.State, outputParam: null); } SetUnreachable(); return null; } private TypeWithState VisitRefExpression(BoundExpression expr, TypeWithAnnotations destinationType) { Visit(expr); TypeWithState resultType = ResultType; if (!expr.IsSuppressed && RemoveConversion(expr, includeExplicitConversions: false).expression.Kind != BoundKind.ThrowExpression) { var lvalueResultType = LvalueResultType; if (IsNullabilityMismatch(lvalueResultType, destinationType)) { // declared types must match ReportNullabilityMismatchInAssignment(expr.Syntax, lvalueResultType, destinationType); } else { // types match, but state would let a null in ReportNullableAssignmentIfNecessary(expr, destinationType, resultType, useLegacyWarnings: false); } } return resultType; } private bool TryGetReturnType(out TypeWithAnnotations type, out FlowAnalysisAnnotations annotations) { var method = CurrentSymbol as MethodSymbol; if (method is null) { type = default; annotations = FlowAnalysisAnnotations.None; return false; } var delegateOrMethod = _useDelegateInvokeReturnType ? _delegateInvokeMethod! : method; var returnType = delegateOrMethod.ReturnTypeWithAnnotations; Debug.Assert((object)returnType != LambdaSymbol.ReturnTypeIsBeingInferred); if (returnType.IsVoidType()) { type = default; annotations = FlowAnalysisAnnotations.None; return false; } if (!method.IsAsync) { annotations = delegateOrMethod.ReturnTypeFlowAnalysisAnnotations; type = ApplyUnconditionalAnnotations(returnType, annotations); return true; } if (method.IsAsyncEffectivelyReturningGenericTask(compilation)) { type = ((NamedTypeSymbol)returnType.Type).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.Single(); annotations = FlowAnalysisAnnotations.None; return true; } type = default; annotations = FlowAnalysisAnnotations.None; return false; } public override BoundNode? VisitLocal(BoundLocal node) { var local = node.LocalSymbol; int slot = GetOrCreateSlot(local); var type = GetDeclaredLocalResult(local); if (!node.Type.Equals(type.Type, TypeCompareKind.ConsiderEverything | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes | TypeCompareKind.IgnoreDynamicAndTupleNames)) { // When the local is used before or during initialization, there can potentially be a mismatch between node.LocalSymbol.Type and node.Type. We // need to prefer node.Type as we shouldn't be changing the type of the BoundLocal node during rewrite. // https://github.com/dotnet/roslyn/issues/34158 Debug.Assert(node.Type.IsErrorType() || type.Type.IsErrorType()); type = TypeWithAnnotations.Create(node.Type, type.NullableAnnotation); } SetResult(node, GetAdjustedResult(type.ToTypeWithState(), slot), type); SplitIfBooleanConstant(node); return null; } public override BoundNode? VisitBlock(BoundBlock node) { DeclareLocals(node.Locals); VisitStatementsWithLocalFunctions(node); return null; } private void VisitStatementsWithLocalFunctions(BoundBlock block) { // Since the nullable flow state affects type information, and types can be queried by // the semantic model, there needs to be a single flow state input to a local function // that cannot be path-dependent. To decide the local starting state we Meet the state // of captured variables from all the uses of the local function, computing the // conservative combination of all potential starting states. // // For performance we split the analysis into two phases: the first phase where we // analyze everything except the local functions, hoping to visit all of the uses of the // local function, and then a pass where we visit the local functions. If there's no // recursion or calls between the local functions, the starting state of the local // function should be stable and we don't need a second pass. if (!TrackingRegions && !block.LocalFunctions.IsDefaultOrEmpty) { // First visit everything else foreach (var stmt in block.Statements) { if (stmt.Kind != BoundKind.LocalFunctionStatement) { VisitStatement(stmt); } } // Now visit the local function bodies foreach (var stmt in block.Statements) { if (stmt is BoundLocalFunctionStatement localFunc) { VisitLocalFunctionStatement(localFunc); } } } else { foreach (var stmt in block.Statements) { VisitStatement(stmt); } } } public override BoundNode? VisitLocalFunctionStatement(BoundLocalFunctionStatement node) { var localFunc = node.Symbol; var localFunctionState = GetOrCreateLocalFuncUsages(localFunc); // The starting state is the top state, but with captured // variables set according to Joining the state at all the // local function use sites var state = TopState(); var startingState = localFunctionState.StartingState; startingState.ForEach( (slot, variables) => { var symbol = variables[variables.RootSlot(slot)].Symbol; if (Symbol.IsCaptured(symbol, localFunc)) { state[slot] = startingState[slot]; } }, _variables); localFunctionState.Visited = true; AnalyzeLocalFunctionOrLambda( node, localFunc, state, delegateInvokeMethod: null, useDelegateInvokeParameterTypes: false, useDelegateInvokeReturnType: false); SetInvalidResult(); return null; } private Variables GetOrCreateNestedFunctionVariables(Variables container, MethodSymbol lambdaOrLocalFunction) { _nestedFunctionVariables ??= PooledDictionary<MethodSymbol, Variables>.GetInstance(); if (!_nestedFunctionVariables.TryGetValue(lambdaOrLocalFunction, out var variables)) { variables = container.CreateNestedMethodScope(lambdaOrLocalFunction); _nestedFunctionVariables.Add(lambdaOrLocalFunction, variables); } Debug.Assert((object?)variables.Container == container); return variables; } private void AnalyzeLocalFunctionOrLambda( IBoundLambdaOrFunction lambdaOrFunction, MethodSymbol lambdaOrFunctionSymbol, LocalState state, MethodSymbol? delegateInvokeMethod, bool useDelegateInvokeParameterTypes, bool useDelegateInvokeReturnType) { Debug.Assert(!useDelegateInvokeParameterTypes || delegateInvokeMethod is object); Debug.Assert(!useDelegateInvokeReturnType || delegateInvokeMethod is object); var oldSymbol = this.CurrentSymbol; this.CurrentSymbol = lambdaOrFunctionSymbol; var oldDelegateInvokeMethod = _delegateInvokeMethod; _delegateInvokeMethod = delegateInvokeMethod; var oldUseDelegateInvokeParameterTypes = _useDelegateInvokeParameterTypes; _useDelegateInvokeParameterTypes = useDelegateInvokeParameterTypes; var oldUseDelegateInvokeReturnType = _useDelegateInvokeReturnType; _useDelegateInvokeReturnType = useDelegateInvokeReturnType; var oldReturnTypes = _returnTypesOpt; _returnTypesOpt = null; var oldState = this.State; _variables = GetOrCreateNestedFunctionVariables(_variables, lambdaOrFunctionSymbol); this.State = state.CreateNestedMethodState(_variables); var previousSlot = _snapshotBuilderOpt?.EnterNewWalker(lambdaOrFunctionSymbol) ?? -1; try { var oldPending = SavePending(); EnterParameters(); var oldPending2 = SavePending(); // If this is an iterator, there's an implicit branch before the first statement // of the function where the enumerable is returned. if (lambdaOrFunctionSymbol.IsIterator) { PendingBranches.Add(new PendingBranch(null, this.State, null)); } VisitAlways(lambdaOrFunction.Body); RestorePending(oldPending2); // process any forward branches within the lambda body ImmutableArray<PendingBranch> pendingReturns = RemoveReturns(); RestorePending(oldPending); } finally { _snapshotBuilderOpt?.ExitWalker(this.SaveSharedState(), previousSlot); } _variables = _variables.Container!; this.State = oldState; _returnTypesOpt = oldReturnTypes; _useDelegateInvokeReturnType = oldUseDelegateInvokeReturnType; _useDelegateInvokeParameterTypes = oldUseDelegateInvokeParameterTypes; _delegateInvokeMethod = oldDelegateInvokeMethod; this.CurrentSymbol = oldSymbol; } protected override void VisitLocalFunctionUse( LocalFunctionSymbol symbol, LocalFunctionState localFunctionState, SyntaxNode syntax, bool isCall) { // Do not use this overload in NullableWalker. Use the overload below instead. throw ExceptionUtilities.Unreachable; } private void VisitLocalFunctionUse(LocalFunctionSymbol symbol) { Debug.Assert(!IsConditionalState); var localFunctionState = GetOrCreateLocalFuncUsages(symbol); var state = State.GetStateForVariables(localFunctionState.StartingState.Id); if (Join(ref localFunctionState.StartingState, ref state) && localFunctionState.Visited) { // If the starting state of the local function has changed and we've already visited // the local function, we need another pass stateChangedAfterUse = true; } } public override BoundNode? VisitDoStatement(BoundDoStatement node) { DeclareLocals(node.Locals); return base.VisitDoStatement(node); } public override BoundNode? VisitWhileStatement(BoundWhileStatement node) { DeclareLocals(node.Locals); return base.VisitWhileStatement(node); } public override BoundNode? VisitWithExpression(BoundWithExpression withExpr) { Debug.Assert(!IsConditionalState); var receiver = withExpr.Receiver; VisitRvalue(receiver); _ = CheckPossibleNullReceiver(receiver); var resultType = withExpr.CloneMethod?.ReturnTypeWithAnnotations ?? ResultType.ToTypeWithAnnotations(compilation); var resultState = ApplyUnconditionalAnnotations(resultType.ToTypeWithState(), GetRValueAnnotations(withExpr.CloneMethod)); var resultSlot = GetOrCreatePlaceholderSlot(withExpr); // carry over the null state of members of 'receiver' to the result of the with-expression. TrackNullableStateForAssignment(receiver, resultType, resultSlot, resultState, MakeSlot(receiver)); // use the declared nullability of Clone() for the top-level nullability of the result of the with-expression. SetResult(withExpr, resultState, resultType); VisitObjectCreationInitializer(containingSymbol: null, resultSlot, withExpr.InitializerExpression, FlowAnalysisAnnotations.None); // Note: this does not account for the scenario where `Clone()` returns maybe-null and the with-expression has no initializers. // Tracking in https://github.com/dotnet/roslyn/issues/44759 return null; } public override BoundNode? VisitForStatement(BoundForStatement node) { DeclareLocals(node.OuterLocals); DeclareLocals(node.InnerLocals); return base.VisitForStatement(node); } public override BoundNode? VisitForEachStatement(BoundForEachStatement node) { DeclareLocals(node.IterationVariables); return base.VisitForEachStatement(node); } public override BoundNode? VisitUsingStatement(BoundUsingStatement node) { DeclareLocals(node.Locals); Visit(node.AwaitOpt); return base.VisitUsingStatement(node); } public override BoundNode? VisitUsingLocalDeclarations(BoundUsingLocalDeclarations node) { Visit(node.AwaitOpt); return base.VisitUsingLocalDeclarations(node); } public override BoundNode? VisitFixedStatement(BoundFixedStatement node) { DeclareLocals(node.Locals); return base.VisitFixedStatement(node); } public override BoundNode? VisitConstructorMethodBody(BoundConstructorMethodBody node) { DeclareLocals(node.Locals); return base.VisitConstructorMethodBody(node); } private void DeclareLocal(LocalSymbol local) { if (local.DeclarationKind != LocalDeclarationKind.None) { int slot = GetOrCreateSlot(local); if (slot > 0) { this.State[slot] = GetDefaultState(ref this.State, slot); InheritDefaultState(GetDeclaredLocalResult(local).Type, slot); } } } private void DeclareLocals(ImmutableArray<LocalSymbol> locals) { foreach (var local in locals) { DeclareLocal(local); } } public override BoundNode? VisitLocalDeclaration(BoundLocalDeclaration node) { var local = node.LocalSymbol; int slot = GetOrCreateSlot(local); // We need visit the optional arguments so that we can return nullability information // about them, but we don't want to communicate any information about anything underneath. // Additionally, tests like Scope_DeclaratorArguments_06 can have conditional expressions // in the optional arguments that can leave us in a split state, so we want to make sure // we are not in a conditional state after. Debug.Assert(!IsConditionalState); var oldDisable = _disableDiagnostics; _disableDiagnostics = true; var currentState = State; VisitAndUnsplitAll(node.ArgumentsOpt); _disableDiagnostics = oldDisable; SetState(currentState); if (node.DeclaredTypeOpt != null) { VisitTypeExpression(node.DeclaredTypeOpt); } var initializer = node.InitializerOpt; if (initializer is null) { return null; } TypeWithAnnotations type = local.TypeWithAnnotations; TypeWithState valueType; bool inferredType = node.InferredType; if (local.IsRef) { valueType = VisitRefExpression(initializer, type); } else { valueType = VisitOptionalImplicitConversion(initializer, targetTypeOpt: inferredType ? default : type, useLegacyWarnings: true, trackMembers: true, AssignmentKind.Assignment); } if (inferredType) { if (valueType.HasNullType) { Debug.Assert(type.Type.IsErrorType()); valueType = type.ToTypeWithState(); } type = valueType.ToAnnotatedTypeWithAnnotations(compilation); _variables.SetType(local, type); if (node.DeclaredTypeOpt != null) { SetAnalyzedNullability(node.DeclaredTypeOpt, new VisitResult(type.ToTypeWithState(), type), true); } } TrackNullableStateForAssignment(initializer, type, slot, valueType, MakeSlot(initializer)); return null; } protected override BoundExpression? VisitExpressionWithoutStackGuard(BoundExpression node) { Debug.Assert(!IsConditionalState); SetInvalidResult(); _ = base.VisitExpressionWithoutStackGuard(node); TypeWithState resultType = ResultType; #if DEBUG // Verify Visit method set _result. Debug.Assert((object?)resultType.Type != _invalidType.Type); Debug.Assert(AreCloseEnough(resultType.Type, node.Type)); #endif if (ShouldMakeNotNullRvalue(node)) { var result = resultType.WithNotNullState(); SetResult(node, result, LvalueResultType); } return null; } #if DEBUG // For asserts only. private static bool AreCloseEnough(TypeSymbol? typeA, TypeSymbol? typeB) { // https://github.com/dotnet/roslyn/issues/34993: We should be able to tighten this to ensure that we're actually always returning the same type, // not error if one is null or ignoring certain types if ((object?)typeA == typeB) { return true; } if (typeA is null || typeB is null) { return typeA?.IsErrorType() != false && typeB?.IsErrorType() != false; } return canIgnoreAnyType(typeA) || canIgnoreAnyType(typeB) || typeA.Equals(typeB, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes | TypeCompareKind.IgnoreDynamicAndTupleNames); // Ignore TupleElementNames (see https://github.com/dotnet/roslyn/issues/23651). bool canIgnoreAnyType(TypeSymbol type) { return type.VisitType((t, unused1, unused2) => canIgnoreType(t), (object?)null) is object; } bool canIgnoreType(TypeSymbol type) { return type.IsErrorType() || type.IsDynamic() || type.HasUseSiteError || (type.IsAnonymousType && canIgnoreAnonymousType((NamedTypeSymbol)type)); } bool canIgnoreAnonymousType(NamedTypeSymbol type) { return AnonymousTypeManager.GetAnonymousTypePropertyTypesWithAnnotations(type).Any(t => canIgnoreAnyType(t.Type)); } } private static bool AreCloseEnough(Symbol original, Symbol updated) { // When https://github.com/dotnet/roslyn/issues/38195 is fixed, this workaround needs to be removed if (original is ConstructedMethodSymbol || updated is ConstructedMethodSymbol) { return AreCloseEnough(original.OriginalDefinition, updated.OriginalDefinition); } return (original, updated) switch { (LambdaSymbol l, NamedTypeSymbol n) _ when n.IsDelegateType() => AreLambdaAndNewDelegateSimilar(l, n), (FieldSymbol { ContainingType: { IsTupleType: true }, TupleElementIndex: var oi } originalField, FieldSymbol { ContainingType: { IsTupleType: true }, TupleElementIndex: var ui } updatedField) => originalField.Type.Equals(updatedField.Type, TypeCompareKind.AllNullableIgnoreOptions | TypeCompareKind.IgnoreTupleNames) && oi == ui, _ => original.Equals(updated, TypeCompareKind.AllNullableIgnoreOptions | TypeCompareKind.IgnoreTupleNames) }; } #endif private static bool AreLambdaAndNewDelegateSimilar(LambdaSymbol l, NamedTypeSymbol n) { var invokeMethod = n.DelegateInvokeMethod; return invokeMethod!.Parameters.SequenceEqual(l.Parameters, (p1, p2) => p1.Type.Equals(p2.Type, TypeCompareKind.AllNullableIgnoreOptions | TypeCompareKind.IgnoreTupleNames)) && invokeMethod.ReturnType.Equals(l.ReturnType, TypeCompareKind.AllNullableIgnoreOptions | TypeCompareKind.IgnoreTupleNames); } public override BoundNode? Visit(BoundNode? node) { return Visit(node, expressionIsRead: true); } private BoundNode VisitLValue(BoundNode node) { return Visit(node, expressionIsRead: false); } private BoundNode Visit(BoundNode? node, bool expressionIsRead) { bool originalExpressionIsRead = _expressionIsRead; _expressionIsRead = expressionIsRead; TakeIncrementalSnapshot(node); var result = base.Visit(node); _expressionIsRead = originalExpressionIsRead; return result; } protected override void VisitStatement(BoundStatement statement) { SetInvalidResult(); base.VisitStatement(statement); SetInvalidResult(); } public override BoundNode? VisitObjectCreationExpression(BoundObjectCreationExpression node) { Debug.Assert(!IsConditionalState); var arguments = node.Arguments; var argumentResults = VisitArguments(node, arguments, node.ArgumentRefKindsOpt, node.Constructor, node.ArgsToParamsOpt, node.DefaultArguments, node.Expanded, invokedAsExtensionMethod: false).results; VisitObjectOrDynamicObjectCreation(node, arguments, argumentResults, node.InitializerExpressionOpt); return null; } public override BoundNode? VisitUnconvertedObjectCreationExpression(BoundUnconvertedObjectCreationExpression node) { // This method is only involved in method inference with unbound lambdas. // The diagnostics on arguments are reported by VisitObjectCreationExpression. SetResultType(node, TypeWithState.Create(null, NullableFlowState.NotNull)); return null; } private void VisitObjectOrDynamicObjectCreation( BoundExpression node, ImmutableArray<BoundExpression> arguments, ImmutableArray<VisitArgumentResult> argumentResults, BoundExpression? initializerOpt) { Debug.Assert(node.Kind == BoundKind.ObjectCreationExpression || node.Kind == BoundKind.DynamicObjectCreationExpression || node.Kind == BoundKind.NewT); var argumentTypes = argumentResults.SelectAsArray(ar => ar.RValueType); int slot = -1; var type = node.Type; var resultState = NullableFlowState.NotNull; if (type is object) { slot = GetOrCreatePlaceholderSlot(node); if (slot > 0) { var boundObjectCreationExpression = node as BoundObjectCreationExpression; var constructor = boundObjectCreationExpression?.Constructor; bool isDefaultValueTypeConstructor = constructor?.IsDefaultValueTypeConstructor(requireZeroInit: true) == true; if (EmptyStructTypeCache.IsTrackableStructType(type)) { var containingType = constructor?.ContainingType; if (containingType?.IsTupleType == true && !isDefaultValueTypeConstructor) { // new System.ValueTuple<T1, ..., TN>(e1, ..., eN) TrackNullableStateOfTupleElements(slot, containingType, arguments, argumentTypes, boundObjectCreationExpression!.ArgsToParamsOpt, useRestField: true); } else { InheritNullableStateOfTrackableStruct( type, slot, valueSlot: -1, isDefaultValue: isDefaultValueTypeConstructor); } } else if (type.IsNullableType()) { if (isDefaultValueTypeConstructor) { // a nullable value type created with its default constructor is by definition null resultState = NullableFlowState.MaybeNull; } else if (constructor?.ParameterCount == 1) { // if we deal with one-parameter ctor that takes underlying, then Value state is inferred from the argument. var parameterType = constructor.ParameterTypesWithAnnotations[0]; if (AreNullableAndUnderlyingTypes(type, parameterType.Type, out TypeWithAnnotations underlyingType)) { var operand = arguments[0]; int valueSlot = MakeSlot(operand); if (valueSlot > 0) { TrackNullableStateOfNullableValue(slot, type, operand, underlyingType.ToTypeWithState(), valueSlot); } } } } this.State[slot] = resultState; } } if (initializerOpt != null) { VisitObjectCreationInitializer(containingSymbol: null, slot, initializerOpt, leftAnnotations: FlowAnalysisAnnotations.None); } SetResultType(node, TypeWithState.Create(type, resultState)); } private void VisitObjectCreationInitializer(Symbol? containingSymbol, int containingSlot, BoundExpression node, FlowAnalysisAnnotations leftAnnotations) { TakeIncrementalSnapshot(node); switch (node) { case BoundObjectInitializerExpression objectInitializer: checkImplicitReceiver(objectInitializer); foreach (var initializer in objectInitializer.Initializers) { switch (initializer.Kind) { case BoundKind.AssignmentOperator: VisitObjectElementInitializer(containingSlot, (BoundAssignmentOperator)initializer); break; default: VisitRvalue(initializer); break; } } SetNotNullResult(objectInitializer.Placeholder); break; case BoundCollectionInitializerExpression collectionInitializer: checkImplicitReceiver(collectionInitializer); foreach (var initializer in collectionInitializer.Initializers) { switch (initializer.Kind) { case BoundKind.CollectionElementInitializer: VisitCollectionElementInitializer((BoundCollectionElementInitializer)initializer); break; default: VisitRvalue(initializer); break; } } SetNotNullResult(collectionInitializer.Placeholder); break; default: Debug.Assert(containingSymbol is object); if (containingSymbol is object) { var type = ApplyLValueAnnotations(containingSymbol.GetTypeOrReturnType(), leftAnnotations); TypeWithState resultType = VisitOptionalImplicitConversion(node, type, useLegacyWarnings: false, trackMembers: true, AssignmentKind.Assignment); TrackNullableStateForAssignment(node, type, containingSlot, resultType, MakeSlot(node)); } break; } void checkImplicitReceiver(BoundObjectInitializerExpressionBase node) { if (containingSlot >= 0 && !node.Initializers.IsEmpty) { if (!node.Type.IsValueType && State[containingSlot].MayBeNull()) { if (containingSymbol is null) { ReportDiagnostic(ErrorCode.WRN_NullReferenceReceiver, node.Syntax); } else { ReportDiagnostic(ErrorCode.WRN_NullReferenceInitializer, node.Syntax, containingSymbol); } } } } } private void VisitObjectElementInitializer(int containingSlot, BoundAssignmentOperator node) { TakeIncrementalSnapshot(node); var left = node.Left; switch (left.Kind) { case BoundKind.ObjectInitializerMember: { var objectInitializer = (BoundObjectInitializerMember)left; TakeIncrementalSnapshot(left); var symbol = objectInitializer.MemberSymbol; if (!objectInitializer.Arguments.IsDefaultOrEmpty) { VisitArguments(objectInitializer, objectInitializer.Arguments, objectInitializer.ArgumentRefKindsOpt, (PropertySymbol?)symbol, objectInitializer.ArgsToParamsOpt, objectInitializer.DefaultArguments, objectInitializer.Expanded); } if (symbol is object) { int slot = (containingSlot < 0 || !IsSlotMember(containingSlot, symbol)) ? -1 : GetOrCreateSlot(symbol, containingSlot); VisitObjectCreationInitializer(symbol, slot, node.Right, GetLValueAnnotations(node.Left)); // https://github.com/dotnet/roslyn/issues/35040: Should likely be setting _resultType in VisitObjectCreationInitializer // and using that value instead of reconstructing here } var result = new VisitResult(objectInitializer.Type, NullableAnnotation.NotAnnotated, NullableFlowState.NotNull); SetAnalyzedNullability(objectInitializer, result); SetAnalyzedNullability(node, result); } break; default: Visit(node); break; } } private new void VisitCollectionElementInitializer(BoundCollectionElementInitializer node) { // Note: we analyze even omitted calls (var reinferredMethod, _, _) = VisitArguments(node, node.Arguments, refKindsOpt: default, node.AddMethod, node.ArgsToParamsOpt, node.DefaultArguments, node.Expanded, node.InvokedAsExtensionMethod); Debug.Assert(reinferredMethod is object); if (node.ImplicitReceiverOpt != null) { Debug.Assert(node.ImplicitReceiverOpt.Kind == BoundKind.ObjectOrCollectionValuePlaceholder); SetAnalyzedNullability(node.ImplicitReceiverOpt, new VisitResult(node.ImplicitReceiverOpt.Type, NullableAnnotation.NotAnnotated, NullableFlowState.NotNull)); } SetUnknownResultNullability(node); SetUpdatedSymbol(node, node.AddMethod, reinferredMethod); } private void SetNotNullResult(BoundExpression node) { SetResultType(node, TypeWithState.Create(node.Type, NullableFlowState.NotNull)); } /// <summary> /// Returns true if the type is a struct with no fields or properties. /// </summary> protected override bool IsEmptyStructType(TypeSymbol type) { if (type.TypeKind != TypeKind.Struct) { return false; } // EmptyStructTypeCache.IsEmptyStructType() returns false // if there are non-cyclic fields. if (!_emptyStructTypeCache.IsEmptyStructType(type)) { return false; } if (type.SpecialType != SpecialType.None) { return true; } var members = ((NamedTypeSymbol)type).GetMembersUnordered(); // EmptyStructTypeCache.IsEmptyStructType() returned true. If there are fields, // at least one of those fields must be cyclic, so treat the type as empty. if (members.Any(m => m.Kind == SymbolKind.Field)) { return true; } // If there are properties, the type is not empty. if (members.Any(m => m.Kind == SymbolKind.Property)) { return false; } return true; } private int GetOrCreatePlaceholderSlot(BoundExpression node) { Debug.Assert(node.Type is object); if (IsEmptyStructType(node.Type)) { return -1; } return GetOrCreatePlaceholderSlot(node, TypeWithAnnotations.Create(node.Type, NullableAnnotation.NotAnnotated)); } private int GetOrCreatePlaceholderSlot(object identifier, TypeWithAnnotations type) { _placeholderLocalsOpt ??= PooledDictionary<object, PlaceholderLocal>.GetInstance(); if (!_placeholderLocalsOpt.TryGetValue(identifier, out var placeholder)) { placeholder = new PlaceholderLocal(CurrentSymbol, identifier, type); _placeholderLocalsOpt.Add(identifier, placeholder); } Debug.Assert((object)placeholder != null); return GetOrCreateSlot(placeholder, forceSlotEvenIfEmpty: true); } public override BoundNode? VisitAnonymousObjectCreationExpression(BoundAnonymousObjectCreationExpression node) { Debug.Assert(!IsConditionalState); Debug.Assert(node.Type.IsAnonymousType); var anonymousType = (NamedTypeSymbol)node.Type; var arguments = node.Arguments; var argumentTypes = arguments.SelectAsArray((arg, self) => self.VisitRvalueWithState(arg), this); var argumentsWithAnnotations = argumentTypes.SelectAsArray(arg => arg.ToTypeWithAnnotations(compilation)); if (argumentsWithAnnotations.All(argType => argType.HasType)) { anonymousType = AnonymousTypeManager.ConstructAnonymousTypeSymbol(anonymousType, argumentsWithAnnotations); int receiverSlot = GetOrCreatePlaceholderSlot(node); int currentDeclarationIndex = 0; for (int i = 0; i < arguments.Length; i++) { var argument = arguments[i]; var argumentType = argumentTypes[i]; var property = AnonymousTypeManager.GetAnonymousTypeProperty(anonymousType, i); if (property.Type.SpecialType != SpecialType.System_Void) { // A void element results in an error type in the anonymous type but not in the property's container! // To avoid failing an assertion later, we skip them. var slot = GetOrCreateSlot(property, receiverSlot); TrackNullableStateForAssignment(argument, property.TypeWithAnnotations, slot, argumentType, MakeSlot(argument)); var currentDeclaration = getDeclaration(node, property, ref currentDeclarationIndex); if (currentDeclaration is object) { TakeIncrementalSnapshot(currentDeclaration); SetAnalyzedNullability(currentDeclaration, new VisitResult(argumentType, property.TypeWithAnnotations)); } } } } SetResultType(node, TypeWithState.Create(anonymousType, NullableFlowState.NotNull)); return null; static BoundAnonymousPropertyDeclaration? getDeclaration(BoundAnonymousObjectCreationExpression node, PropertySymbol currentProperty, ref int currentDeclarationIndex) { if (currentDeclarationIndex >= node.Declarations.Length) { return null; } var currentDeclaration = node.Declarations[currentDeclarationIndex]; if (currentDeclaration.Property.MemberIndexOpt == currentProperty.MemberIndexOpt) { currentDeclarationIndex++; return currentDeclaration; } return null; } } public override BoundNode? VisitArrayCreation(BoundArrayCreation node) { foreach (var expr in node.Bounds) { VisitRvalue(expr); } var initialization = node.InitializerOpt; if (initialization is null) { SetResultType(node, TypeWithState.Create(node.Type, NullableFlowState.NotNull)); return null; } TakeIncrementalSnapshot(initialization); var expressions = ArrayBuilder<BoundExpression>.GetInstance(initialization.Initializers.Length); GetArrayElements(initialization, expressions); int n = expressions.Count; // Consider recording in the BoundArrayCreation // whether the array was implicitly typed, rather than relying on syntax. bool isInferred = node.Syntax.Kind() == SyntaxKind.ImplicitArrayCreationExpression; var arrayType = (ArrayTypeSymbol)node.Type; var elementType = arrayType.ElementTypeWithAnnotations; if (!isInferred) { foreach (var expr in expressions) { _ = VisitOptionalImplicitConversion(expr, elementType, useLegacyWarnings: false, trackMembers: false, AssignmentKind.Assignment); } } else { var expressionsNoConversions = ArrayBuilder<BoundExpression>.GetInstance(n); var conversions = ArrayBuilder<Conversion>.GetInstance(n); var resultTypes = ArrayBuilder<TypeWithState>.GetInstance(n); var placeholderBuilder = ArrayBuilder<BoundExpression>.GetInstance(n); foreach (var expression in expressions) { // collect expressions, conversions and result types (BoundExpression expressionNoConversion, Conversion conversion) = RemoveConversion(expression, includeExplicitConversions: false); expressionsNoConversions.Add(expressionNoConversion); conversions.Add(conversion); SnapshotWalkerThroughConversionGroup(expression, expressionNoConversion); var resultType = VisitRvalueWithState(expressionNoConversion); resultTypes.Add(resultType); placeholderBuilder.Add(CreatePlaceholderIfNecessary(expressionNoConversion, resultType.ToTypeWithAnnotations(compilation))); } var placeholders = placeholderBuilder.ToImmutableAndFree(); TypeSymbol? bestType = null; if (!node.HasErrors) { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; bestType = BestTypeInferrer.InferBestType(placeholders, _conversions, ref discardedUseSiteInfo); } TypeWithAnnotations inferredType = (bestType is null) ? elementType.SetUnknownNullabilityForReferenceTypes() : TypeWithAnnotations.Create(bestType); if (bestType is object) { // Convert elements to best type to determine element top-level nullability and to report nested nullability warnings for (int i = 0; i < n; i++) { var expressionNoConversion = expressionsNoConversions[i]; var expression = GetConversionIfApplicable(expressions[i], expressionNoConversion); resultTypes[i] = VisitConversion(expression, expressionNoConversion, conversions[i], inferredType, resultTypes[i], checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Assignment, reportRemainingWarnings: true, reportTopLevelWarnings: false); } // Set top-level nullability on inferred element type var elementState = BestTypeInferrer.GetNullableState(resultTypes); inferredType = TypeWithState.Create(inferredType.Type, elementState).ToTypeWithAnnotations(compilation); for (int i = 0; i < n; i++) { // Report top-level warnings _ = VisitConversion(conversionOpt: null, conversionOperand: expressionsNoConversions[i], Conversion.Identity, targetTypeWithNullability: inferredType, operandType: resultTypes[i], checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Assignment, reportRemainingWarnings: false); } } else { // We need to ensure that we're tracking the inferred type with nullability of any conversions that // were stripped off. for (int i = 0; i < n; i++) { TrackAnalyzedNullabilityThroughConversionGroup(inferredType.ToTypeWithState(), expressions[i] as BoundConversion, expressionsNoConversions[i]); } } expressionsNoConversions.Free(); conversions.Free(); resultTypes.Free(); arrayType = arrayType.WithElementType(inferredType); } expressions.Free(); SetResultType(node, TypeWithState.Create(arrayType, NullableFlowState.NotNull)); return null; } /// <summary> /// Applies analysis similar to <see cref="VisitArrayCreation"/>. /// The expressions returned from a lambda are not converted though, so we'll have to classify fresh conversions. /// Note: even if some conversions fail, we'll proceed to infer top-level nullability. That is reasonable in common cases. /// </summary> internal static TypeWithAnnotations BestTypeForLambdaReturns( ArrayBuilder<(BoundExpression, TypeWithAnnotations)> returns, Binder binder, BoundNode node, Conversions conversions) { var walker = new NullableWalker(binder.Compilation, symbol: null, useConstructorExitWarnings: false, useDelegateInvokeParameterTypes: false, useDelegateInvokeReturnType: false, delegateInvokeMethodOpt: null, node, binder, conversions: conversions, variables: null, returnTypesOpt: null, analyzedNullabilityMapOpt: null, snapshotBuilderOpt: null); int n = returns.Count; var resultTypes = ArrayBuilder<TypeWithAnnotations>.GetInstance(n); var placeholdersBuilder = ArrayBuilder<BoundExpression>.GetInstance(n); for (int i = 0; i < n; i++) { var (returnExpr, resultType) = returns[i]; resultTypes.Add(resultType); placeholdersBuilder.Add(CreatePlaceholderIfNecessary(returnExpr, resultType)); } var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var placeholders = placeholdersBuilder.ToImmutableAndFree(); TypeSymbol? bestType = BestTypeInferrer.InferBestType(placeholders, walker._conversions, ref discardedUseSiteInfo); TypeWithAnnotations inferredType; if (bestType is { }) { // Note: so long as we have a best type, we can proceed. var bestTypeWithObliviousAnnotation = TypeWithAnnotations.Create(bestType); ConversionsBase conversionsWithoutNullability = walker._conversions.WithNullability(false); for (int i = 0; i < n; i++) { BoundExpression placeholder = placeholders[i]; Conversion conversion = conversionsWithoutNullability.ClassifyConversionFromExpression(placeholder, bestType, ref discardedUseSiteInfo); resultTypes[i] = walker.VisitConversion(conversionOpt: null, placeholder, conversion, bestTypeWithObliviousAnnotation, resultTypes[i].ToTypeWithState(), checkConversion: false, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Return, reportRemainingWarnings: false, reportTopLevelWarnings: false).ToTypeWithAnnotations(binder.Compilation); } // Set top-level nullability on inferred type inferredType = TypeWithAnnotations.Create(bestType, BestTypeInferrer.GetNullableAnnotation(resultTypes)); } else { inferredType = default; } resultTypes.Free(); walker.Free(); return inferredType; } private static void GetArrayElements(BoundArrayInitialization node, ArrayBuilder<BoundExpression> builder) { foreach (var child in node.Initializers) { if (child.Kind == BoundKind.ArrayInitialization) { GetArrayElements((BoundArrayInitialization)child, builder); } else { builder.Add(child); } } } public override BoundNode? VisitArrayAccess(BoundArrayAccess node) { Debug.Assert(!IsConditionalState); Visit(node.Expression); Debug.Assert(!IsConditionalState); Debug.Assert(!node.Expression.Type!.IsValueType); // https://github.com/dotnet/roslyn/issues/30598: Mark receiver as not null // after indices have been visited, and only if the receiver has not changed. _ = CheckPossibleNullReceiver(node.Expression); var type = ResultType.Type as ArrayTypeSymbol; foreach (var i in node.Indices) { VisitRvalue(i); } TypeWithAnnotations result; if (node.Indices.Length == 1 && TypeSymbol.Equals(node.Indices[0].Type, compilation.GetWellKnownType(WellKnownType.System_Range), TypeCompareKind.ConsiderEverything2)) { result = TypeWithAnnotations.Create(type); } else { result = type?.ElementTypeWithAnnotations ?? default; } SetLvalueResultType(node, result); return null; } private TypeWithState InferResultNullability(BinaryOperatorKind operatorKind, MethodSymbol? methodOpt, TypeSymbol resultType, TypeWithState leftType, TypeWithState rightType) { NullableFlowState resultState = NullableFlowState.NotNull; if (operatorKind.IsUserDefined()) { if (methodOpt?.ParameterCount == 2) { if (operatorKind.IsLifted() && !operatorKind.IsComparison()) { return GetLiftedReturnType(methodOpt.ReturnTypeWithAnnotations, leftType.State.Join(rightType.State)); } var resultTypeWithState = GetReturnTypeWithState(methodOpt); if ((leftType.IsNotNull && methodOpt.ReturnNotNullIfParameterNotNull.Contains(methodOpt.Parameters[0].Name)) || (rightType.IsNotNull && methodOpt.ReturnNotNullIfParameterNotNull.Contains(methodOpt.Parameters[1].Name))) { resultTypeWithState = resultTypeWithState.WithNotNullState(); } return resultTypeWithState; } } else if (!operatorKind.IsDynamic() && !resultType.IsValueType) { switch (operatorKind.Operator() | operatorKind.OperandTypes()) { case BinaryOperatorKind.DelegateCombination: resultState = leftType.State.Meet(rightType.State); break; case BinaryOperatorKind.DelegateRemoval: resultState = NullableFlowState.MaybeNull; // Delegate removal can produce null. break; default: resultState = NullableFlowState.NotNull; break; } } if (operatorKind.IsLifted() && !operatorKind.IsComparison()) { resultState = leftType.State.Join(rightType.State); } return TypeWithState.Create(resultType, resultState); } protected override void VisitBinaryOperatorChildren(ArrayBuilder<BoundBinaryOperator> stack) { var binary = stack.Pop(); var (leftOperand, leftConversion) = RemoveConversion(binary.Left, includeExplicitConversions: false); // Only the leftmost operator of a left-associative binary operator chain can learn from a conditional access on the left // For simplicity, we just special case it here. // For example, `a?.b(out x) == true` has a conditional access on the left of the operator, // but `expr == a?.b(out x) == true` has a conditional access on the right of the operator if (VisitPossibleConditionalAccess(leftOperand, out var conditionalStateWhenNotNull) && CanPropagateStateWhenNotNull(leftConversion) && binary.OperatorKind.Operator() is BinaryOperatorKind.Equal or BinaryOperatorKind.NotEqual) { Debug.Assert(!IsConditionalState); var leftType = ResultType; var (rightOperand, rightConversion) = RemoveConversion(binary.Right, includeExplicitConversions: false); // Consider the following two scenarios: // `a?.b(x = new object()) == c.d(x = null)` // `x` is maybe-null after expression // `a?.b(x = null) == c.d(x = new object())` // `x` is not-null after expression // In this scenario, we visit the RHS twice: // (1) Once using the single "stateWhenNotNull" after the LHS, in order to update the "stateWhenNotNull" with the effects of the RHS // (2) Once using the "worst case" state after the LHS for diagnostics and public API // After the two visits of the RHS, we may set a conditional state using the state after (1) as the StateWhenTrue and the state after (2) as the StateWhenFalse. // Depending on whether `==` or `!=` was used, and depending on the value of the RHS, we may then swap the StateWhenTrue with the StateWhenFalse. var oldDisableDiagnostics = _disableDiagnostics; _disableDiagnostics = true; var stateAfterLeft = this.State; SetState(getUnconditionalStateWhenNotNull(rightOperand, conditionalStateWhenNotNull)); VisitRvalue(rightOperand); var stateWhenNotNull = this.State; _disableDiagnostics = oldDisableDiagnostics; // Now visit the right side for public API and diagnostics using the worst-case state from the LHS. // Note that we do this visit last to try and make sure that the "visit for public API" overwrites walker state recorded during previous visits where possible. SetState(stateAfterLeft); var rightType = VisitRvalueWithState(rightOperand); ReinferBinaryOperatorAndSetResult(leftOperand, leftConversion, leftType, rightOperand, rightConversion, rightType, binary); if (isKnownNullOrNotNull(rightOperand, rightType)) { var isNullConstant = rightOperand.ConstantValue?.IsNull == true; SetConditionalState(isNullConstant == isEquals(binary) ? (State, stateWhenNotNull) : (stateWhenNotNull, State)); } if (stack.Count == 0) { return; } leftOperand = binary; leftConversion = Conversion.Identity; binary = stack.Pop(); } while (true) { if (!learnFromConditionalAccessOrBoolConstant()) { Unsplit(); // VisitRvalue does this UseRvalueOnly(leftOperand); // drop lvalue part AfterLeftChildHasBeenVisited(leftOperand, leftConversion, binary); } if (stack.Count == 0) { break; } leftOperand = binary; leftConversion = Conversion.Identity; binary = stack.Pop(); } static bool isEquals(BoundBinaryOperator binary) => binary.OperatorKind.Operator() == BinaryOperatorKind.Equal; static bool isKnownNullOrNotNull(BoundExpression expr, TypeWithState resultType) { return resultType.State.IsNotNull() || expr.ConstantValue is object; } LocalState getUnconditionalStateWhenNotNull(BoundExpression otherOperand, PossiblyConditionalState conditionalStateWhenNotNull) { LocalState stateWhenNotNull; if (!conditionalStateWhenNotNull.IsConditionalState) { stateWhenNotNull = conditionalStateWhenNotNull.State; } else if (isEquals(binary) && otherOperand.ConstantValue is { IsBoolean: true, BooleanValue: var boolValue }) { // can preserve conditional state from `.TryGetValue` in `dict?.TryGetValue(key, out value) == true`, // but not in `dict?.TryGetValue(key, out value) != false` stateWhenNotNull = boolValue ? conditionalStateWhenNotNull.StateWhenTrue : conditionalStateWhenNotNull.StateWhenFalse; } else { stateWhenNotNull = conditionalStateWhenNotNull.StateWhenTrue; Join(ref stateWhenNotNull, ref conditionalStateWhenNotNull.StateWhenFalse); } return stateWhenNotNull; } // Returns true if `binary.Right` was visited by the call. bool learnFromConditionalAccessOrBoolConstant() { if (binary.OperatorKind.Operator() is not (BinaryOperatorKind.Equal or BinaryOperatorKind.NotEqual)) { return false; } var leftResult = ResultType; var (rightOperand, rightConversion) = RemoveConversion(binary.Right, includeExplicitConversions: false); // `true == a?.b(out x)` if (isKnownNullOrNotNull(leftOperand, leftResult) && CanPropagateStateWhenNotNull(rightConversion) && TryVisitConditionalAccess(rightOperand, out var conditionalStateWhenNotNull)) { ReinferBinaryOperatorAndSetResult(leftOperand, leftConversion, leftResult, rightOperand, rightConversion, rightType: ResultType, binary); var stateWhenNotNull = getUnconditionalStateWhenNotNull(leftOperand, conditionalStateWhenNotNull); var isNullConstant = leftOperand.ConstantValue?.IsNull == true; SetConditionalState(isNullConstant == isEquals(binary) ? (State, stateWhenNotNull) : (stateWhenNotNull, State)); return true; } // can only learn from a bool constant operand here if it's using the built in `bool operator ==(bool left, bool right)` if (binary.OperatorKind.IsUserDefined()) { return false; } // `(x != null) == true` if (IsConditionalState && binary.Right.ConstantValue is { IsBoolean: true } rightConstant) { var (stateWhenTrue, stateWhenFalse) = (StateWhenTrue.Clone(), StateWhenFalse.Clone()); Unsplit(); Visit(binary.Right); UseRvalueOnly(binary.Right); // record result for the right SetConditionalState(isEquals(binary) == rightConstant.BooleanValue ? (stateWhenTrue, stateWhenFalse) : (stateWhenFalse, stateWhenTrue)); } // `true == (x != null)` else if (binary.Left.ConstantValue is { IsBoolean: true } leftConstant) { Unsplit(); Visit(binary.Right); UseRvalueOnly(binary.Right); if (IsConditionalState && isEquals(binary) != leftConstant.BooleanValue) { SetConditionalState(StateWhenFalse, StateWhenTrue); } } else { return false; } // record result for the binary Debug.Assert(binary.Type.SpecialType == SpecialType.System_Boolean); SetResult(binary, TypeWithState.ForType(binary.Type), TypeWithAnnotations.Create(binary.Type)); return true; } } private void ReinferBinaryOperatorAndSetResult( BoundExpression leftOperand, Conversion leftConversion, TypeWithState leftType, BoundExpression rightOperand, Conversion rightConversion, TypeWithState rightType, BoundBinaryOperator binary) { Debug.Assert(!IsConditionalState); // At this point, State.Reachable may be false for // invalid code such as `s + throw new Exception()`. var method = binary.Method; if (binary.OperatorKind.IsUserDefined() && method?.ParameterCount == 2) { // Update method based on inferred operand type. TypeSymbol methodContainer = method.ContainingType; bool isLifted = binary.OperatorKind.IsLifted(); TypeWithState leftUnderlyingType = GetNullableUnderlyingTypeIfNecessary(isLifted, leftType); TypeWithState rightUnderlyingType = GetNullableUnderlyingTypeIfNecessary(isLifted, rightType); TypeSymbol? asMemberOfType = getTypeIfContainingType(methodContainer, leftUnderlyingType.Type) ?? getTypeIfContainingType(methodContainer, rightUnderlyingType.Type); if (asMemberOfType is object) { method = (MethodSymbol)AsMemberOfType(asMemberOfType, method); } // Analyze operator call properly (honoring [Disallow|Allow|Maybe|NotNull] attribute annotations) https://github.com/dotnet/roslyn/issues/32671 var parameters = method.Parameters; visitOperandConversion(binary.Left, leftOperand, leftConversion, parameters[0], leftUnderlyingType); visitOperandConversion(binary.Right, rightOperand, rightConversion, parameters[1], rightUnderlyingType); SetUpdatedSymbol(binary, binary.Method!, method); void visitOperandConversion( BoundExpression expr, BoundExpression operand, Conversion conversion, ParameterSymbol parameter, TypeWithState operandType) { TypeWithAnnotations targetTypeWithNullability = parameter.TypeWithAnnotations; if (isLifted && targetTypeWithNullability.Type.IsNonNullableValueType()) { targetTypeWithNullability = TypeWithAnnotations.Create(MakeNullableOf(targetTypeWithNullability)); } _ = VisitConversion( expr as BoundConversion, operand, conversion, targetTypeWithNullability, operandType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Argument, parameter); } } else { // Assume this is a built-in operator in which case the parameter types are unannotated. visitOperandConversion(binary.Left, leftOperand, leftConversion, leftType); visitOperandConversion(binary.Right, rightOperand, rightConversion, rightType); void visitOperandConversion( BoundExpression expr, BoundExpression operand, Conversion conversion, TypeWithState operandType) { if (expr.Type is null) { Debug.Assert(operand == expr); } else { _ = VisitConversion( expr as BoundConversion, operand, conversion, TypeWithAnnotations.Create(expr.Type), operandType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Argument); } } } Debug.Assert(!IsConditionalState); // For nested binary operators, this can be the only time they're visited due to explicit stack used in AbstractFlowPass.VisitBinaryOperator, // so we need to set the flow-analyzed type here. var inferredResult = InferResultNullability(binary.OperatorKind, method, binary.Type, leftType, rightType); SetResult(binary, inferredResult, inferredResult.ToTypeWithAnnotations(compilation)); TypeSymbol? getTypeIfContainingType(TypeSymbol baseType, TypeSymbol? derivedType) { if (derivedType is null) { return null; } derivedType = derivedType.StrippedType(); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var conversion = _conversions.ClassifyBuiltInConversion(derivedType, baseType, ref discardedUseSiteInfo); if (conversion.Exists && !conversion.IsExplicit) { return derivedType; } return null; } } private void AfterLeftChildHasBeenVisited( BoundExpression leftOperand, Conversion leftConversion, BoundBinaryOperator binary) { Debug.Assert(!IsConditionalState); var leftType = ResultType; var (rightOperand, rightConversion) = RemoveConversion(binary.Right, includeExplicitConversions: false); VisitRvalue(rightOperand); var rightType = ResultType; ReinferBinaryOperatorAndSetResult(leftOperand, leftConversion, leftType, rightOperand, rightConversion, rightType, binary); BinaryOperatorKind op = binary.OperatorKind.Operator(); if (op == BinaryOperatorKind.Equal || op == BinaryOperatorKind.NotEqual) { // learn from null constant BoundExpression? operandComparedToNull = null; if (binary.Right.ConstantValue?.IsNull == true) { operandComparedToNull = binary.Left; } else if (binary.Left.ConstantValue?.IsNull == true) { operandComparedToNull = binary.Right; } if (operandComparedToNull != null) { // Set all nested conditional slots. For example in a?.b?.c we'll set a, b, and c. bool nonNullCase = op != BinaryOperatorKind.Equal; // true represents WhenTrue splitAndLearnFromNonNullTest(operandComparedToNull, whenTrue: nonNullCase); // `x == null` and `x != null` are pure null tests so update the null-state in the alternative branch too LearnFromNullTest(operandComparedToNull, ref nonNullCase ? ref StateWhenFalse : ref StateWhenTrue); return; } } // learn from comparison between non-null and maybe-null, possibly updating maybe-null to non-null BoundExpression? operandComparedToNonNull = null; if (leftType.IsNotNull && rightType.MayBeNull) { operandComparedToNonNull = binary.Right; } else if (rightType.IsNotNull && leftType.MayBeNull) { operandComparedToNonNull = binary.Left; } if (operandComparedToNonNull != null) { switch (op) { case BinaryOperatorKind.Equal: case BinaryOperatorKind.GreaterThan: case BinaryOperatorKind.LessThan: case BinaryOperatorKind.GreaterThanOrEqual: case BinaryOperatorKind.LessThanOrEqual: operandComparedToNonNull = SkipReferenceConversions(operandComparedToNonNull); splitAndLearnFromNonNullTest(operandComparedToNonNull, whenTrue: true); return; case BinaryOperatorKind.NotEqual: operandComparedToNonNull = SkipReferenceConversions(operandComparedToNonNull); splitAndLearnFromNonNullTest(operandComparedToNonNull, whenTrue: false); return; }; } void splitAndLearnFromNonNullTest(BoundExpression operandComparedToNonNull, bool whenTrue) { var slotBuilder = ArrayBuilder<int>.GetInstance(); GetSlotsToMarkAsNotNullable(operandComparedToNonNull, slotBuilder); if (slotBuilder.Count != 0) { Split(); ref LocalState stateToUpdate = ref whenTrue ? ref this.StateWhenTrue : ref this.StateWhenFalse; MarkSlotsAsNotNull(slotBuilder, ref stateToUpdate); } slotBuilder.Free(); } } protected override bool VisitInterpolatedStringHandlerParts(BoundInterpolatedStringBase node, bool usesBoolReturns, bool firstPartIsConditional, ref LocalState shortCircuitState) { var result = base.VisitInterpolatedStringHandlerParts(node, usesBoolReturns, firstPartIsConditional, ref shortCircuitState); SetNotNullResult(node); return result; } protected override void VisitInterpolatedStringBinaryOperatorNode(BoundBinaryOperator node) { SetNotNullResult(node); } /// <summary> /// If we learn that the operand is non-null, we can infer that certain /// sub-expressions were also non-null. /// Get all nested conditional slots for those sub-expressions. For example in a?.b?.c we'll set a, b, and c. /// Only returns slots for tracked expressions. /// </summary> /// <remarks>https://github.com/dotnet/roslyn/issues/53397 This method should potentially be removed.</remarks> private void GetSlotsToMarkAsNotNullable(BoundExpression operand, ArrayBuilder<int> slotBuilder) { Debug.Assert(operand != null); var previousConditionalAccessSlot = _lastConditionalAccessSlot; try { while (true) { // Due to the nature of binding, if there are conditional access they will be at the top of the bound tree, // potentially with a conversion on top of it. We go through any conditional accesses, adding slots for the // conditional receivers if they have them. If we ever get to a receiver that MakeSlot doesn't return a slot // for, nothing underneath is trackable and we bail at that point. Example: // // a?.GetB()?.C // a is a field, GetB is a method, and C is a property // // The top of the tree is the a?.GetB() conditional call. We'll ask for a slot for a, and we'll get one because // fields have slots. The AccessExpression of the BoundConditionalAccess is another BoundConditionalAccess, this time // with a receiver of the GetB() BoundCall. Attempting to get a slot for this receiver will fail, and we'll // return an array with just the slot for a. int slot; switch (operand.Kind) { case BoundKind.Conversion: // https://github.com/dotnet/roslyn/issues/33879 Detect when conversion has a nullable operand operand = ((BoundConversion)operand).Operand; continue; case BoundKind.AsOperator: operand = ((BoundAsOperator)operand).Operand; continue; case BoundKind.ConditionalAccess: var conditional = (BoundConditionalAccess)operand; GetSlotsToMarkAsNotNullable(conditional.Receiver, slotBuilder); slot = MakeSlot(conditional.Receiver); if (slot > 0) { // We need to continue the walk regardless of whether the receiver should be updated. var receiverType = conditional.Receiver.Type!; if (receiverType.IsNullableType()) slot = GetNullableOfTValueSlot(receiverType, slot, out _); } if (slot > 0) { // When MakeSlot is called on the nested AccessExpression, it will recurse through receivers // until it gets to the BoundConditionalReceiver associated with this node. In our override // of MakeSlot, we substitute this slot when we encounter a BoundConditionalReceiver, and reset the // _lastConditionalAccess field. _lastConditionalAccessSlot = slot; operand = conditional.AccessExpression; continue; } // If there's no slot for this receiver, there cannot be another slot for any of the remaining // access expressions. break; default: // Attempt to create a slot for the current thing. If there were any more conditional accesses, // they would have been on top, so this is the last thing we need to specially handle. // https://github.com/dotnet/roslyn/issues/33879 When we handle unconditional access survival (ie after // c.D has been invoked, c must be nonnull or we've thrown a NullRef), revisit whether // we need more special handling here slot = MakeSlot(operand); if (slot > 0 && PossiblyNullableType(operand.Type)) { slotBuilder.Add(slot); } break; } return; } } finally { _lastConditionalAccessSlot = previousConditionalAccessSlot; } } private static bool PossiblyNullableType([NotNullWhen(true)] TypeSymbol? operandType) => operandType?.CanContainNull() == true; private static void MarkSlotsAsNotNull(ArrayBuilder<int> slots, ref LocalState stateToUpdate) { foreach (int slot in slots) { stateToUpdate[slot] = NullableFlowState.NotNull; } } private void LearnFromNonNullTest(BoundExpression expression, ref LocalState state) { if (expression.Kind == BoundKind.AwaitableValuePlaceholder) { if (_awaitablePlaceholdersOpt != null && _awaitablePlaceholdersOpt.TryGetValue((BoundAwaitableValuePlaceholder)expression, out var value)) { expression = value.AwaitableExpression; } else { return; } } var slotBuilder = ArrayBuilder<int>.GetInstance(); GetSlotsToMarkAsNotNullable(expression, slotBuilder); MarkSlotsAsNotNull(slotBuilder, ref state); slotBuilder.Free(); } private void LearnFromNonNullTest(int slot, ref LocalState state) { state[slot] = NullableFlowState.NotNull; } private void LearnFromNullTest(BoundExpression expression, ref LocalState state) { // nothing to learn about a constant if (expression.ConstantValue != null) return; // We should not blindly strip conversions here. Tracked by https://github.com/dotnet/roslyn/issues/36164 var expressionWithoutConversion = RemoveConversion(expression, includeExplicitConversions: true).expression; var slot = MakeSlot(expressionWithoutConversion); // Since we know for sure the slot is null (we just tested it), we know that dependent slots are not // reachable and therefore can be treated as not null. However, we have not computed the proper // (inferred) type for the expression, so we cannot compute the correct symbols for the member slots here // (using the incorrect symbols would result in computing an incorrect default state for them). // Therefore we do not mark dependent slots not null. See https://github.com/dotnet/roslyn/issues/39624 LearnFromNullTest(slot, expressionWithoutConversion.Type, ref state, markDependentSlotsNotNull: false); } private void LearnFromNullTest(int slot, TypeSymbol? expressionType, ref LocalState state, bool markDependentSlotsNotNull) { if (slot > 0 && PossiblyNullableType(expressionType)) { if (state[slot] == NullableFlowState.NotNull) { // Note: We leave a MaybeDefault state as-is state[slot] = NullableFlowState.MaybeNull; } if (markDependentSlotsNotNull) { MarkDependentSlotsNotNull(slot, expressionType, ref state); } } } // If we know for sure that a slot contains a null value, then we know for sure that dependent slots // are "unreachable" so we might as well treat them as not null. That way when this state is merged // with another state, those dependent states won't pollute values from the other state. private void MarkDependentSlotsNotNull(int slot, TypeSymbol expressionType, ref LocalState state, int depth = 2) { if (depth <= 0) return; foreach (var member in getMembers(expressionType)) { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var containingType = this._symbol?.ContainingType; if ((member is PropertySymbol { IsIndexedProperty: false } || member.Kind == SymbolKind.Field) && member.RequiresInstanceReceiver() && (containingType is null || AccessCheck.IsSymbolAccessible(member, containingType, ref discardedUseSiteInfo))) { int childSlot = GetOrCreateSlot(member, slot, forceSlotEvenIfEmpty: true, createIfMissing: false); if (childSlot > 0) { state[childSlot] = NullableFlowState.NotNull; MarkDependentSlotsNotNull(childSlot, member.GetTypeOrReturnType().Type, ref state, depth - 1); } } } static IEnumerable<Symbol> getMembers(TypeSymbol type) { // First, return the direct members foreach (var member in type.GetMembers()) yield return member; // All types inherit members from their effective bases for (NamedTypeSymbol baseType = effectiveBase(type); !(baseType is null); baseType = baseType.BaseTypeNoUseSiteDiagnostics) foreach (var member in baseType.GetMembers()) yield return member; // Interfaces and type parameters inherit from their effective interfaces foreach (NamedTypeSymbol interfaceType in inheritedInterfaces(type)) foreach (var member in interfaceType.GetMembers()) yield return member; yield break; static NamedTypeSymbol effectiveBase(TypeSymbol type) => type switch { TypeParameterSymbol tp => tp.EffectiveBaseClassNoUseSiteDiagnostics, var t => t.BaseTypeNoUseSiteDiagnostics, }; static ImmutableArray<NamedTypeSymbol> inheritedInterfaces(TypeSymbol type) => type switch { TypeParameterSymbol tp => tp.AllEffectiveInterfacesNoUseSiteDiagnostics, { TypeKind: TypeKind.Interface } => type.AllInterfacesNoUseSiteDiagnostics, _ => ImmutableArray<NamedTypeSymbol>.Empty, }; } } private static BoundExpression SkipReferenceConversions(BoundExpression possiblyConversion) { while (possiblyConversion.Kind == BoundKind.Conversion) { var conversion = (BoundConversion)possiblyConversion; switch (conversion.ConversionKind) { case ConversionKind.ImplicitReference: case ConversionKind.ExplicitReference: possiblyConversion = conversion.Operand; break; default: return possiblyConversion; } } return possiblyConversion; } public override BoundNode? VisitNullCoalescingAssignmentOperator(BoundNullCoalescingAssignmentOperator node) { BoundExpression leftOperand = node.LeftOperand; BoundExpression rightOperand = node.RightOperand; int leftSlot = MakeSlot(leftOperand); TypeWithAnnotations targetType = VisitLvalueWithAnnotations(leftOperand); var leftState = this.State.Clone(); LearnFromNonNullTest(leftOperand, ref leftState); LearnFromNullTest(leftOperand, ref this.State); if (node.IsNullableValueTypeAssignment) { targetType = TypeWithAnnotations.Create(node.Type, NullableAnnotation.NotAnnotated); } TypeWithState rightResult = VisitOptionalImplicitConversion(rightOperand, targetType, useLegacyWarnings: UseLegacyWarnings(leftOperand, targetType), trackMembers: false, AssignmentKind.Assignment); TrackNullableStateForAssignment(rightOperand, targetType, leftSlot, rightResult, MakeSlot(rightOperand)); Join(ref this.State, ref leftState); TypeWithState resultType = TypeWithState.Create(targetType.Type, rightResult.State); SetResultType(node, resultType); return null; } public override BoundNode? VisitNullCoalescingOperator(BoundNullCoalescingOperator node) { Debug.Assert(!IsConditionalState); BoundExpression leftOperand = node.LeftOperand; BoundExpression rightOperand = node.RightOperand; if (IsConstantNull(leftOperand)) { VisitRvalue(leftOperand); Visit(rightOperand); var rightUnconditionalResult = ResultType; // Should be able to use rightResult for the result of the operator but // binding may have generated a different result type in the case of errors. SetResultType(node, TypeWithState.Create(node.Type, rightUnconditionalResult.State)); return null; } VisitPossibleConditionalAccess(leftOperand, out var whenNotNull); TypeWithState leftResult = ResultType; Unsplit(); LearnFromNullTest(leftOperand, ref this.State); bool leftIsConstant = leftOperand.ConstantValue != null; if (leftIsConstant) { SetUnreachable(); } Visit(rightOperand); TypeWithState rightResult = ResultType; Join(ref whenNotNull); var leftResultType = leftResult.Type; var rightResultType = rightResult.Type; var (resultType, leftState) = node.OperatorResultKind switch { BoundNullCoalescingOperatorResultKind.NoCommonType => (node.Type, NullableFlowState.NotNull), BoundNullCoalescingOperatorResultKind.LeftType => getLeftResultType(leftResultType!, rightResultType!), BoundNullCoalescingOperatorResultKind.LeftUnwrappedType => getLeftResultType(leftResultType!.StrippedType(), rightResultType!), BoundNullCoalescingOperatorResultKind.RightType => getResultStateWithRightType(leftResultType!, rightResultType!), BoundNullCoalescingOperatorResultKind.LeftUnwrappedRightType => getResultStateWithRightType(leftResultType!.StrippedType(), rightResultType!), BoundNullCoalescingOperatorResultKind.RightDynamicType => (rightResultType!, NullableFlowState.NotNull), _ => throw ExceptionUtilities.UnexpectedValue(node.OperatorResultKind), }; SetResultType(node, TypeWithState.Create(resultType, rightResult.State.Join(leftState))); return null; (TypeSymbol ResultType, NullableFlowState LeftState) getLeftResultType(TypeSymbol leftType, TypeSymbol rightType) { Debug.Assert(rightType is object); // If there was an identity conversion between the two operands (in short, if there // is no implicit conversion on the right operand), then check nullable conversions // in both directions since it's possible the right operand is the better result type. if ((node.RightOperand as BoundConversion)?.ExplicitCastInCode != false && GenerateConversionForConditionalOperator(node.LeftOperand, leftType, rightType, reportMismatch: false) is { Exists: true } conversion) { Debug.Assert(!conversion.IsUserDefined); return (rightType, NullableFlowState.NotNull); } conversion = GenerateConversionForConditionalOperator(node.RightOperand, rightType, leftType, reportMismatch: true); Debug.Assert(!conversion.IsUserDefined); return (leftType, NullableFlowState.NotNull); } (TypeSymbol ResultType, NullableFlowState LeftState) getResultStateWithRightType(TypeSymbol leftType, TypeSymbol rightType) { var conversion = GenerateConversionForConditionalOperator(node.LeftOperand, leftType, rightType, reportMismatch: true); if (conversion.IsUserDefined) { var conversionResult = VisitConversion( conversionOpt: null, node.LeftOperand, conversion, TypeWithAnnotations.Create(rightType), // When considering the conversion on the left node, it can only occur in the case where the underlying // execution returned non-null TypeWithState.Create(leftType, NullableFlowState.NotNull), checkConversion: false, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Assignment, reportTopLevelWarnings: false, reportRemainingWarnings: false); Debug.Assert(conversionResult.Type is not null); return (conversionResult.Type!, conversionResult.State); } return (rightType, NullableFlowState.NotNull); } } /// <summary> /// Visits a node only if it is a conditional access. /// Returns 'true' if and only if the node was visited. /// </summary> private bool TryVisitConditionalAccess(BoundExpression node, out PossiblyConditionalState stateWhenNotNull) { var (operand, conversion) = RemoveConversion(node, includeExplicitConversions: true); if (operand is not BoundConditionalAccess access || !CanPropagateStateWhenNotNull(conversion)) { stateWhenNotNull = default; return false; } Unsplit(); VisitConditionalAccess(access, out stateWhenNotNull); if (node is BoundConversion boundConversion) { var operandType = ResultType; TypeWithAnnotations explicitType = boundConversion.ConversionGroupOpt?.ExplicitType ?? default; bool fromExplicitCast = explicitType.HasType; TypeWithAnnotations targetType = fromExplicitCast ? explicitType : TypeWithAnnotations.Create(boundConversion.Type); Debug.Assert(targetType.HasType); var result = VisitConversion(boundConversion, access, conversion, targetType, operandType, checkConversion: true, fromExplicitCast, useLegacyWarnings: true, assignmentKind: AssignmentKind.Assignment); SetResultType(boundConversion, result); } Debug.Assert(!IsConditionalState); return true; } /// <summary> /// Unconditionally visits an expression and returns the "state when not null" for the expression. /// </summary> private bool VisitPossibleConditionalAccess(BoundExpression node, out PossiblyConditionalState stateWhenNotNull) { if (TryVisitConditionalAccess(node, out stateWhenNotNull)) { return true; } // in case we *didn't* have a conditional access, the only thing we learn in the "state when not null" // is that the top-level expression was non-null. Visit(node); stateWhenNotNull = PossiblyConditionalState.Create(this); (node, _) = RemoveConversion(node, includeExplicitConversions: true); var slot = MakeSlot(node); if (slot > -1) { if (IsConditionalState) { LearnFromNonNullTest(slot, ref stateWhenNotNull.StateWhenTrue); LearnFromNonNullTest(slot, ref stateWhenNotNull.StateWhenFalse); } else { LearnFromNonNullTest(slot, ref stateWhenNotNull.State); } } return false; } private void VisitConditionalAccess(BoundConditionalAccess node, out PossiblyConditionalState stateWhenNotNull) { Debug.Assert(!IsConditionalState); var receiver = node.Receiver; // handle scenarios like `(a?.b)?.c()` VisitPossibleConditionalAccess(receiver, out stateWhenNotNull); Unsplit(); _currentConditionalReceiverVisitResult = _visitResult; var previousConditionalAccessSlot = _lastConditionalAccessSlot; if (receiver.ConstantValue is { IsNull: false }) { // Consider a scenario like `"a"?.M0(x = 1)?.M0(y = 1)`. // We can "know" that `.M0(x = 1)` was evaluated unconditionally but not `M0(y = 1)`. // Therefore we do a VisitPossibleConditionalAccess here which unconditionally includes the "after receiver" state in State // and includes the "after subsequent conditional accesses" in stateWhenNotNull VisitPossibleConditionalAccess(node.AccessExpression, out stateWhenNotNull); } else { var savedState = this.State.Clone(); if (IsConstantNull(receiver)) { SetUnreachable(); _lastConditionalAccessSlot = -1; } else { // In the when-null branch, the receiver is known to be maybe-null. // In the other branch, the receiver is known to be non-null. LearnFromNullTest(receiver, ref savedState); makeAndAdjustReceiverSlot(receiver); SetPossiblyConditionalState(stateWhenNotNull); } // We want to preserve stateWhenNotNull from accesses in the same "chain": // a?.b(out x)?.c(out y); // expected to preserve stateWhenNotNull from both ?.b(out x) and ?.c(out y) // but not accesses in nested expressions: // a?.b(out x, c?.d(out y)); // expected to preserve stateWhenNotNull from a?.b(out x, ...) but not from c?.d(out y) BoundExpression expr = node.AccessExpression; while (expr is BoundConditionalAccess innerCondAccess) { // we assume that non-conditional accesses can never contain conditional accesses from the same "chain". // that is, we never have to dig through non-conditional accesses to find and handle conditional accesses. Debug.Assert(innerCondAccess.Receiver is not (BoundConditionalAccess or BoundConversion)); VisitRvalue(innerCondAccess.Receiver); _currentConditionalReceiverVisitResult = _visitResult; makeAndAdjustReceiverSlot(innerCondAccess.Receiver); // The savedState here represents the scenario where 0 or more of the access expressions could have been evaluated. // e.g. after visiting `a?.b(x = null)?.c(x = new object())`, the "state when not null" of `x` is NotNull, but the "state when maybe null" of `x` is MaybeNull. Join(ref savedState, ref State); expr = innerCondAccess.AccessExpression; } Debug.Assert(expr is BoundExpression); Visit(expr); expr = node.AccessExpression; while (expr is BoundConditionalAccess innerCondAccess) { // The resulting nullability of each nested conditional access is the same as the resulting nullability of the rightmost access. SetAnalyzedNullability(innerCondAccess, _visitResult); expr = innerCondAccess.AccessExpression; } Debug.Assert(expr is BoundExpression); var slot = MakeSlot(expr); if (slot > -1) { if (IsConditionalState) { LearnFromNonNullTest(slot, ref StateWhenTrue); LearnFromNonNullTest(slot, ref StateWhenFalse); } else { LearnFromNonNullTest(slot, ref State); } } stateWhenNotNull = PossiblyConditionalState.Create(this); Unsplit(); Join(ref this.State, ref savedState); } var accessTypeWithAnnotations = LvalueResultType; TypeSymbol accessType = accessTypeWithAnnotations.Type; var oldType = node.Type; var resultType = oldType.IsVoidType() || oldType.IsErrorType() ? oldType : oldType.IsNullableType() && !accessType.IsNullableType() ? MakeNullableOf(accessTypeWithAnnotations) : accessType; // Per LDM 2019-02-13 decision, the result of a conditional access "may be null" even if // both the receiver and right-hand-side are believed not to be null. SetResultType(node, TypeWithState.Create(resultType, NullableFlowState.MaybeDefault)); _currentConditionalReceiverVisitResult = default; _lastConditionalAccessSlot = previousConditionalAccessSlot; void makeAndAdjustReceiverSlot(BoundExpression receiver) { var slot = MakeSlot(receiver); if (slot > -1) LearnFromNonNullTest(slot, ref State); // given `a?.b()`, when `a` is a nullable value type, // the conditional receiver for `?.b()` must be linked to `a.Value`, not to `a`. if (slot > 0 && receiver.Type?.IsNullableType() == true) slot = GetNullableOfTValueSlot(receiver.Type, slot, out _); _lastConditionalAccessSlot = slot; } } public override BoundNode? VisitConditionalAccess(BoundConditionalAccess node) { VisitConditionalAccess(node, out _); return null; } protected override BoundNode? VisitConditionalOperatorCore( BoundExpression node, bool isRef, BoundExpression condition, BoundExpression originalConsequence, BoundExpression originalAlternative) { VisitCondition(condition); var consequenceState = this.StateWhenTrue; var alternativeState = this.StateWhenFalse; TypeWithState consequenceRValue; TypeWithState alternativeRValue; if (isRef) { TypeWithAnnotations consequenceLValue; TypeWithAnnotations alternativeLValue; (consequenceLValue, consequenceRValue) = visitConditionalRefOperand(consequenceState, originalConsequence); consequenceState = this.State; (alternativeLValue, alternativeRValue) = visitConditionalRefOperand(alternativeState, originalAlternative); Join(ref this.State, ref consequenceState); TypeSymbol? refResultType = node.Type?.SetUnknownNullabilityForReferenceTypes(); if (IsNullabilityMismatch(consequenceLValue, alternativeLValue)) { // l-value types must match ReportNullabilityMismatchInAssignment(node.Syntax, consequenceLValue, alternativeLValue); } else if (!node.HasErrors) { refResultType = consequenceRValue.Type!.MergeEquivalentTypes(alternativeRValue.Type, VarianceKind.None); } var lValueAnnotation = consequenceLValue.NullableAnnotation.EnsureCompatible(alternativeLValue.NullableAnnotation); var rValueState = consequenceRValue.State.Join(alternativeRValue.State); SetResult(node, TypeWithState.Create(refResultType, rValueState), TypeWithAnnotations.Create(refResultType, lValueAnnotation)); return null; } (var consequence, var consequenceConversion, consequenceRValue) = visitConditionalOperand(consequenceState, originalConsequence); var consequenceConditionalState = PossiblyConditionalState.Create(this); consequenceState = CloneAndUnsplit(ref consequenceConditionalState); var consequenceEndReachable = consequenceState.Reachable; (var alternative, var alternativeConversion, alternativeRValue) = visitConditionalOperand(alternativeState, originalAlternative); var alternativeConditionalState = PossiblyConditionalState.Create(this); alternativeState = CloneAndUnsplit(ref alternativeConditionalState); var alternativeEndReachable = alternativeState.Reachable; SetPossiblyConditionalState(in consequenceConditionalState); Join(ref alternativeConditionalState); TypeSymbol? resultType; bool wasTargetTyped = node is BoundConditionalOperator { WasTargetTyped: true }; if (node.HasErrors || wasTargetTyped) { resultType = null; } else { // Determine nested nullability using BestTypeInferrer. // If a branch is unreachable, we could use the nested nullability of the other // branch, but that requires using the nullability of the branch as it applies to the // target type. For instance, the result of the conditional in the following should // be `IEnumerable<object>` not `object[]`: // object[] a = ...; // IEnumerable<object?> b = ...; // var c = true ? a : b; BoundExpression consequencePlaceholder = CreatePlaceholderIfNecessary(consequence, consequenceRValue.ToTypeWithAnnotations(compilation)); BoundExpression alternativePlaceholder = CreatePlaceholderIfNecessary(alternative, alternativeRValue.ToTypeWithAnnotations(compilation)); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; resultType = BestTypeInferrer.InferBestTypeForConditionalOperator(consequencePlaceholder, alternativePlaceholder, _conversions, out _, ref discardedUseSiteInfo); } resultType ??= node.Type?.SetUnknownNullabilityForReferenceTypes(); NullableFlowState resultState; if (!wasTargetTyped) { if (resultType is null) { // This can happen when we're inferring the return type of a lambda. For this case, we don't need to do any work, // the unconverted conditional operator can't contribute info. The conversion that should be on top of this // can add or remove nullability, and nested nodes aren't being publicly exposed by the semantic model. Debug.Assert(node is BoundUnconvertedConditionalOperator); Debug.Assert(_returnTypesOpt is not null); resultState = default; } else { var resultTypeWithAnnotations = TypeWithAnnotations.Create(resultType); TypeWithState convertedConsequenceResult = ConvertConditionalOperandOrSwitchExpressionArmResult( originalConsequence, consequence, consequenceConversion, resultTypeWithAnnotations, consequenceRValue, consequenceState, consequenceEndReachable); TypeWithState convertedAlternativeResult = ConvertConditionalOperandOrSwitchExpressionArmResult( originalAlternative, alternative, alternativeConversion, resultTypeWithAnnotations, alternativeRValue, alternativeState, alternativeEndReachable); resultState = convertedConsequenceResult.State.Join(convertedAlternativeResult.State); } } else { resultState = consequenceRValue.State.Join(alternativeRValue.State); ConditionalInfoForConversion.Add(node, ImmutableArray.Create( (consequenceState, consequenceRValue, consequenceEndReachable), (alternativeState, alternativeRValue, alternativeEndReachable))); } SetResultType(node, TypeWithState.Create(resultType, resultState)); return null; (BoundExpression, Conversion, TypeWithState) visitConditionalOperand(LocalState state, BoundExpression operand) { Conversion conversion; SetState(state); Debug.Assert(!isRef); BoundExpression operandNoConversion; (operandNoConversion, conversion) = RemoveConversion(operand, includeExplicitConversions: false); SnapshotWalkerThroughConversionGroup(operand, operandNoConversion); Visit(operandNoConversion); return (operandNoConversion, conversion, ResultType); } (TypeWithAnnotations LValueType, TypeWithState RValueType) visitConditionalRefOperand(LocalState state, BoundExpression operand) { SetState(state); Debug.Assert(isRef); TypeWithAnnotations lValueType = VisitLvalueWithAnnotations(operand); return (lValueType, ResultType); } } private TypeWithState ConvertConditionalOperandOrSwitchExpressionArmResult( BoundExpression node, BoundExpression operand, Conversion conversion, TypeWithAnnotations targetType, TypeWithState operandType, LocalState state, bool isReachable) { var savedState = this.State; this.State = state; bool previousDisabledDiagnostics = _disableDiagnostics; // If the node is not reachable, then we're only visiting to get // nullability information for the public API, and not to produce diagnostics. // Disable diagnostics, and return default for the resulting state // to indicate that warnings were suppressed. if (!isReachable) { _disableDiagnostics = true; } var resultType = VisitConversion( GetConversionIfApplicable(node, operand), operand, conversion, targetType, operandType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Assignment, reportTopLevelWarnings: false); if (!isReachable) { resultType = default; _disableDiagnostics = previousDisabledDiagnostics; } this.State = savedState; return resultType; } private bool IsReachable() => this.IsConditionalState ? (this.StateWhenTrue.Reachable || this.StateWhenFalse.Reachable) : this.State.Reachable; /// <summary> /// Placeholders are bound expressions with type and state. /// But for typeless expressions (such as `null` or `(null, null)` we hold onto the original bound expression, /// as it will be useful for conversions from expression. /// </summary> private static BoundExpression CreatePlaceholderIfNecessary(BoundExpression expr, TypeWithAnnotations type) { return !type.HasType ? expr : new BoundExpressionWithNullability(expr.Syntax, expr, type.NullableAnnotation, type.Type); } public override BoundNode? VisitConditionalReceiver(BoundConditionalReceiver node) { var rvalueType = _currentConditionalReceiverVisitResult.RValueType.Type; if (rvalueType?.IsNullableType() == true) { rvalueType = rvalueType.GetNullableUnderlyingType(); } SetResultType(node, TypeWithState.Create(rvalueType, NullableFlowState.NotNull)); return null; } public override BoundNode? VisitCall(BoundCall node) { // Note: we analyze even omitted calls TypeWithState receiverType = VisitCallReceiver(node); ReinferMethodAndVisitArguments(node, receiverType); return null; } private void ReinferMethodAndVisitArguments(BoundCall node, TypeWithState receiverType) { var method = node.Method; ImmutableArray<RefKind> refKindsOpt = node.ArgumentRefKindsOpt; if (!receiverType.HasNullType) { // Update method based on inferred receiver type. method = (MethodSymbol)AsMemberOfType(receiverType.Type, method); } ImmutableArray<VisitArgumentResult> results; bool returnNotNull; (method, results, returnNotNull) = VisitArguments(node, node.Arguments, refKindsOpt, method!.Parameters, node.ArgsToParamsOpt, node.DefaultArguments, node.Expanded, node.InvokedAsExtensionMethod, method); ApplyMemberPostConditions(node.ReceiverOpt, method); LearnFromEqualsMethod(method, node, receiverType, results); var returnState = GetReturnTypeWithState(method); if (returnNotNull) { returnState = returnState.WithNotNullState(); } SetResult(node, returnState, method.ReturnTypeWithAnnotations); SetUpdatedSymbol(node, node.Method, method); } private void LearnFromEqualsMethod(MethodSymbol method, BoundCall node, TypeWithState receiverType, ImmutableArray<VisitArgumentResult> results) { // easy out var parameterCount = method.ParameterCount; var arguments = node.Arguments; if (node.HasErrors || (parameterCount != 1 && parameterCount != 2) || parameterCount != arguments.Length || method.MethodKind != MethodKind.Ordinary || method.ReturnType.SpecialType != SpecialType.System_Boolean || (method.Name != SpecialMembers.GetDescriptor(SpecialMember.System_Object__Equals).Name && method.Name != SpecialMembers.GetDescriptor(SpecialMember.System_Object__ReferenceEquals).Name && !anyOverriddenMethodHasExplicitImplementation(method))) { return; } var isStaticEqualsMethod = method.Equals(compilation.GetSpecialTypeMember(SpecialMember.System_Object__EqualsObjectObject)) || method.Equals(compilation.GetSpecialTypeMember(SpecialMember.System_Object__ReferenceEquals)); if (isStaticEqualsMethod || isWellKnownEqualityMethodOrImplementation(compilation, method, receiverType.Type, WellKnownMember.System_Collections_Generic_IEqualityComparer_T__Equals)) { Debug.Assert(arguments.Length == 2); learnFromEqualsMethodArguments(arguments[0], results[0].RValueType, arguments[1], results[1].RValueType); return; } var isObjectEqualsMethodOrOverride = method.GetLeastOverriddenMethod(accessingTypeOpt: null) .Equals(compilation.GetSpecialTypeMember(SpecialMember.System_Object__Equals)); if (node.ReceiverOpt is BoundExpression receiver && (isObjectEqualsMethodOrOverride || isWellKnownEqualityMethodOrImplementation(compilation, method, receiverType.Type, WellKnownMember.System_IEquatable_T__Equals))) { Debug.Assert(arguments.Length == 1); learnFromEqualsMethodArguments(receiver, receiverType, arguments[0], results[0].RValueType); return; } static bool anyOverriddenMethodHasExplicitImplementation(MethodSymbol method) { for (var overriddenMethod = method; overriddenMethod is object; overriddenMethod = overriddenMethod.OverriddenMethod) { if (overriddenMethod.IsExplicitInterfaceImplementation) { return true; } } return false; } static bool isWellKnownEqualityMethodOrImplementation(CSharpCompilation compilation, MethodSymbol method, TypeSymbol? receiverType, WellKnownMember wellKnownMember) { var wellKnownMethod = (MethodSymbol?)compilation.GetWellKnownTypeMember(wellKnownMember); if (wellKnownMethod is null || receiverType is null) { return false; } var wellKnownType = wellKnownMethod.ContainingType; var parameterType = method.Parameters[0].TypeWithAnnotations; var constructedType = wellKnownType.Construct(ImmutableArray.Create(parameterType)); var constructedMethod = wellKnownMethod.AsMember(constructedType); // FindImplementationForInterfaceMember doesn't check if this method is itself the interface method we're looking for if (constructedMethod.Equals(method)) { return true; } // check whether 'method', when called on this receiver, is an implementation of 'constructedMethod'. for (var baseType = receiverType; baseType is object && method is object; baseType = baseType.BaseTypeNoUseSiteDiagnostics) { var implementationMethod = baseType.FindImplementationForInterfaceMember(constructedMethod); if (implementationMethod is null) { // we know no base type will implement this interface member either return false; } if (implementationMethod.ContainingType.IsInterface) { // this method cannot be called directly from source because an interface can only explicitly implement a method from its base interface. return false; } // could be calling an override of a method that implements the interface method for (var overriddenMethod = method; overriddenMethod is object; overriddenMethod = overriddenMethod.OverriddenMethod) { if (overriddenMethod.Equals(implementationMethod)) { return true; } } // the Equals method being called isn't the method that implements the interface method in this type. // it could be a method that implements the interface on a base type, so check again with the base type of 'implementationMethod.ContainingType' // e.g. in this hierarchy: // class A -> B -> C -> D // method virtual B.Equals -> override D.Equals // // we would potentially check: // 1. D.Equals when called on D, then B.Equals when called on D // 2. B.Equals when called on C // 3. B.Equals when called on B // 4. give up when checking A, since B.Equals is not overriding anything in A // we know that implementationMethod.ContainingType is the same type or a base type of 'baseType', // and that the implementation method will be the same between 'baseType' and 'implementationMethod.ContainingType'. // we step through the intermediate bases in order to skip unnecessary override methods. while (!baseType.Equals(implementationMethod.ContainingType) && method is object) { if (baseType.Equals(method.ContainingType)) { // since we're about to move on to the base of 'method.ContainingType', // we know the implementation could only be an overridden method of 'method'. method = method.OverriddenMethod; } baseType = baseType.BaseTypeNoUseSiteDiagnostics; // the implementation method must be contained in this 'baseType' or one of its bases. Debug.Assert(baseType is object); } // now 'baseType == implementationMethod.ContainingType', so if 'method' is // contained in that same type we should advance 'method' one more time. if (method is object && baseType.Equals(method.ContainingType)) { method = method.OverriddenMethod; } } return false; } void learnFromEqualsMethodArguments(BoundExpression left, TypeWithState leftType, BoundExpression right, TypeWithState rightType) { // comparing anything to a null literal gives maybe-null when true and not-null when false // comparing a maybe-null to a not-null gives us not-null when true, nothing learned when false if (left.ConstantValue?.IsNull == true) { Split(); LearnFromNullTest(right, ref StateWhenTrue); LearnFromNonNullTest(right, ref StateWhenFalse); } else if (right.ConstantValue?.IsNull == true) { Split(); LearnFromNullTest(left, ref StateWhenTrue); LearnFromNonNullTest(left, ref StateWhenFalse); } else if (leftType.MayBeNull && rightType.IsNotNull) { Split(); LearnFromNonNullTest(left, ref StateWhenTrue); } else if (rightType.MayBeNull && leftType.IsNotNull) { Split(); LearnFromNonNullTest(right, ref StateWhenTrue); } } } private bool IsCompareExchangeMethod(MethodSymbol? method) { if (method is null) { return false; } return method.Equals(compilation.GetWellKnownTypeMember(WellKnownMember.System_Threading_Interlocked__CompareExchange), SymbolEqualityComparer.ConsiderEverything.CompareKind) || method.OriginalDefinition.Equals(compilation.GetWellKnownTypeMember(WellKnownMember.System_Threading_Interlocked__CompareExchange_T), SymbolEqualityComparer.ConsiderEverything.CompareKind); } private readonly struct CompareExchangeInfo { public readonly ImmutableArray<BoundExpression> Arguments; public readonly ImmutableArray<VisitArgumentResult> Results; public readonly ImmutableArray<int> ArgsToParamsOpt; public CompareExchangeInfo(ImmutableArray<BoundExpression> arguments, ImmutableArray<VisitArgumentResult> results, ImmutableArray<int> argsToParamsOpt) { Arguments = arguments; Results = results; ArgsToParamsOpt = argsToParamsOpt; } public bool IsDefault => Arguments.IsDefault || Results.IsDefault; } private NullableFlowState LearnFromCompareExchangeMethod(in CompareExchangeInfo compareExchangeInfo) { Debug.Assert(!compareExchangeInfo.IsDefault); // In general a call to CompareExchange of the form: // // Interlocked.CompareExchange(ref location, value, comparand); // // will be analyzed similarly to the following: // // if (location == comparand) // { // location = value; // } if (compareExchangeInfo.Arguments.Length != 3) { // This can occur if CompareExchange has optional arguments. // Since none of the main runtimes have optional arguments, // we bail to avoid an exception but don't bother actually calculating the FlowState. return NullableFlowState.NotNull; } var argsToParamsOpt = compareExchangeInfo.ArgsToParamsOpt; Debug.Assert(argsToParamsOpt is { IsDefault: true } or { Length: 3 }); var (comparandIndex, valueIndex, locationIndex) = argsToParamsOpt.IsDefault ? (2, 1, 0) : (argsToParamsOpt.IndexOf(2), argsToParamsOpt.IndexOf(1), argsToParamsOpt.IndexOf(0)); var comparand = compareExchangeInfo.Arguments[comparandIndex]; var valueFlowState = compareExchangeInfo.Results[valueIndex].RValueType.State; if (comparand.ConstantValue?.IsNull == true) { // If location contained a null, then the write `location = value` definitely occurred } else { var locationFlowState = compareExchangeInfo.Results[locationIndex].RValueType.State; // A write may have occurred valueFlowState = valueFlowState.Join(locationFlowState); } return valueFlowState; } private TypeWithState VisitCallReceiver(BoundCall node) { var receiverOpt = node.ReceiverOpt; TypeWithState receiverType = default; if (receiverOpt != null) { receiverType = VisitRvalueWithState(receiverOpt); // methods which are members of Nullable<T> (ex: ToString, GetHashCode) can be invoked on null receiver. // However, inherited methods (ex: GetType) are invoked on a boxed value (since base types are reference types) // and therefore in those cases nullable receivers should be checked for nullness. bool checkNullableValueType = false; var type = receiverType.Type; var method = node.Method; if (method.RequiresInstanceReceiver && type?.IsNullableType() == true && method.ContainingType.IsReferenceType) { checkNullableValueType = true; } else if (method.OriginalDefinition == compilation.GetSpecialTypeMember(SpecialMember.System_Nullable_T_get_Value)) { // call to get_Value may not occur directly in source, but may be inserted as a result of premature lowering. // One example where we do it is foreach with nullables. // The reason is Dev10 compatibility (see: UnwrapCollectionExpressionIfNullable in ForEachLoopBinder.cs) // Regardless of the reasons, we know that the method does not tolerate nulls. checkNullableValueType = true; } // https://github.com/dotnet/roslyn/issues/30598: Mark receiver as not null // after arguments have been visited, and only if the receiver has not changed. _ = CheckPossibleNullReceiver(receiverOpt, checkNullableValueType); } return receiverType; } private TypeWithState GetReturnTypeWithState(MethodSymbol method) { return TypeWithState.Create(method.ReturnTypeWithAnnotations, GetRValueAnnotations(method)); } private FlowAnalysisAnnotations GetRValueAnnotations(Symbol? symbol) { // Annotations are ignored when binding an attribute to avoid cycles. (Members used // in attributes are error scenarios, so missing warnings should not be important.) if (IsAnalyzingAttribute) { return FlowAnalysisAnnotations.None; } var annotations = symbol.GetFlowAnalysisAnnotations(); return annotations & (FlowAnalysisAnnotations.MaybeNull | FlowAnalysisAnnotations.NotNull); } private FlowAnalysisAnnotations GetParameterAnnotations(ParameterSymbol parameter) { // Annotations are ignored when binding an attribute to avoid cycles. (Members used // in attributes are error scenarios, so missing warnings should not be important.) return IsAnalyzingAttribute ? FlowAnalysisAnnotations.None : parameter.FlowAnalysisAnnotations; } /// <summary> /// Fix a TypeWithAnnotations based on Allow/DisallowNull annotations prior to a conversion or assignment. /// Note this does not work for nullable value types, so an additional check with <see cref="CheckDisallowedNullAssignment"/> may be required. /// </summary> private static TypeWithAnnotations ApplyLValueAnnotations(TypeWithAnnotations declaredType, FlowAnalysisAnnotations flowAnalysisAnnotations) { if ((flowAnalysisAnnotations & FlowAnalysisAnnotations.DisallowNull) == FlowAnalysisAnnotations.DisallowNull) { return declaredType.AsNotAnnotated(); } else if ((flowAnalysisAnnotations & FlowAnalysisAnnotations.AllowNull) == FlowAnalysisAnnotations.AllowNull) { return declaredType.AsAnnotated(); } return declaredType; } /// <summary> /// Update the null-state based on MaybeNull/NotNull /// </summary> private static TypeWithState ApplyUnconditionalAnnotations(TypeWithState typeWithState, FlowAnalysisAnnotations annotations) { if ((annotations & FlowAnalysisAnnotations.NotNull) == FlowAnalysisAnnotations.NotNull) { return TypeWithState.Create(typeWithState.Type, NullableFlowState.NotNull); } if ((annotations & FlowAnalysisAnnotations.MaybeNull) == FlowAnalysisAnnotations.MaybeNull) { return TypeWithState.Create(typeWithState.Type, NullableFlowState.MaybeDefault); } return typeWithState; } private static TypeWithAnnotations ApplyUnconditionalAnnotations(TypeWithAnnotations declaredType, FlowAnalysisAnnotations annotations) { if ((annotations & FlowAnalysisAnnotations.MaybeNull) == FlowAnalysisAnnotations.MaybeNull) { return declaredType.AsAnnotated(); } if ((annotations & FlowAnalysisAnnotations.NotNull) == FlowAnalysisAnnotations.NotNull) { return declaredType.AsNotAnnotated(); } return declaredType; } // https://github.com/dotnet/roslyn/issues/29863 Record in the node whether type // arguments were implicit, to allow for cases where the syntax is not an // invocation (such as a synthesized call from a query interpretation). private static bool HasImplicitTypeArguments(BoundNode node) { if (node is BoundCollectionElementInitializer { AddMethod: { TypeArgumentsWithAnnotations: { IsEmpty: false } } }) { return true; } if (node is BoundForEachStatement { EnumeratorInfoOpt: { GetEnumeratorInfo: { Method: { TypeArgumentsWithAnnotations: { IsEmpty: false } } } } }) { return true; } var syntax = node.Syntax; if (syntax.Kind() != SyntaxKind.InvocationExpression) { // Unexpected syntax kind. return false; } return HasImplicitTypeArguments(((InvocationExpressionSyntax)syntax).Expression); } private static bool HasImplicitTypeArguments(SyntaxNode syntax) { var nameSyntax = Binder.GetNameSyntax(syntax, out _); if (nameSyntax == null) { // Unexpected syntax kind. return false; } nameSyntax = nameSyntax.GetUnqualifiedName(); return nameSyntax.Kind() != SyntaxKind.GenericName; } protected override void VisitArguments(ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> refKindsOpt, MethodSymbol method) { // Callers should be using VisitArguments overload below. throw ExceptionUtilities.Unreachable; } private (MethodSymbol? method, ImmutableArray<VisitArgumentResult> results, bool returnNotNull) VisitArguments( BoundExpression node, ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> refKindsOpt, MethodSymbol? method, ImmutableArray<int> argsToParamsOpt, BitVector defaultArguments, bool expanded, bool invokedAsExtensionMethod) { return VisitArguments(node, arguments, refKindsOpt, method is null ? default : method.Parameters, argsToParamsOpt, defaultArguments, expanded, invokedAsExtensionMethod, method); } private ImmutableArray<VisitArgumentResult> VisitArguments( BoundExpression node, ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> refKindsOpt, PropertySymbol? property, ImmutableArray<int> argsToParamsOpt, BitVector defaultArguments, bool expanded) { return VisitArguments(node, arguments, refKindsOpt, property is null ? default : property.Parameters, argsToParamsOpt, defaultArguments, expanded, invokedAsExtensionMethod: false).results; } /// <summary> /// If you pass in a method symbol, its type arguments will be re-inferred and the re-inferred method will be returned. /// </summary> private (MethodSymbol? method, ImmutableArray<VisitArgumentResult> results, bool returnNotNull) VisitArguments( BoundNode node, ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> refKindsOpt, ImmutableArray<ParameterSymbol> parametersOpt, ImmutableArray<int> argsToParamsOpt, BitVector defaultArguments, bool expanded, bool invokedAsExtensionMethod, MethodSymbol? method = null) { Debug.Assert(!arguments.IsDefault); bool shouldReturnNotNull = false; (ImmutableArray<BoundExpression> argumentsNoConversions, ImmutableArray<Conversion> conversions) = RemoveArgumentConversions(arguments, refKindsOpt); // Visit the arguments and collect results ImmutableArray<VisitArgumentResult> results = VisitArgumentsEvaluate(node.Syntax, argumentsNoConversions, refKindsOpt, parametersOpt, argsToParamsOpt, defaultArguments, expanded); // Re-infer method type parameters if (method?.IsGenericMethod == true) { if (HasImplicitTypeArguments(node)) { method = InferMethodTypeArguments(method, GetArgumentsForMethodTypeInference(results, argumentsNoConversions), refKindsOpt, argsToParamsOpt, expanded); parametersOpt = method.Parameters; } if (ConstraintsHelper.RequiresChecking(method)) { var syntax = node.Syntax; CheckMethodConstraints( syntax switch { InvocationExpressionSyntax { Expression: var expression } => expression, ForEachStatementSyntax { Expression: var expression } => expression, _ => syntax }, method); } } bool parameterHasNotNullIfNotNull = !IsAnalyzingAttribute && !parametersOpt.IsDefault && parametersOpt.Any(p => !p.NotNullIfParameterNotNull.IsEmpty); var notNullParametersBuilder = parameterHasNotNullIfNotNull ? ArrayBuilder<ParameterSymbol>.GetInstance() : null; if (!parametersOpt.IsDefault) { // Visit conversions, inbound assignments including pre-conditions ImmutableHashSet<string>? returnNotNullIfParameterNotNull = IsAnalyzingAttribute ? null : method?.ReturnNotNullIfParameterNotNull; for (int i = 0; i < results.Length; i++) { var argumentNoConversion = argumentsNoConversions[i]; var argument = i < arguments.Length ? arguments[i] : argumentNoConversion; if (argument is not BoundConversion && argumentNoConversion is BoundLambda lambda) { Debug.Assert(node.HasErrors); Debug.Assert((object)argument == argumentNoConversion); // 'VisitConversion' only visits a lambda when the lambda has an AnonymousFunction conversion. // This lambda doesn't have a conversion, so we need to visit it here. VisitLambda(lambda, delegateTypeOpt: null, results[i].StateForLambda); continue; } (ParameterSymbol? parameter, TypeWithAnnotations parameterType, FlowAnalysisAnnotations parameterAnnotations, bool isExpandedParamsArgument) = GetCorrespondingParameter(i, parametersOpt, argsToParamsOpt, expanded); if (parameter is null) { // If this assert fails, we are missing necessary info to visit the // conversion of a target typed conditional or switch. Debug.Assert(argumentNoConversion is not (BoundConditionalOperator { WasTargetTyped: true } or BoundConvertedSwitchExpression { WasTargetTyped: true }) && _conditionalInfoForConversionOpt?.ContainsKey(argumentNoConversion) is null or false); // If this assert fails, it means we failed to visit a lambda for error recovery above. Debug.Assert(argumentNoConversion is not BoundLambda); continue; } // We disable diagnostics when: // 1. the containing call has errors (to reduce cascading diagnostics) // 2. on implicit default arguments (since that's really only an issue with the declaration) var previousDisableDiagnostics = _disableDiagnostics; _disableDiagnostics |= node.HasErrors || defaultArguments[i]; VisitArgumentConversionAndInboundAssignmentsAndPreConditions( GetConversionIfApplicable(argument, argumentNoConversion), argumentNoConversion, conversions.IsDefault || i >= conversions.Length ? Conversion.Identity : conversions[i], GetRefKind(refKindsOpt, i), parameter, parameterType, parameterAnnotations, results[i], invokedAsExtensionMethod && i == 0); _disableDiagnostics = previousDisableDiagnostics; if (results[i].RValueType.IsNotNull || isExpandedParamsArgument) { notNullParametersBuilder?.Add(parameter); if (returnNotNullIfParameterNotNull?.Contains(parameter.Name) == true) { shouldReturnNotNull = true; } } } } if (node is BoundCall { Method: { OriginalDefinition: LocalFunctionSymbol localFunction } }) { VisitLocalFunctionUse(localFunction); } if (!node.HasErrors && !parametersOpt.IsDefault) { // For CompareExchange method we need more context to determine the state of outbound assignment CompareExchangeInfo compareExchangeInfo = IsCompareExchangeMethod(method) ? new CompareExchangeInfo(arguments, results, argsToParamsOpt) : default; // Visit outbound assignments and post-conditions // Note: the state may get split in this step for (int i = 0; i < arguments.Length; i++) { (ParameterSymbol? parameter, TypeWithAnnotations parameterType, FlowAnalysisAnnotations parameterAnnotations, _) = GetCorrespondingParameter(i, parametersOpt, argsToParamsOpt, expanded); if (parameter is null) { continue; } VisitArgumentOutboundAssignmentsAndPostConditions( arguments[i], GetRefKind(refKindsOpt, i), parameter, parameterType, parameterAnnotations, results[i], notNullParametersBuilder, (!compareExchangeInfo.IsDefault && parameter.Ordinal == 0) ? compareExchangeInfo : default); } } else { for (int i = 0; i < arguments.Length; i++) { // We can hit this case when dynamic methods are involved, or when there are errors. In either case we have no information, // so just assume that the conversions have the same nullability as the underlying result var argument = arguments[i]; var result = results[i]; var argumentNoConversion = argumentsNoConversions[i]; TrackAnalyzedNullabilityThroughConversionGroup(TypeWithState.Create(argument.Type, result.RValueType.State), argument as BoundConversion, argumentNoConversion); } } if (!IsAnalyzingAttribute && method is object && (method.FlowAnalysisAnnotations & FlowAnalysisAnnotations.DoesNotReturn) == FlowAnalysisAnnotations.DoesNotReturn) { SetUnreachable(); } notNullParametersBuilder?.Free(); return (method, results, shouldReturnNotNull); } private void ApplyMemberPostConditions(BoundExpression? receiverOpt, MethodSymbol? method) { if (method is null) { return; } int receiverSlot = method.IsStatic ? 0 : receiverOpt is null ? -1 : MakeSlot(receiverOpt); if (receiverSlot < 0) { return; } ApplyMemberPostConditions(receiverSlot, method); } private void ApplyMemberPostConditions(int receiverSlot, MethodSymbol method) { Debug.Assert(receiverSlot >= 0); do { var type = method.ContainingType; var notNullMembers = method.NotNullMembers; var notNullWhenTrueMembers = method.NotNullWhenTrueMembers; var notNullWhenFalseMembers = method.NotNullWhenFalseMembers; if (IsConditionalState) { applyMemberPostConditions(receiverSlot, type, notNullMembers, ref StateWhenTrue); applyMemberPostConditions(receiverSlot, type, notNullMembers, ref StateWhenFalse); } else { applyMemberPostConditions(receiverSlot, type, notNullMembers, ref State); } if (!notNullWhenTrueMembers.IsEmpty || !notNullWhenFalseMembers.IsEmpty) { Split(); applyMemberPostConditions(receiverSlot, type, notNullWhenTrueMembers, ref StateWhenTrue); applyMemberPostConditions(receiverSlot, type, notNullWhenFalseMembers, ref StateWhenFalse); } method = method.OverriddenMethod; } while (method != null); void applyMemberPostConditions(int receiverSlot, TypeSymbol type, ImmutableArray<string> members, ref LocalState state) { if (members.IsEmpty) { return; } foreach (var memberName in members) { markMembersAsNotNull(receiverSlot, type, memberName, ref state); } } void markMembersAsNotNull(int receiverSlot, TypeSymbol type, string memberName, ref LocalState state) { foreach (Symbol member in type.GetMembers(memberName)) { if (member.IsStatic) { receiverSlot = 0; } switch (member.Kind) { case SymbolKind.Field: case SymbolKind.Property: if (GetOrCreateSlot(member, receiverSlot) is int memberSlot && memberSlot > 0) { state[memberSlot] = NullableFlowState.NotNull; } break; case SymbolKind.Event: case SymbolKind.Method: break; } } } } private ImmutableArray<VisitArgumentResult> VisitArgumentsEvaluate( SyntaxNode syntax, ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> refKindsOpt, ImmutableArray<ParameterSymbol> parametersOpt, ImmutableArray<int> argsToParamsOpt, BitVector defaultArguments, bool expanded) { Debug.Assert(!IsConditionalState); int n = arguments.Length; if (n == 0 && parametersOpt.IsDefaultOrEmpty) { return ImmutableArray<VisitArgumentResult>.Empty; } var visitedParameters = PooledHashSet<ParameterSymbol?>.GetInstance(); var resultsBuilder = ArrayBuilder<VisitArgumentResult>.GetInstance(n); var previousDisableDiagnostics = _disableDiagnostics; for (int i = 0; i < n; i++) { var (parameter, _, parameterAnnotations, _) = GetCorrespondingParameter(i, parametersOpt, argsToParamsOpt, expanded); // we disable nullable warnings on default arguments _disableDiagnostics = defaultArguments[i] || previousDisableDiagnostics; resultsBuilder.Add(VisitArgumentEvaluate(arguments[i], GetRefKind(refKindsOpt, i), parameterAnnotations)); visitedParameters.Add(parameter); } _disableDiagnostics = previousDisableDiagnostics; SetInvalidResult(); visitedParameters.Free(); return resultsBuilder.ToImmutableAndFree(); } private VisitArgumentResult VisitArgumentEvaluate(BoundExpression argument, RefKind refKind, FlowAnalysisAnnotations annotations) { Debug.Assert(!IsConditionalState); var savedState = (argument.Kind == BoundKind.Lambda) ? this.State.Clone() : default(Optional<LocalState>); // Note: DoesNotReturnIf is ineffective on ref/out parameters switch (refKind) { case RefKind.Ref: Visit(argument); Unsplit(); break; case RefKind.None: case RefKind.In: switch (annotations & (FlowAnalysisAnnotations.DoesNotReturnIfTrue | FlowAnalysisAnnotations.DoesNotReturnIfFalse)) { case FlowAnalysisAnnotations.DoesNotReturnIfTrue: Visit(argument); if (IsConditionalState) { SetState(StateWhenFalse); } break; case FlowAnalysisAnnotations.DoesNotReturnIfFalse: Visit(argument); if (IsConditionalState) { SetState(StateWhenTrue); } break; default: VisitRvalue(argument); break; } break; case RefKind.Out: // As far as we can tell, there is no scenario relevant to nullability analysis // where splitting an L-value (for instance with a ref conditional) would affect the result. Visit(argument); // We'll want to use the l-value type, rather than the result type, for method re-inference UseLvalueOnly(argument); break; } Debug.Assert(!IsConditionalState); return new VisitArgumentResult(_visitResult, savedState); } /// <summary> /// Verifies that an argument's nullability is compatible with its parameter's on the way in. /// </summary> private void VisitArgumentConversionAndInboundAssignmentsAndPreConditions( BoundConversion? conversionOpt, BoundExpression argumentNoConversion, Conversion conversion, RefKind refKind, ParameterSymbol parameter, TypeWithAnnotations parameterType, FlowAnalysisAnnotations parameterAnnotations, VisitArgumentResult result, bool extensionMethodThisArgument) { Debug.Assert(!this.IsConditionalState); // Note: we allow for some variance in `in` and `out` cases. Unlike in binding, we're not // limited by CLR constraints. var resultType = result.RValueType; switch (refKind) { case RefKind.None: case RefKind.In: { // Note: for lambda arguments, they will be converted in the context/state we saved for that argument if (conversion is { Kind: ConversionKind.ImplicitUserDefined }) { var argumentResultType = resultType.Type; conversion = GenerateConversion(_conversions, argumentNoConversion, argumentResultType, parameterType.Type, fromExplicitCast: false, extensionMethodThisArgument: false); if (!conversion.Exists && !argumentNoConversion.IsSuppressed) { Debug.Assert(argumentResultType is not null); ReportNullabilityMismatchInArgument(argumentNoConversion.Syntax, argumentResultType, parameter, parameterType.Type, forOutput: false); } } var stateAfterConversion = VisitConversion( conversionOpt: conversionOpt, conversionOperand: argumentNoConversion, conversion: conversion, targetTypeWithNullability: ApplyLValueAnnotations(parameterType, parameterAnnotations), operandType: resultType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, assignmentKind: AssignmentKind.Argument, parameterOpt: parameter, extensionMethodThisArgument: extensionMethodThisArgument, stateForLambda: result.StateForLambda); // If the parameter has annotations, we perform an additional check for nullable value types if (CheckDisallowedNullAssignment(stateAfterConversion, parameterAnnotations, argumentNoConversion.Syntax.Location)) { LearnFromNonNullTest(argumentNoConversion, ref State); } SetResultType(argumentNoConversion, stateAfterConversion, updateAnalyzedNullability: false); } break; case RefKind.Ref: if (!argumentNoConversion.IsSuppressed) { var lvalueResultType = result.LValueType; if (IsNullabilityMismatch(lvalueResultType.Type, parameterType.Type)) { // declared types must match, ignoring top-level nullability ReportNullabilityMismatchInRefArgument(argumentNoConversion, argumentType: lvalueResultType.Type, parameter, parameterType.Type); } else { // types match, but state would let a null in ReportNullableAssignmentIfNecessary(argumentNoConversion, ApplyLValueAnnotations(parameterType, parameterAnnotations), resultType, useLegacyWarnings: false); // If the parameter has annotations, we perform an additional check for nullable value types CheckDisallowedNullAssignment(resultType, parameterAnnotations, argumentNoConversion.Syntax.Location); } } break; case RefKind.Out: break; default: throw ExceptionUtilities.UnexpectedValue(refKind); } Debug.Assert(!this.IsConditionalState); } /// <summary>Returns <see langword="true"/> if this is an assignment forbidden by DisallowNullAttribute, otherwise <see langword="false"/>.</summary> private bool CheckDisallowedNullAssignment(TypeWithState state, FlowAnalysisAnnotations annotations, Location location, BoundExpression? boundValueOpt = null) { if (boundValueOpt is { WasCompilerGenerated: true }) { // We need to skip `return backingField;` in auto-prop getters return false; } // We do this extra check for types whose non-nullable version cannot be represented if (IsDisallowedNullAssignment(state, annotations)) { ReportDiagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, location); return true; } return false; } private static bool IsDisallowedNullAssignment(TypeWithState valueState, FlowAnalysisAnnotations targetAnnotations) { return ((targetAnnotations & FlowAnalysisAnnotations.DisallowNull) != 0) && hasNoNonNullableCounterpart(valueState.Type) && valueState.MayBeNull; static bool hasNoNonNullableCounterpart(TypeSymbol? type) { if (type is null) { return false; } // Some types that could receive a maybe-null value have a NotNull counterpart: // [NotNull]string? -> string // [NotNull]string -> string // [NotNull]TClass -> TClass // [NotNull]TClass? -> TClass // // While others don't: // [NotNull]int? -> X // [NotNull]TNullable -> X // [NotNull]TStruct? -> X // [NotNull]TOpen -> X return (type.Kind == SymbolKind.TypeParameter && !type.IsReferenceType) || type.IsNullableTypeOrTypeParameter(); } } /// <summary> /// Verifies that outbound assignments (from parameter to argument) are safe and /// tracks those assignments (or learns from post-condition attributes) /// </summary> private void VisitArgumentOutboundAssignmentsAndPostConditions( BoundExpression argument, RefKind refKind, ParameterSymbol parameter, TypeWithAnnotations parameterType, FlowAnalysisAnnotations parameterAnnotations, VisitArgumentResult result, ArrayBuilder<ParameterSymbol>? notNullParametersOpt, CompareExchangeInfo compareExchangeInfoOpt) { // Note: the state may be conditional if a previous argument involved a conditional post-condition // The WhenTrue/False states correspond to the invocation returning true/false switch (refKind) { case RefKind.None: case RefKind.In: { // learn from post-conditions [Maybe/NotNull, Maybe/NotNullWhen] without using an assignment learnFromPostConditions(argument, parameterType, parameterAnnotations); } break; case RefKind.Ref: { // assign from a fictional value from the parameter to the argument. parameterAnnotations = notNullBasedOnParameters(parameterAnnotations, notNullParametersOpt, parameter); var parameterWithState = TypeWithState.Create(parameterType, parameterAnnotations); if (!compareExchangeInfoOpt.IsDefault) { var adjustedState = LearnFromCompareExchangeMethod(in compareExchangeInfoOpt); parameterWithState = TypeWithState.Create(parameterType.Type, adjustedState); } var parameterValue = new BoundParameter(argument.Syntax, parameter); var lValueType = result.LValueType; trackNullableStateForAssignment(parameterValue, lValueType, MakeSlot(argument), parameterWithState, argument.IsSuppressed, parameterAnnotations); // check whether parameter would unsafely let a null out in the worse case if (!argument.IsSuppressed) { var leftAnnotations = GetLValueAnnotations(argument); ReportNullableAssignmentIfNecessary( parameterValue, targetType: ApplyLValueAnnotations(lValueType, leftAnnotations), valueType: applyPostConditionsUnconditionally(parameterWithState, parameterAnnotations), UseLegacyWarnings(argument, result.LValueType)); } } break; case RefKind.Out: { // compute the fictional parameter state parameterAnnotations = notNullBasedOnParameters(parameterAnnotations, notNullParametersOpt, parameter); var parameterWithState = TypeWithState.Create(parameterType, parameterAnnotations); // Adjust parameter state if MaybeNull or MaybeNullWhen are present (for `var` type and for assignment warnings) var worstCaseParameterWithState = applyPostConditionsUnconditionally(parameterWithState, parameterAnnotations); var declaredType = result.LValueType; var leftAnnotations = GetLValueAnnotations(argument); var lValueType = ApplyLValueAnnotations(declaredType, leftAnnotations); if (argument is BoundLocal local && local.DeclarationKind == BoundLocalDeclarationKind.WithInferredType) { var varType = worstCaseParameterWithState.ToAnnotatedTypeWithAnnotations(compilation); _variables.SetType(local.LocalSymbol, varType); lValueType = varType; } else if (argument is BoundDiscardExpression discard) { SetAnalyzedNullability(discard, new VisitResult(parameterWithState, parameterWithState.ToTypeWithAnnotations(compilation)), isLvalue: true); } // track state by assigning from a fictional value from the parameter to the argument. var parameterValue = new BoundParameter(argument.Syntax, parameter); // If the argument type has annotations, we perform an additional check for nullable value types CheckDisallowedNullAssignment(parameterWithState, leftAnnotations, argument.Syntax.Location); AdjustSetValue(argument, ref parameterWithState); trackNullableStateForAssignment(parameterValue, lValueType, MakeSlot(argument), parameterWithState, argument.IsSuppressed, parameterAnnotations); // report warnings if parameter would unsafely let a null out in the worst case if (!argument.IsSuppressed) { ReportNullableAssignmentIfNecessary(parameterValue, lValueType, worstCaseParameterWithState, UseLegacyWarnings(argument, result.LValueType)); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; if (!_conversions.HasIdentityOrImplicitReferenceConversion(parameterType.Type, lValueType.Type, ref discardedUseSiteInfo)) { ReportNullabilityMismatchInArgument(argument.Syntax, lValueType.Type, parameter, parameterType.Type, forOutput: true); } } } break; default: throw ExceptionUtilities.UnexpectedValue(refKind); } FlowAnalysisAnnotations notNullBasedOnParameters(FlowAnalysisAnnotations parameterAnnotations, ArrayBuilder<ParameterSymbol>? notNullParametersOpt, ParameterSymbol parameter) { if (!IsAnalyzingAttribute && notNullParametersOpt is object) { var notNullIfParameterNotNull = parameter.NotNullIfParameterNotNull; if (!notNullIfParameterNotNull.IsEmpty) { foreach (var notNullParameter in notNullParametersOpt) { if (notNullIfParameterNotNull.Contains(notNullParameter.Name)) { return FlowAnalysisAnnotations.NotNull; } } } } return parameterAnnotations; } void trackNullableStateForAssignment(BoundExpression parameterValue, TypeWithAnnotations lValueType, int targetSlot, TypeWithState parameterWithState, bool isSuppressed, FlowAnalysisAnnotations parameterAnnotations) { if (!IsConditionalState && !hasConditionalPostCondition(parameterAnnotations)) { TrackNullableStateForAssignment(parameterValue, lValueType, targetSlot, parameterWithState.WithSuppression(isSuppressed)); } else { Split(); var originalWhenFalse = StateWhenFalse.Clone(); SetState(StateWhenTrue); // Note: the suppression applies over the post-condition attributes TrackNullableStateForAssignment(parameterValue, lValueType, targetSlot, applyPostConditionsWhenTrue(parameterWithState, parameterAnnotations).WithSuppression(isSuppressed)); Debug.Assert(!IsConditionalState); var newWhenTrue = State.Clone(); SetState(originalWhenFalse); TrackNullableStateForAssignment(parameterValue, lValueType, targetSlot, applyPostConditionsWhenFalse(parameterWithState, parameterAnnotations).WithSuppression(isSuppressed)); Debug.Assert(!IsConditionalState); SetConditionalState(newWhenTrue, whenFalse: State); } } static bool hasConditionalPostCondition(FlowAnalysisAnnotations annotations) { return (((annotations & FlowAnalysisAnnotations.MaybeNullWhenTrue) != 0) ^ ((annotations & FlowAnalysisAnnotations.MaybeNullWhenFalse) != 0)) || (((annotations & FlowAnalysisAnnotations.NotNullWhenTrue) != 0) ^ ((annotations & FlowAnalysisAnnotations.NotNullWhenFalse) != 0)); } static TypeWithState applyPostConditionsUnconditionally(TypeWithState typeWithState, FlowAnalysisAnnotations annotations) { if ((annotations & FlowAnalysisAnnotations.MaybeNull) != 0) { // MaybeNull and MaybeNullWhen return TypeWithState.Create(typeWithState.Type, NullableFlowState.MaybeDefault); } if ((annotations & FlowAnalysisAnnotations.NotNull) == FlowAnalysisAnnotations.NotNull) { // NotNull return TypeWithState.Create(typeWithState.Type, NullableFlowState.NotNull); } return typeWithState; } static TypeWithState applyPostConditionsWhenTrue(TypeWithState typeWithState, FlowAnalysisAnnotations annotations) { bool notNullWhenTrue = (annotations & FlowAnalysisAnnotations.NotNullWhenTrue) != 0; bool maybeNullWhenTrue = (annotations & FlowAnalysisAnnotations.MaybeNullWhenTrue) != 0; bool maybeNullWhenFalse = (annotations & FlowAnalysisAnnotations.MaybeNullWhenFalse) != 0; if (maybeNullWhenTrue && !(maybeNullWhenFalse && notNullWhenTrue)) { // [MaybeNull, NotNullWhen(true)] means [MaybeNullWhen(false)] return TypeWithState.Create(typeWithState.Type, NullableFlowState.MaybeDefault); } else if (notNullWhenTrue) { return TypeWithState.Create(typeWithState.Type, NullableFlowState.NotNull); } return typeWithState; } static TypeWithState applyPostConditionsWhenFalse(TypeWithState typeWithState, FlowAnalysisAnnotations annotations) { bool notNullWhenFalse = (annotations & FlowAnalysisAnnotations.NotNullWhenFalse) != 0; bool maybeNullWhenTrue = (annotations & FlowAnalysisAnnotations.MaybeNullWhenTrue) != 0; bool maybeNullWhenFalse = (annotations & FlowAnalysisAnnotations.MaybeNullWhenFalse) != 0; if (maybeNullWhenFalse && !(maybeNullWhenTrue && notNullWhenFalse)) { // [MaybeNull, NotNullWhen(false)] means [MaybeNullWhen(true)] return TypeWithState.Create(typeWithState.Type, NullableFlowState.MaybeDefault); } else if (notNullWhenFalse) { return TypeWithState.Create(typeWithState.Type, NullableFlowState.NotNull); } return typeWithState; } void learnFromPostConditions(BoundExpression argument, TypeWithAnnotations parameterType, FlowAnalysisAnnotations parameterAnnotations) { // Note: NotNull = NotNullWhen(true) + NotNullWhen(false) bool notNullWhenTrue = (parameterAnnotations & FlowAnalysisAnnotations.NotNullWhenTrue) != 0; bool notNullWhenFalse = (parameterAnnotations & FlowAnalysisAnnotations.NotNullWhenFalse) != 0; // Note: MaybeNull = MaybeNullWhen(true) + MaybeNullWhen(false) bool maybeNullWhenTrue = (parameterAnnotations & FlowAnalysisAnnotations.MaybeNullWhenTrue) != 0; bool maybeNullWhenFalse = (parameterAnnotations & FlowAnalysisAnnotations.MaybeNullWhenFalse) != 0; if (maybeNullWhenTrue && maybeNullWhenFalse && !IsConditionalState && !(notNullWhenTrue && notNullWhenFalse)) { LearnFromNullTest(argument, ref State); } else if (notNullWhenTrue && notNullWhenFalse && !IsConditionalState && !(maybeNullWhenTrue || maybeNullWhenFalse)) { LearnFromNonNullTest(argument, ref State); } else if (notNullWhenTrue || notNullWhenFalse || maybeNullWhenTrue || maybeNullWhenFalse) { Split(); if (notNullWhenTrue) { LearnFromNonNullTest(argument, ref StateWhenTrue); } if (notNullWhenFalse) { LearnFromNonNullTest(argument, ref StateWhenFalse); } if (maybeNullWhenTrue) { LearnFromNullTest(argument, ref StateWhenTrue); } if (maybeNullWhenFalse) { LearnFromNullTest(argument, ref StateWhenFalse); } } } } private (ImmutableArray<BoundExpression> arguments, ImmutableArray<Conversion> conversions) RemoveArgumentConversions( ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> refKindsOpt) { int n = arguments.Length; var conversions = default(ImmutableArray<Conversion>); if (n > 0) { var argumentsBuilder = ArrayBuilder<BoundExpression>.GetInstance(n); var conversionsBuilder = ArrayBuilder<Conversion>.GetInstance(n); bool includedConversion = false; for (int i = 0; i < n; i++) { RefKind refKind = GetRefKind(refKindsOpt, i); var argument = arguments[i]; var conversion = Conversion.Identity; if (refKind == RefKind.None) { var before = argument; (argument, conversion) = RemoveConversion(argument, includeExplicitConversions: false); if (argument != before) { SnapshotWalkerThroughConversionGroup(before, argument); includedConversion = true; } } argumentsBuilder.Add(argument); conversionsBuilder.Add(conversion); } if (includedConversion) { arguments = argumentsBuilder.ToImmutable(); conversions = conversionsBuilder.ToImmutable(); } argumentsBuilder.Free(); conversionsBuilder.Free(); } return (arguments, conversions); } private static VariableState GetVariableState(Variables variables, LocalState localState) { Debug.Assert(variables.Id == localState.Id); return new VariableState(variables.CreateSnapshot(), localState.CreateSnapshot()); } private (ParameterSymbol? Parameter, TypeWithAnnotations Type, FlowAnalysisAnnotations Annotations, bool isExpandedParamsArgument) GetCorrespondingParameter( int argumentOrdinal, ImmutableArray<ParameterSymbol> parametersOpt, ImmutableArray<int> argsToParamsOpt, bool expanded) { if (parametersOpt.IsDefault) { return default; } var parameter = Binder.GetCorrespondingParameter(argumentOrdinal, parametersOpt, argsToParamsOpt, expanded); if (parameter is null) { Debug.Assert(!expanded); return default; } var type = parameter.TypeWithAnnotations; if (expanded && parameter.Ordinal == parametersOpt.Length - 1 && type.IsSZArray()) { type = ((ArrayTypeSymbol)type.Type).ElementTypeWithAnnotations; return (parameter, type, FlowAnalysisAnnotations.None, isExpandedParamsArgument: true); } return (parameter, type, GetParameterAnnotations(parameter), isExpandedParamsArgument: false); } private MethodSymbol InferMethodTypeArguments( MethodSymbol method, ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> argumentRefKindsOpt, ImmutableArray<int> argsToParamsOpt, bool expanded) { Debug.Assert(method.IsGenericMethod); // https://github.com/dotnet/roslyn/issues/27961 OverloadResolution.IsMemberApplicableInNormalForm and // IsMemberApplicableInExpandedForm use the least overridden method. We need to do the same here. var definition = method.ConstructedFrom; var refKinds = ArrayBuilder<RefKind>.GetInstance(); if (argumentRefKindsOpt != null) { refKinds.AddRange(argumentRefKindsOpt); } // https://github.com/dotnet/roslyn/issues/27961 Do we really need OverloadResolution.GetEffectiveParameterTypes? // Aren't we doing roughly the same calculations in GetCorrespondingParameter? OverloadResolution.GetEffectiveParameterTypes( definition, arguments.Length, argsToParamsOpt, refKinds, isMethodGroupConversion: false, // https://github.com/dotnet/roslyn/issues/27961 `allowRefOmittedArguments` should be // false for constructors and several other cases (see Binder use). Should we // capture the original value in the BoundCall? allowRefOmittedArguments: true, binder: _binder, expanded: expanded, parameterTypes: out ImmutableArray<TypeWithAnnotations> parameterTypes, parameterRefKinds: out ImmutableArray<RefKind> parameterRefKinds); refKinds.Free(); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var result = MethodTypeInferrer.Infer( _binder, _conversions, definition.TypeParameters, definition.ContainingType, parameterTypes, parameterRefKinds, arguments, ref discardedUseSiteInfo, new MethodInferenceExtensions(this)); if (!result.Success) { return method; } return definition.Construct(result.InferredTypeArguments); } private sealed class MethodInferenceExtensions : MethodTypeInferrer.Extensions { private readonly NullableWalker _walker; internal MethodInferenceExtensions(NullableWalker walker) { _walker = walker; } internal override TypeWithAnnotations GetTypeWithAnnotations(BoundExpression expr) { return TypeWithAnnotations.Create(expr.GetTypeOrFunctionType(), GetNullableAnnotation(expr)); } /// <summary> /// Return top-level nullability for the expression. This method should be called on a limited /// set of expressions only. It should not be called on expressions tracked by flow analysis /// other than <see cref="BoundKind.ExpressionWithNullability"/> which is an expression /// specifically created in NullableWalker to represent the flow analysis state. /// </summary> private static NullableAnnotation GetNullableAnnotation(BoundExpression expr) { switch (expr.Kind) { case BoundKind.DefaultLiteral: case BoundKind.DefaultExpression: case BoundKind.Literal: return expr.ConstantValue == ConstantValue.NotAvailable || !expr.ConstantValue.IsNull || expr.IsSuppressed ? NullableAnnotation.NotAnnotated : NullableAnnotation.Annotated; case BoundKind.ExpressionWithNullability: return ((BoundExpressionWithNullability)expr).NullableAnnotation; case BoundKind.MethodGroup: case BoundKind.UnboundLambda: case BoundKind.UnconvertedObjectCreationExpression: return NullableAnnotation.NotAnnotated; default: Debug.Assert(false); // unexpected value return NullableAnnotation.Oblivious; } } internal override TypeWithAnnotations GetMethodGroupResultType(BoundMethodGroup group, MethodSymbol method) { if (_walker.TryGetMethodGroupReceiverNullability(group.ReceiverOpt, out TypeWithState receiverType)) { if (!method.IsStatic) { method = (MethodSymbol)AsMemberOfType(receiverType.Type, method); } } return method.ReturnTypeWithAnnotations; } } private ImmutableArray<BoundExpression> GetArgumentsForMethodTypeInference(ImmutableArray<VisitArgumentResult> argumentResults, ImmutableArray<BoundExpression> arguments) { // https://github.com/dotnet/roslyn/issues/27961 MethodTypeInferrer.Infer relies // on the BoundExpressions for tuple element types and method groups. // By using a generic BoundValuePlaceholder, we're losing inference in those cases. // https://github.com/dotnet/roslyn/issues/27961 Inference should be based on // unconverted arguments. Consider cases such as `default`, lambdas, tuples. int n = argumentResults.Length; var builder = ArrayBuilder<BoundExpression>.GetInstance(n); for (int i = 0; i < n; i++) { var visitArgumentResult = argumentResults[i]; var lambdaState = visitArgumentResult.StateForLambda; // Note: for `out` arguments, the argument result contains the declaration type (see `VisitArgumentEvaluate`) var argumentResult = visitArgumentResult.RValueType.ToTypeWithAnnotations(compilation); builder.Add(getArgumentForMethodTypeInference(arguments[i], argumentResult, lambdaState)); } return builder.ToImmutableAndFree(); BoundExpression getArgumentForMethodTypeInference(BoundExpression argument, TypeWithAnnotations argumentType, Optional<LocalState> lambdaState) { if (argument.Kind == BoundKind.Lambda) { Debug.Assert(lambdaState.HasValue); // MethodTypeInferrer must infer nullability for lambdas based on the nullability // from flow analysis rather than the declared nullability. To allow that, we need // to re-bind lambdas in MethodTypeInferrer. return getUnboundLambda((BoundLambda)argument, GetVariableState(_variables, lambdaState.Value)); } if (!argumentType.HasType) { return argument; } if (argument is BoundLocal { DeclarationKind: BoundLocalDeclarationKind.WithInferredType } or BoundConditionalOperator { WasTargetTyped: true } or BoundConvertedSwitchExpression { WasTargetTyped: true }) { // target-typed contexts don't contribute to nullability return new BoundExpressionWithNullability(argument.Syntax, argument, NullableAnnotation.Oblivious, type: null); } return new BoundExpressionWithNullability(argument.Syntax, argument, argumentType.NullableAnnotation, argumentType.Type); } static UnboundLambda getUnboundLambda(BoundLambda expr, VariableState variableState) { return expr.UnboundLambda.WithNullableState(variableState); } } private void CheckMethodConstraints(SyntaxNode syntax, MethodSymbol method) { if (_disableDiagnostics) { return; } var diagnosticsBuilder = ArrayBuilder<TypeParameterDiagnosticInfo>.GetInstance(); var nullabilityBuilder = ArrayBuilder<TypeParameterDiagnosticInfo>.GetInstance(); ArrayBuilder<TypeParameterDiagnosticInfo>? useSiteDiagnosticsBuilder = null; ConstraintsHelper.CheckMethodConstraints( method, new ConstraintsHelper.CheckConstraintsArgs(compilation, _conversions, includeNullability: true, NoLocation.Singleton, diagnostics: null, template: CompoundUseSiteInfo<AssemblySymbol>.Discarded), diagnosticsBuilder, nullabilityBuilder, ref useSiteDiagnosticsBuilder); foreach (var pair in nullabilityBuilder) { if (pair.UseSiteInfo.DiagnosticInfo is object) { Diagnostics.Add(pair.UseSiteInfo.DiagnosticInfo, syntax.Location); } } useSiteDiagnosticsBuilder?.Free(); nullabilityBuilder.Free(); diagnosticsBuilder.Free(); } /// <summary> /// Returns the expression without the top-most conversion plus the conversion. /// If the expression is not a conversion, returns the original expression plus /// the Identity conversion. If `includeExplicitConversions` is true, implicit and /// explicit conversions are considered. If `includeExplicitConversions` is false /// only implicit conversions are considered and if the expression is an explicit /// conversion, the expression is returned as is, with the Identity conversion. /// (Currently, the only visit method that passes `includeExplicitConversions: true` /// is VisitConversion. All other callers are handling implicit conversions only.) /// </summary> private static (BoundExpression expression, Conversion conversion) RemoveConversion(BoundExpression expr, bool includeExplicitConversions) { ConversionGroup? group = null; while (true) { if (expr.Kind != BoundKind.Conversion) { break; } var conversion = (BoundConversion)expr; if (group != conversion.ConversionGroupOpt && group != null) { // E.g.: (C)(B)a break; } group = conversion.ConversionGroupOpt; Debug.Assert(group != null || !conversion.ExplicitCastInCode); // Explicit conversions should include a group. if (!includeExplicitConversions && group?.IsExplicitConversion == true) { return (expr, Conversion.Identity); } expr = conversion.Operand; if (group == null) { // Ungrouped conversion should not be followed by another ungrouped // conversion. Otherwise, the conversions should have been grouped. // https://github.com/dotnet/roslyn/issues/34919 This assertion does not always hold true for // enum initializers //Debug.Assert(expr.Kind != BoundKind.Conversion || // ((BoundConversion)expr).ConversionGroupOpt != null || // ((BoundConversion)expr).ConversionKind == ConversionKind.NoConversion); return (expr, conversion.Conversion); } } return (expr, group?.Conversion ?? Conversion.Identity); } // See Binder.BindNullCoalescingOperator for initial binding. private Conversion GenerateConversionForConditionalOperator(BoundExpression sourceExpression, TypeSymbol? sourceType, TypeSymbol destinationType, bool reportMismatch) { var conversion = GenerateConversion(_conversions, sourceExpression, sourceType, destinationType, fromExplicitCast: false, extensionMethodThisArgument: false); bool canConvertNestedNullability = conversion.Exists; if (!canConvertNestedNullability && reportMismatch && !sourceExpression.IsSuppressed) { ReportNullabilityMismatchInAssignment(sourceExpression.Syntax, GetTypeAsDiagnosticArgument(sourceType), destinationType); } return conversion; } private static Conversion GenerateConversion(Conversions conversions, BoundExpression? sourceExpression, TypeSymbol? sourceType, TypeSymbol destinationType, bool fromExplicitCast, bool extensionMethodThisArgument) { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; bool useExpression = sourceType is null || UseExpressionForConversion(sourceExpression); if (extensionMethodThisArgument) { return conversions.ClassifyImplicitExtensionMethodThisArgConversion( useExpression ? sourceExpression : null, sourceType, destinationType, ref discardedUseSiteInfo); } return useExpression ? (fromExplicitCast ? conversions.ClassifyConversionFromExpression(sourceExpression, destinationType, ref discardedUseSiteInfo, forCast: true) : conversions.ClassifyImplicitConversionFromExpression(sourceExpression, destinationType, ref discardedUseSiteInfo)) : (fromExplicitCast ? conversions.ClassifyConversionFromType(sourceType, destinationType, ref discardedUseSiteInfo, forCast: true) : conversions.ClassifyImplicitConversionFromType(sourceType, destinationType, ref discardedUseSiteInfo)); } /// <summary> /// Returns true if the expression should be used as the source when calculating /// a conversion from this expression, rather than using the type (with nullability) /// calculated by visiting this expression. Typically, that means expressions that /// do not have an explicit type but there are several other cases as well. /// (See expressions handled in ClassifyImplicitBuiltInConversionFromExpression.) /// </summary> private static bool UseExpressionForConversion([NotNullWhen(true)] BoundExpression? value) { if (value is null) { return false; } if (value.Type is null || value.Type.IsDynamic() || value.ConstantValue != null) { return true; } switch (value.Kind) { case BoundKind.InterpolatedString: return true; default: return false; } } /// <summary> /// Adjust declared type based on inferred nullability at the point of reference. /// </summary> private TypeWithState GetAdjustedResult(TypeWithState type, int slot) { if (this.State.HasValue(slot)) { NullableFlowState state = this.State[slot]; return TypeWithState.Create(type.Type, state); } return type; } /// <summary> /// Gets the corresponding member for a symbol from initial binding to match an updated receiver type in NullableWalker. /// For instance, this will map from List&lt;string~&gt;.Add(string~) to List&lt;string?&gt;.Add(string?) in the following example: /// <example> /// string s = null; /// var list = new[] { s }.ToList(); /// list.Add(null); /// </example> /// </summary> private static Symbol AsMemberOfType(TypeSymbol? type, Symbol symbol) { Debug.Assert((object)symbol != null); var containingType = type as NamedTypeSymbol; if (containingType is null || containingType.IsErrorType() || symbol is ErrorMethodSymbol) { return symbol; } if (symbol.Kind == SymbolKind.Method) { if (((MethodSymbol)symbol).MethodKind == MethodKind.LocalFunction) { // https://github.com/dotnet/roslyn/issues/27233 Handle type substitution for local functions. return symbol; } } if (symbol is TupleElementFieldSymbol or TupleErrorFieldSymbol) { return symbol.SymbolAsMember(containingType); } var symbolContainer = symbol.ContainingType; if (symbolContainer.IsAnonymousType) { int? memberIndex = symbol.Kind == SymbolKind.Property ? symbol.MemberIndexOpt : null; if (!memberIndex.HasValue) { return symbol; } return AnonymousTypeManager.GetAnonymousTypeProperty(containingType, memberIndex.GetValueOrDefault()); } if (!symbolContainer.IsGenericType) { Debug.Assert(symbol.ContainingType.IsDefinition); return symbol; } if (!containingType.IsGenericType) { return symbol; } if (symbolContainer.IsInterface) { if (tryAsMemberOfSingleType(containingType, out var result)) { return result; } foreach (var @interface in containingType.AllInterfacesNoUseSiteDiagnostics) { if (tryAsMemberOfSingleType(@interface, out result)) { return result; } } } else { while (true) { if (tryAsMemberOfSingleType(containingType, out var result)) { return result; } containingType = containingType.BaseTypeNoUseSiteDiagnostics; if ((object)containingType == null) { break; } } } Debug.Assert(false); // If this assert fails, add an appropriate test. return symbol; bool tryAsMemberOfSingleType(NamedTypeSymbol singleType, [NotNullWhen(true)] out Symbol? result) { if (!singleType.Equals(symbolContainer, TypeCompareKind.AllIgnoreOptions)) { result = null; return false; } var symbolDef = symbol.OriginalDefinition; result = symbolDef.SymbolAsMember(singleType); if (result is MethodSymbol resultMethod && resultMethod.IsGenericMethod) { result = resultMethod.Construct(((MethodSymbol)symbol).TypeArgumentsWithAnnotations); } return true; } } public override BoundNode? VisitConversion(BoundConversion node) { // https://github.com/dotnet/roslyn/issues/35732: Assert VisitConversion is only used for explicit conversions. //Debug.Assert(node.ExplicitCastInCode); //Debug.Assert(node.ConversionGroupOpt != null); //Debug.Assert(node.ConversionGroupOpt.ExplicitType.HasType); TypeWithAnnotations explicitType = node.ConversionGroupOpt?.ExplicitType ?? default; bool fromExplicitCast = explicitType.HasType; TypeWithAnnotations targetType = fromExplicitCast ? explicitType : TypeWithAnnotations.Create(node.Type); Debug.Assert(targetType.HasType); (BoundExpression operand, Conversion conversion) = RemoveConversion(node, includeExplicitConversions: true); SnapshotWalkerThroughConversionGroup(node, operand); TypeWithState operandType = VisitRvalueWithState(operand); SetResultType(node, VisitConversion( node, operand, conversion, targetType, operandType, checkConversion: true, fromExplicitCast: fromExplicitCast, useLegacyWarnings: fromExplicitCast, AssignmentKind.Assignment, reportTopLevelWarnings: fromExplicitCast, reportRemainingWarnings: true, trackMembers: true)); return null; } /// <summary> /// Visit an expression. If an explicit target type is provided, the expression is converted /// to that type. This method should be called whenever an expression may contain /// an implicit conversion, even if that conversion was omitted from the bound tree, /// so the conversion can be re-classified with nullability. /// </summary> private TypeWithState VisitOptionalImplicitConversion(BoundExpression expr, TypeWithAnnotations targetTypeOpt, bool useLegacyWarnings, bool trackMembers, AssignmentKind assignmentKind) { if (!targetTypeOpt.HasType) { return VisitRvalueWithState(expr); } (BoundExpression operand, Conversion conversion) = RemoveConversion(expr, includeExplicitConversions: false); SnapshotWalkerThroughConversionGroup(expr, operand); var operandType = VisitRvalueWithState(operand); // If an explicit conversion was used in place of an implicit conversion, the explicit // conversion was created by initial binding after reporting "error CS0266: // Cannot implicitly convert type '...' to '...'. An explicit conversion exists ...". // Since an error was reported, we don't need to report nested warnings as well. bool reportNestedWarnings = !conversion.IsExplicit; var resultType = VisitConversion( GetConversionIfApplicable(expr, operand), operand, conversion, targetTypeOpt, operandType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: useLegacyWarnings, assignmentKind, reportTopLevelWarnings: true, reportRemainingWarnings: reportNestedWarnings, trackMembers: trackMembers); return resultType; } private static bool AreNullableAndUnderlyingTypes([NotNullWhen(true)] TypeSymbol? nullableTypeOpt, [NotNullWhen(true)] TypeSymbol? underlyingTypeOpt, out TypeWithAnnotations underlyingTypeWithAnnotations) { if (nullableTypeOpt?.IsNullableType() == true && underlyingTypeOpt?.IsNullableType() == false) { var typeArg = nullableTypeOpt.GetNullableUnderlyingTypeWithAnnotations(); if (typeArg.Type.Equals(underlyingTypeOpt, TypeCompareKind.AllIgnoreOptions)) { underlyingTypeWithAnnotations = typeArg; return true; } } underlyingTypeWithAnnotations = default; return false; } public override BoundNode? VisitTupleLiteral(BoundTupleLiteral node) { VisitTupleExpression(node); return null; } public override BoundNode? VisitConvertedTupleLiteral(BoundConvertedTupleLiteral node) { Debug.Assert(!IsConditionalState); var savedState = this.State.Clone(); // Visit the source tuple so that the semantic model can correctly report nullability for it // Disable diagnostics, as we don't want to duplicate any that are produced by visiting the converted literal below VisitWithoutDiagnostics(node.SourceTuple); this.SetState(savedState); VisitTupleExpression(node); return null; } private void VisitTupleExpression(BoundTupleExpression node) { var arguments = node.Arguments; ImmutableArray<TypeWithState> elementTypes = arguments.SelectAsArray((a, w) => w.VisitRvalueWithState(a), this); ImmutableArray<TypeWithAnnotations> elementTypesWithAnnotations = elementTypes.SelectAsArray(a => a.ToTypeWithAnnotations(compilation)); var tupleOpt = (NamedTypeSymbol?)node.Type; if (tupleOpt is null) { SetResultType(node, TypeWithState.Create(null, NullableFlowState.NotNull)); } else { int slot = GetOrCreatePlaceholderSlot(node); if (slot > 0) { this.State[slot] = NullableFlowState.NotNull; TrackNullableStateOfTupleElements(slot, tupleOpt, arguments, elementTypes, argsToParamsOpt: default, useRestField: false); } tupleOpt = tupleOpt.WithElementTypes(elementTypesWithAnnotations); if (!_disableDiagnostics) { var locations = tupleOpt.TupleElements.SelectAsArray((element, location) => element.Locations.FirstOrDefault() ?? location, node.Syntax.Location); tupleOpt.CheckConstraints(new ConstraintsHelper.CheckConstraintsArgs(compilation, _conversions, includeNullability: true, node.Syntax.Location, diagnostics: null), typeSyntax: node.Syntax, locations, nullabilityDiagnosticsOpt: new BindingDiagnosticBag(Diagnostics)); } SetResultType(node, TypeWithState.Create(tupleOpt, NullableFlowState.NotNull)); } } /// <summary> /// Set the nullability of tuple elements for tuples at the point of construction. /// If <paramref name="useRestField"/> is true, the tuple was constructed with an explicit /// 'new ValueTuple' call, in which case the 8-th element, if any, represents the 'Rest' field. /// </summary> private void TrackNullableStateOfTupleElements( int slot, NamedTypeSymbol tupleType, ImmutableArray<BoundExpression> values, ImmutableArray<TypeWithState> types, ImmutableArray<int> argsToParamsOpt, bool useRestField) { Debug.Assert(tupleType.IsTupleType); Debug.Assert(values.Length == types.Length); Debug.Assert(values.Length == (useRestField ? Math.Min(tupleType.TupleElements.Length, NamedTypeSymbol.ValueTupleRestPosition) : tupleType.TupleElements.Length)); if (slot > 0) { var tupleElements = tupleType.TupleElements; int n = values.Length; if (useRestField) { n = Math.Min(n, NamedTypeSymbol.ValueTupleRestPosition - 1); } for (int i = 0; i < n; i++) { var argOrdinal = GetArgumentOrdinalFromParameterOrdinal(i); trackState(values[argOrdinal], tupleElements[i], types[argOrdinal]); } if (useRestField && values.Length == NamedTypeSymbol.ValueTupleRestPosition && tupleType.GetMembers(NamedTypeSymbol.ValueTupleRestFieldName).FirstOrDefault() is FieldSymbol restField) { var argOrdinal = GetArgumentOrdinalFromParameterOrdinal(NamedTypeSymbol.ValueTupleRestPosition - 1); trackState(values[argOrdinal], restField, types[argOrdinal]); } } void trackState(BoundExpression value, FieldSymbol field, TypeWithState valueType) { int targetSlot = GetOrCreateSlot(field, slot); TrackNullableStateForAssignment(value, field.TypeWithAnnotations, targetSlot, valueType, MakeSlot(value)); } int GetArgumentOrdinalFromParameterOrdinal(int parameterOrdinal) { var index = argsToParamsOpt.IsDefault ? parameterOrdinal : argsToParamsOpt.IndexOf(parameterOrdinal); Debug.Assert(index != -1); return index; } } private void TrackNullableStateOfNullableValue(int containingSlot, TypeSymbol containingType, BoundExpression? value, TypeWithState valueType, int valueSlot) { Debug.Assert(containingType.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T); Debug.Assert(containingSlot > 0); Debug.Assert(valueSlot > 0); int targetSlot = GetNullableOfTValueSlot(containingType, containingSlot, out Symbol? symbol); if (targetSlot > 0) { TrackNullableStateForAssignment(value, symbol!.GetTypeOrReturnType(), targetSlot, valueType, valueSlot); } } private void TrackNullableStateOfTupleConversion( BoundConversion? conversionOpt, BoundExpression convertedNode, Conversion conversion, TypeSymbol targetType, TypeSymbol operandType, int slot, int valueSlot, AssignmentKind assignmentKind, ParameterSymbol? parameterOpt, bool reportWarnings) { Debug.Assert(conversion.Kind == ConversionKind.ImplicitTuple || conversion.Kind == ConversionKind.ExplicitTuple); Debug.Assert(slot > 0); Debug.Assert(valueSlot > 0); var valueTuple = operandType as NamedTypeSymbol; if (valueTuple is null || !valueTuple.IsTupleType) { return; } var conversions = conversion.UnderlyingConversions; var targetElements = ((NamedTypeSymbol)targetType).TupleElements; var valueElements = valueTuple.TupleElements; int n = valueElements.Length; for (int i = 0; i < n; i++) { trackConvertedValue(targetElements[i], conversions[i], valueElements[i]); } void trackConvertedValue(FieldSymbol targetField, Conversion conversion, FieldSymbol valueField) { switch (conversion.Kind) { case ConversionKind.Identity: case ConversionKind.NullLiteral: case ConversionKind.DefaultLiteral: case ConversionKind.ImplicitReference: case ConversionKind.ExplicitReference: case ConversionKind.Boxing: case ConversionKind.Unboxing: InheritNullableStateOfMember(slot, valueSlot, valueField, isDefaultValue: false, skipSlot: slot); break; case ConversionKind.ImplicitTupleLiteral: case ConversionKind.ExplicitTupleLiteral: case ConversionKind.ImplicitTuple: case ConversionKind.ExplicitTuple: { int targetFieldSlot = GetOrCreateSlot(targetField, slot); if (targetFieldSlot > 0) { this.State[targetFieldSlot] = NullableFlowState.NotNull; int valueFieldSlot = GetOrCreateSlot(valueField, valueSlot); if (valueFieldSlot > 0) { TrackNullableStateOfTupleConversion(conversionOpt, convertedNode, conversion, targetField.Type, valueField.Type, targetFieldSlot, valueFieldSlot, assignmentKind, parameterOpt, reportWarnings); } } } break; case ConversionKind.ImplicitNullable: case ConversionKind.ExplicitNullable: // Conversion of T to Nullable<T> is equivalent to new Nullable<T>(t). if (AreNullableAndUnderlyingTypes(targetField.Type, valueField.Type, out _)) { int targetFieldSlot = GetOrCreateSlot(targetField, slot); if (targetFieldSlot > 0) { this.State[targetFieldSlot] = NullableFlowState.NotNull; int valueFieldSlot = GetOrCreateSlot(valueField, valueSlot); if (valueFieldSlot > 0) { TrackNullableStateOfNullableValue(targetFieldSlot, targetField.Type, null, valueField.TypeWithAnnotations.ToTypeWithState(), valueFieldSlot); } } } break; case ConversionKind.ImplicitUserDefined: case ConversionKind.ExplicitUserDefined: { var convertedType = VisitUserDefinedConversion( conversionOpt, convertedNode, conversion, targetField.TypeWithAnnotations, valueField.TypeWithAnnotations.ToTypeWithState(), useLegacyWarnings: false, assignmentKind, parameterOpt, reportTopLevelWarnings: reportWarnings, reportRemainingWarnings: reportWarnings, diagnosticLocation: (conversionOpt ?? convertedNode).Syntax.GetLocation()); int targetFieldSlot = GetOrCreateSlot(targetField, slot); if (targetFieldSlot > 0) { this.State[targetFieldSlot] = convertedType.State; } } break; default: break; } } } public override BoundNode? VisitTupleBinaryOperator(BoundTupleBinaryOperator node) { base.VisitTupleBinaryOperator(node); SetNotNullResult(node); return null; } private void ReportNullabilityMismatchWithTargetDelegate(Location location, TypeSymbol targetType, MethodSymbol targetInvokeMethod, MethodSymbol sourceInvokeMethod, bool invokedAsExtensionMethod) { SourceMemberContainerTypeSymbol.CheckValidNullableMethodOverride( compilation, targetInvokeMethod, sourceInvokeMethod, new BindingDiagnosticBag(Diagnostics), reportBadDelegateReturn, reportBadDelegateParameter, extraArgument: (targetType, location), invokedAsExtensionMethod: invokedAsExtensionMethod); void reportBadDelegateReturn(BindingDiagnosticBag bag, MethodSymbol targetInvokeMethod, MethodSymbol sourceInvokeMethod, bool topLevel, (TypeSymbol targetType, Location location) arg) { ReportDiagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, arg.location, new FormattedSymbol(sourceInvokeMethod, SymbolDisplayFormat.MinimallyQualifiedFormat), arg.targetType); } void reportBadDelegateParameter(BindingDiagnosticBag bag, MethodSymbol sourceInvokeMethod, MethodSymbol targetInvokeMethod, ParameterSymbol parameter, bool topLevel, (TypeSymbol targetType, Location location) arg) { ReportDiagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, arg.location, GetParameterAsDiagnosticArgument(parameter), GetContainingSymbolAsDiagnosticArgument(parameter), arg.targetType); } } private void ReportNullabilityMismatchWithTargetDelegate(Location location, NamedTypeSymbol delegateType, UnboundLambda unboundLambda) { if (!unboundLambda.HasExplicitlyTypedParameterList) { return; } var invoke = delegateType?.DelegateInvokeMethod; if (invoke is null) { return; } Debug.Assert(delegateType is object); if (unboundLambda.HasExplicitReturnType(out _, out var returnType) && IsNullabilityMismatch(invoke.ReturnTypeWithAnnotations, returnType, requireIdentity: true)) { ReportDiagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, location, unboundLambda.MessageID.Localize(), delegateType); } int count = Math.Min(invoke.ParameterCount, unboundLambda.ParameterCount); for (int i = 0; i < count; i++) { var invokeParameter = invoke.Parameters[i]; // Parameter nullability is expected to match exactly. This corresponds to the behavior of initial binding. // Action<string> x = (object o) => { }; // error CS1661: Cannot convert lambda expression to delegate type 'Action<string>' because the parameter types do not match the delegate parameter types // Action<object> y = (object? o) => { }; // warning CS8622: Nullability of reference types in type of parameter 'o' of 'lambda expression' doesn't match the target delegate 'Action<object>'. // https://github.com/dotnet/roslyn/issues/35564: Consider relaxing and allow implicit conversions of nullability. // (Compare with method group conversions which pass `requireIdentity: false`.) if (IsNullabilityMismatch(invokeParameter.TypeWithAnnotations, unboundLambda.ParameterTypeWithAnnotations(i), requireIdentity: true)) { // Should the warning be reported using location of specific lambda parameter? ReportDiagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, location, unboundLambda.ParameterName(i), unboundLambda.MessageID.Localize(), delegateType); } } } private bool IsNullabilityMismatch(TypeWithAnnotations source, TypeWithAnnotations destination, bool requireIdentity) { if (!HasTopLevelNullabilityConversion(source, destination, requireIdentity)) { return true; } if (requireIdentity) { return IsNullabilityMismatch(source, destination); } var sourceType = source.Type; var destinationType = destination.Type; var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; return !_conversions.ClassifyImplicitConversionFromType(sourceType, destinationType, ref discardedUseSiteInfo).Exists; } private bool HasTopLevelNullabilityConversion(TypeWithAnnotations source, TypeWithAnnotations destination, bool requireIdentity) { return requireIdentity ? _conversions.HasTopLevelNullabilityIdentityConversion(source, destination) : _conversions.HasTopLevelNullabilityImplicitConversion(source, destination); } /// <summary> /// Gets the conversion node for passing to <see cref="VisitConversion(BoundConversion, BoundExpression, Conversion, TypeWithAnnotations, TypeWithState, bool, bool, bool, AssignmentKind, ParameterSymbol, bool, bool, bool, Optional{LocalState}, bool, Location)"/>, /// if one should be passed. /// </summary> private static BoundConversion? GetConversionIfApplicable(BoundExpression? conversionOpt, BoundExpression convertedNode) { Debug.Assert(conversionOpt is null || convertedNode == conversionOpt // Note that convertedNode itself can be a BoundConversion, so we do this check explicitly // because the below calls to RemoveConversion could potentially strip that conversion. || convertedNode == RemoveConversion(conversionOpt, includeExplicitConversions: false).expression || convertedNode == RemoveConversion(conversionOpt, includeExplicitConversions: true).expression); return conversionOpt == convertedNode ? null : (BoundConversion?)conversionOpt; } /// <summary> /// Apply the conversion to the type of the operand and return the resulting type. /// If the operand does not have an explicit type, the operand expression is used. /// </summary> /// <param name="checkConversion"> /// If <see langword="true"/>, the incoming conversion is assumed to be from binding /// and will be re-calculated, this time considering nullability. /// Note that the conversion calculation considers nested nullability only. /// The caller is responsible for checking the top-level nullability of /// the type returned by this method. /// </param> /// <param name="trackMembers"> /// If <see langword="true"/>, the nullability of any members of the operand /// will be copied to the converted result when possible. /// </param> /// <param name="useLegacyWarnings"> /// If <see langword="true"/>, indicates that the "non-safety" diagnostic <see cref="ErrorCode.WRN_ConvertingNullableToNonNullable"/> /// should be given for an invalid conversion. /// </param> private TypeWithState VisitConversion( BoundConversion? conversionOpt, BoundExpression conversionOperand, Conversion conversion, TypeWithAnnotations targetTypeWithNullability, TypeWithState operandType, bool checkConversion, bool fromExplicitCast, bool useLegacyWarnings, AssignmentKind assignmentKind, ParameterSymbol? parameterOpt = null, bool reportTopLevelWarnings = true, bool reportRemainingWarnings = true, bool extensionMethodThisArgument = false, Optional<LocalState> stateForLambda = default, bool trackMembers = false, Location? diagnosticLocationOpt = null) { Debug.Assert(!trackMembers || !IsConditionalState); Debug.Assert(conversionOperand != null); NullableFlowState resultState = NullableFlowState.NotNull; bool canConvertNestedNullability = true; bool isSuppressed = false; diagnosticLocationOpt ??= (conversionOpt ?? conversionOperand).Syntax.GetLocation(); if (conversionOperand.IsSuppressed == true) { reportTopLevelWarnings = false; reportRemainingWarnings = false; isSuppressed = true; } #nullable disable TypeSymbol targetType = targetTypeWithNullability.Type; switch (conversion.Kind) { case ConversionKind.MethodGroup: { var group = conversionOperand as BoundMethodGroup; var (invokeSignature, parameters) = getDelegateOrFunctionPointerInfo(targetType); var method = conversion.Method; if (group != null) { if (method?.OriginalDefinition is LocalFunctionSymbol localFunc) { VisitLocalFunctionUse(localFunc); } method = CheckMethodGroupReceiverNullability(group, parameters, method, conversion.IsExtensionMethod); } if (reportRemainingWarnings && invokeSignature != null) { ReportNullabilityMismatchWithTargetDelegate(diagnosticLocationOpt, targetType, invokeSignature, method, conversion.IsExtensionMethod); } } resultState = NullableFlowState.NotNull; break; static (MethodSymbol invokeSignature, ImmutableArray<ParameterSymbol>) getDelegateOrFunctionPointerInfo(TypeSymbol targetType) => targetType switch { NamedTypeSymbol { TypeKind: TypeKind.Delegate, DelegateInvokeMethod: { Parameters: { } parameters } signature } => (signature, parameters), FunctionPointerTypeSymbol { Signature: { Parameters: { } parameters } signature } => (signature, parameters), _ => (null, ImmutableArray<ParameterSymbol>.Empty), }; case ConversionKind.AnonymousFunction: if (conversionOperand is BoundLambda lambda) { var delegateType = targetType.GetDelegateType(); VisitLambda(lambda, delegateType, stateForLambda); if (reportRemainingWarnings) { ReportNullabilityMismatchWithTargetDelegate(diagnosticLocationOpt, delegateType, lambda.UnboundLambda); } TrackAnalyzedNullabilityThroughConversionGroup(targetTypeWithNullability.ToTypeWithState(), conversionOpt, conversionOperand); return TypeWithState.Create(targetType, NullableFlowState.NotNull); } break; case ConversionKind.FunctionType: resultState = NullableFlowState.NotNull; break; case ConversionKind.InterpolatedString: resultState = NullableFlowState.NotNull; break; case ConversionKind.InterpolatedStringHandler: // https://github.com/dotnet/roslyn/issues/54583 Handle resultState = NullableFlowState.NotNull; break; case ConversionKind.ObjectCreation: case ConversionKind.SwitchExpression: case ConversionKind.ConditionalExpression: resultState = visitNestedTargetTypedConstructs(); TrackAnalyzedNullabilityThroughConversionGroup(targetTypeWithNullability.ToTypeWithState(), conversionOpt, conversionOperand); break; case ConversionKind.ExplicitUserDefined: case ConversionKind.ImplicitUserDefined: return VisitUserDefinedConversion(conversionOpt, conversionOperand, conversion, targetTypeWithNullability, operandType, useLegacyWarnings, assignmentKind, parameterOpt, reportTopLevelWarnings, reportRemainingWarnings, diagnosticLocationOpt); case ConversionKind.ExplicitDynamic: case ConversionKind.ImplicitDynamic: resultState = getConversionResultState(operandType); break; case ConversionKind.Boxing: resultState = getBoxingConversionResultState(targetTypeWithNullability, operandType); break; case ConversionKind.Unboxing: if (targetType.IsNonNullableValueType()) { if (!operandType.IsNotNull && reportRemainingWarnings) { ReportDiagnostic(ErrorCode.WRN_UnboxPossibleNull, diagnosticLocationOpt); } LearnFromNonNullTest(conversionOperand, ref State); } else { resultState = getUnboxingConversionResultState(operandType); } break; case ConversionKind.ImplicitThrow: resultState = NullableFlowState.NotNull; break; case ConversionKind.NoConversion: resultState = getConversionResultState(operandType); break; case ConversionKind.NullLiteral: case ConversionKind.DefaultLiteral: checkConversion = false; goto case ConversionKind.Identity; case ConversionKind.Identity: // If the operand is an explicit conversion, and this identity conversion // is converting to the same type including nullability, skip the conversion // to avoid reporting redundant warnings. Also check useLegacyWarnings // since that value was used when reporting warnings for the explicit cast. // Don't skip the node when it's a user-defined conversion, as identity conversions // on top of user-defined conversions means that we're coming in from VisitUserDefinedConversion // and that any warnings caught by this recursive call of VisitConversion won't be redundant. if (useLegacyWarnings && conversionOperand is BoundConversion operandConversion && !operandConversion.ConversionKind.IsUserDefinedConversion()) { var explicitType = operandConversion.ConversionGroupOpt?.ExplicitType; if (explicitType?.Equals(targetTypeWithNullability, TypeCompareKind.ConsiderEverything) == true) { TrackAnalyzedNullabilityThroughConversionGroup( calculateResultType(targetTypeWithNullability, fromExplicitCast, operandType.State, isSuppressed, targetType), conversionOpt, conversionOperand); return operandType; } } if (operandType.Type?.IsTupleType == true || conversionOperand.Kind == BoundKind.TupleLiteral) { goto case ConversionKind.ImplicitTuple; } goto case ConversionKind.ImplicitReference; case ConversionKind.ImplicitReference: case ConversionKind.ExplicitReference: // Inherit state from the operand. if (checkConversion) { conversion = GenerateConversion(_conversions, conversionOperand, operandType.Type, targetType, fromExplicitCast, extensionMethodThisArgument); canConvertNestedNullability = conversion.Exists; } resultState = conversion.IsReference ? getReferenceConversionResultState(targetTypeWithNullability, operandType) : operandType.State; break; case ConversionKind.ImplicitNullable: if (trackMembers) { Debug.Assert(conversionOperand != null); if (AreNullableAndUnderlyingTypes(targetType, operandType.Type, out TypeWithAnnotations underlyingType)) { // Conversion of T to Nullable<T> is equivalent to new Nullable<T>(t). int valueSlot = MakeSlot(conversionOperand); if (valueSlot > 0) { int containingSlot = GetOrCreatePlaceholderSlot(conversionOpt); Debug.Assert(containingSlot > 0); TrackNullableStateOfNullableValue(containingSlot, targetType, conversionOperand, underlyingType.ToTypeWithState(), valueSlot); } } } if (checkConversion) { conversion = GenerateConversion(_conversions, conversionOperand, operandType.Type, targetType, fromExplicitCast, extensionMethodThisArgument); canConvertNestedNullability = conversion.Exists; } resultState = operandType.State; break; case ConversionKind.ExplicitNullable: if (operandType.Type?.IsNullableType() == true && !targetType.IsNullableType()) { // Explicit conversion of Nullable<T> to T is equivalent to Nullable<T>.Value. if (reportTopLevelWarnings && operandType.MayBeNull) { ReportDiagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, diagnosticLocationOpt); } // Mark the value as not nullable, regardless of whether it was known to be nullable, // because the implied call to `.Value` will only succeed if not null. if (conversionOperand != null) { LearnFromNonNullTest(conversionOperand, ref State); } } goto case ConversionKind.ImplicitNullable; case ConversionKind.ImplicitTuple: case ConversionKind.ImplicitTupleLiteral: case ConversionKind.ExplicitTupleLiteral: case ConversionKind.ExplicitTuple: if (trackMembers) { Debug.Assert(conversionOperand != null); switch (conversion.Kind) { case ConversionKind.ImplicitTuple: case ConversionKind.ExplicitTuple: int valueSlot = MakeSlot(conversionOperand); if (valueSlot > 0) { int slot = GetOrCreatePlaceholderSlot(conversionOpt); if (slot > 0) { TrackNullableStateOfTupleConversion(conversionOpt, conversionOperand, conversion, targetType, operandType.Type, slot, valueSlot, assignmentKind, parameterOpt, reportWarnings: reportRemainingWarnings); } } break; } } if (checkConversion && !targetType.IsErrorType()) { // https://github.com/dotnet/roslyn/issues/29699: Report warnings for user-defined conversions on tuple elements. conversion = GenerateConversion(_conversions, conversionOperand, operandType.Type, targetType, fromExplicitCast, extensionMethodThisArgument); canConvertNestedNullability = conversion.Exists; } resultState = NullableFlowState.NotNull; break; case ConversionKind.Deconstruction: // Can reach here, with an error type, when the // Deconstruct method is missing or inaccessible. break; case ConversionKind.ExplicitEnumeration: // Can reach here, with an error type. break; default: Debug.Assert(targetType.IsValueType || targetType.IsErrorType()); break; } TypeWithState resultType = calculateResultType(targetTypeWithNullability, fromExplicitCast, resultState, isSuppressed, targetType); if (operandType.Type?.IsErrorType() != true && !targetType.IsErrorType()) { // Need to report all warnings that apply since the warnings can be suppressed individually. if (reportTopLevelWarnings) { ReportNullableAssignmentIfNecessary(conversionOperand, targetTypeWithNullability, resultType, useLegacyWarnings, assignmentKind, parameterOpt, diagnosticLocationOpt); } if (reportRemainingWarnings && !canConvertNestedNullability) { if (assignmentKind == AssignmentKind.Argument) { ReportNullabilityMismatchInArgument(diagnosticLocationOpt, operandType.Type, parameterOpt, targetType, forOutput: false); } else { ReportNullabilityMismatchInAssignment(diagnosticLocationOpt, GetTypeAsDiagnosticArgument(operandType.Type), targetType); } } } TrackAnalyzedNullabilityThroughConversionGroup(resultType, conversionOpt, conversionOperand); return resultType; #nullable enable static TypeWithState calculateResultType(TypeWithAnnotations targetTypeWithNullability, bool fromExplicitCast, NullableFlowState resultState, bool isSuppressed, TypeSymbol targetType) { if (isSuppressed) { resultState = NullableFlowState.NotNull; } else if (fromExplicitCast && targetTypeWithNullability.NullableAnnotation.IsAnnotated() && !targetType.IsNullableType()) { // An explicit cast to a nullable reference type introduces nullability resultState = targetType?.IsTypeParameterDisallowingAnnotationInCSharp8() == true ? NullableFlowState.MaybeDefault : NullableFlowState.MaybeNull; } var resultType = TypeWithState.Create(targetType, resultState); return resultType; } static NullableFlowState getReferenceConversionResultState(TypeWithAnnotations targetType, TypeWithState operandType) { var state = operandType.State; switch (state) { case NullableFlowState.MaybeNull: if (targetType.Type?.IsTypeParameterDisallowingAnnotationInCSharp8() == true) { var type = operandType.Type; if (type is null || !type.IsTypeParameterDisallowingAnnotationInCSharp8()) { return NullableFlowState.MaybeDefault; } else if (targetType.NullableAnnotation.IsNotAnnotated() && type is TypeParameterSymbol typeParameter1 && dependsOnTypeParameter(typeParameter1, (TypeParameterSymbol)targetType.Type, NullableAnnotation.NotAnnotated, out var annotation)) { return (annotation == NullableAnnotation.Annotated) ? NullableFlowState.MaybeDefault : NullableFlowState.MaybeNull; } } break; case NullableFlowState.MaybeDefault: if (targetType.Type?.IsTypeParameterDisallowingAnnotationInCSharp8() == false) { return NullableFlowState.MaybeNull; } break; } return state; } // Converting to a less-derived type (object, interface, type parameter). // If the operand is MaybeNull, the result should be // MaybeNull (if the target type allows) or MaybeDefault otherwise. static NullableFlowState getBoxingConversionResultState(TypeWithAnnotations targetType, TypeWithState operandType) { var state = operandType.State; if (state == NullableFlowState.MaybeNull) { var type = operandType.Type; if (type is null || !type.IsTypeParameterDisallowingAnnotationInCSharp8()) { return NullableFlowState.MaybeDefault; } else if (targetType.NullableAnnotation.IsNotAnnotated() && type is TypeParameterSymbol typeParameter1 && targetType.Type is TypeParameterSymbol typeParameter2) { bool dependsOn = dependsOnTypeParameter(typeParameter1, typeParameter2, NullableAnnotation.NotAnnotated, out var annotation); Debug.Assert(dependsOn); // If this case fails, add a corresponding test. if (dependsOn) { return (annotation == NullableAnnotation.Annotated) ? NullableFlowState.MaybeDefault : NullableFlowState.MaybeNull; } } } return state; } // Converting to a more-derived type (struct, class, type parameter). // If the operand is MaybeNull or MaybeDefault, the result should be // MaybeDefault. static NullableFlowState getUnboxingConversionResultState(TypeWithState operandType) { var state = operandType.State; if (state == NullableFlowState.MaybeNull) { return NullableFlowState.MaybeDefault; } return state; } static NullableFlowState getConversionResultState(TypeWithState operandType) { var state = operandType.State; if (state == NullableFlowState.MaybeNull) { return NullableFlowState.MaybeDefault; } return state; } // If type parameter 1 depends on type parameter 2 (that is, if type parameter 2 appears // in the constraint types of type parameter 1), returns the effective annotation on // type parameter 2 in the constraints of type parameter 1. static bool dependsOnTypeParameter(TypeParameterSymbol typeParameter1, TypeParameterSymbol typeParameter2, NullableAnnotation typeParameter1Annotation, out NullableAnnotation annotation) { if (typeParameter1.Equals(typeParameter2, TypeCompareKind.AllIgnoreOptions)) { annotation = typeParameter1Annotation; return true; } bool dependsOn = false; var combinedAnnotation = NullableAnnotation.Annotated; foreach (var constraintType in typeParameter1.ConstraintTypesNoUseSiteDiagnostics) { if (constraintType.Type is TypeParameterSymbol constraintTypeParameter && dependsOnTypeParameter(constraintTypeParameter, typeParameter2, constraintType.NullableAnnotation, out var constraintAnnotation)) { dependsOn = true; combinedAnnotation = combinedAnnotation.Meet(constraintAnnotation); } } if (dependsOn) { annotation = combinedAnnotation.Join(typeParameter1Annotation); return true; } annotation = default; return false; } NullableFlowState visitNestedTargetTypedConstructs() { switch (conversionOperand) { case BoundConditionalOperator { WasTargetTyped: true } conditional: { Debug.Assert(ConditionalInfoForConversion.ContainsKey(conditional)); var info = ConditionalInfoForConversion[conditional]; Debug.Assert(info.Length == 2); var consequence = conditional.Consequence; (BoundExpression consequenceOperand, Conversion consequenceConversion) = RemoveConversion(consequence, includeExplicitConversions: false); var consequenceRValue = ConvertConditionalOperandOrSwitchExpressionArmResult(consequence, consequenceOperand, consequenceConversion, targetTypeWithNullability, info[0].ResultType, info[0].State, info[0].EndReachable); var alternative = conditional.Alternative; (BoundExpression alternativeOperand, Conversion alternativeConversion) = RemoveConversion(alternative, includeExplicitConversions: false); var alternativeRValue = ConvertConditionalOperandOrSwitchExpressionArmResult(alternative, alternativeOperand, alternativeConversion, targetTypeWithNullability, info[1].ResultType, info[1].State, info[1].EndReachable); ConditionalInfoForConversion.Remove(conditional); return consequenceRValue.State.Join(alternativeRValue.State); } case BoundConvertedSwitchExpression { WasTargetTyped: true } @switch: { Debug.Assert(ConditionalInfoForConversion.ContainsKey(@switch)); var info = ConditionalInfoForConversion[@switch]; Debug.Assert(info.Length == @switch.SwitchArms.Length); var resultTypes = ArrayBuilder<TypeWithState>.GetInstance(info.Length); for (int i = 0; i < info.Length; i++) { var (state, armResultType, isReachable) = info[i]; var arm = @switch.SwitchArms[i].Value; var (operand, conversion) = RemoveConversion(arm, includeExplicitConversions: false); resultTypes.Add(ConvertConditionalOperandOrSwitchExpressionArmResult(arm, operand, conversion, targetTypeWithNullability, armResultType, state, isReachable)); } var resultState = BestTypeInferrer.GetNullableState(resultTypes); resultTypes.Free(); ConditionalInfoForConversion.Remove(@switch); return resultState; } case BoundObjectCreationExpression { WasTargetTyped: true }: case BoundUnconvertedObjectCreationExpression: return NullableFlowState.NotNull; case BoundUnconvertedConditionalOperator: case BoundUnconvertedSwitchExpression: return operandType.State; default: throw ExceptionUtilities.UnexpectedValue(conversionOperand.Kind); } } } private TypeWithState VisitUserDefinedConversion( BoundConversion? conversionOpt, BoundExpression conversionOperand, Conversion conversion, TypeWithAnnotations targetTypeWithNullability, TypeWithState operandType, bool useLegacyWarnings, AssignmentKind assignmentKind, ParameterSymbol? parameterOpt, bool reportTopLevelWarnings, bool reportRemainingWarnings, Location diagnosticLocation) { Debug.Assert(!IsConditionalState); Debug.Assert(conversionOperand != null); Debug.Assert(targetTypeWithNullability.HasType); Debug.Assert(diagnosticLocation != null); Debug.Assert(conversion.Kind == ConversionKind.ExplicitUserDefined || conversion.Kind == ConversionKind.ImplicitUserDefined); TypeSymbol targetType = targetTypeWithNullability.Type; // cf. Binder.CreateUserDefinedConversion if (!conversion.IsValid) { var resultType = TypeWithState.Create(targetType, NullableFlowState.NotNull); TrackAnalyzedNullabilityThroughConversionGroup(resultType, conversionOpt, conversionOperand); return resultType; } // operand -> conversion "from" type // May be distinct from method parameter type for Nullable<T>. operandType = VisitConversion( conversionOpt, conversionOperand, conversion.UserDefinedFromConversion, TypeWithAnnotations.Create(conversion.BestUserDefinedConversionAnalysis!.FromType), operandType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings, assignmentKind, parameterOpt, reportTopLevelWarnings, reportRemainingWarnings, diagnosticLocationOpt: diagnosticLocation); // Update method based on operandType: see https://github.com/dotnet/roslyn/issues/29605. // (see NullableReferenceTypesTests.ImplicitConversions_07). var method = conversion.Method; Debug.Assert(method is object); Debug.Assert(method.ParameterCount == 1); Debug.Assert(operandType.Type is object); var parameter = method.Parameters[0]; var parameterAnnotations = GetParameterAnnotations(parameter); var parameterType = ApplyLValueAnnotations(parameter.TypeWithAnnotations, parameterAnnotations); TypeWithState underlyingOperandType = default; bool isLiftedConversion = false; if (operandType.Type.IsNullableType() && !parameterType.IsNullableType()) { var underlyingOperandTypeWithAnnotations = operandType.Type.GetNullableUnderlyingTypeWithAnnotations(); underlyingOperandType = underlyingOperandTypeWithAnnotations.ToTypeWithState(); isLiftedConversion = parameterType.Equals(underlyingOperandTypeWithAnnotations, TypeCompareKind.AllIgnoreOptions); } // conversion "from" type -> method parameter type NullableFlowState operandState = operandType.State; Location operandLocation = conversionOperand.Syntax.GetLocation(); _ = ClassifyAndVisitConversion( conversionOperand, parameterType, isLiftedConversion ? underlyingOperandType : operandType, useLegacyWarnings, AssignmentKind.Argument, parameterOpt: parameter, reportWarnings: reportRemainingWarnings, fromExplicitCast: false, diagnosticLocation: operandLocation); // in the case of a lifted conversion, we assume that the call to the operator occurs only if the argument is not-null if (!isLiftedConversion && CheckDisallowedNullAssignment(operandType, parameterAnnotations, conversionOperand.Syntax.Location)) { LearnFromNonNullTest(conversionOperand, ref State); } // method parameter type -> method return type var methodReturnType = method.ReturnTypeWithAnnotations; operandType = GetLiftedReturnTypeIfNecessary(isLiftedConversion, methodReturnType, operandState); if (!isLiftedConversion || operandState.IsNotNull()) { var returnNotNull = operandState.IsNotNull() && method.ReturnNotNullIfParameterNotNull.Contains(parameter.Name); if (returnNotNull) { operandType = operandType.WithNotNullState(); } else { operandType = ApplyUnconditionalAnnotations(operandType, GetRValueAnnotations(method)); } } // method return type -> conversion "to" type // May be distinct from method return type for Nullable<T>. operandType = ClassifyAndVisitConversion( conversionOperand, TypeWithAnnotations.Create(conversion.BestUserDefinedConversionAnalysis!.ToType), operandType, useLegacyWarnings, assignmentKind, parameterOpt, reportWarnings: reportRemainingWarnings, fromExplicitCast: false, diagnosticLocation: operandLocation); // conversion "to" type -> final type // We should only pass fromExplicitCast here. Given the following example: // // class A { public static explicit operator C(A a) => throw null!; } // class C // { // void M() => var c = (C?)new A(); // } // // This final conversion from the method return type "C" to the cast type "C?" is // where we will need to ensure that this is counted as an explicit cast, so that // the resulting operandType is nullable if that was introduced via cast. operandType = ClassifyAndVisitConversion( conversionOpt ?? conversionOperand, targetTypeWithNullability, operandType, useLegacyWarnings, assignmentKind, parameterOpt, reportWarnings: reportRemainingWarnings, fromExplicitCast: conversionOpt?.ExplicitCastInCode ?? false, diagnosticLocation); TrackAnalyzedNullabilityThroughConversionGroup(operandType, conversionOpt, conversionOperand); return operandType; } private void SnapshotWalkerThroughConversionGroup(BoundExpression conversionExpression, BoundExpression convertedNode) { if (_snapshotBuilderOpt is null) { return; } var conversionOpt = conversionExpression as BoundConversion; var conversionGroup = conversionOpt?.ConversionGroupOpt; while (conversionOpt != null && conversionOpt != convertedNode && conversionOpt.Syntax.SpanStart != convertedNode.Syntax.SpanStart) { Debug.Assert(conversionOpt.ConversionGroupOpt == conversionGroup); TakeIncrementalSnapshot(conversionOpt); conversionOpt = conversionOpt.Operand as BoundConversion; } } private void TrackAnalyzedNullabilityThroughConversionGroup(TypeWithState resultType, BoundConversion? conversionOpt, BoundExpression convertedNode) { var visitResult = new VisitResult(resultType, resultType.ToTypeWithAnnotations(compilation)); var conversionGroup = conversionOpt?.ConversionGroupOpt; while (conversionOpt != null && conversionOpt != convertedNode) { Debug.Assert(conversionOpt.ConversionGroupOpt == conversionGroup); visitResult = withType(visitResult, conversionOpt.Type); SetAnalyzedNullability(conversionOpt, visitResult); conversionOpt = conversionOpt.Operand as BoundConversion; } static VisitResult withType(VisitResult visitResult, TypeSymbol newType) => new VisitResult(TypeWithState.Create(newType, visitResult.RValueType.State), TypeWithAnnotations.Create(newType, visitResult.LValueType.NullableAnnotation)); } /// <summary> /// Return the return type for a lifted operator, given the nullability state of its operands. /// </summary> private TypeWithState GetLiftedReturnType(TypeWithAnnotations returnType, NullableFlowState operandState) { bool typeNeedsLifting = returnType.Type.IsNonNullableValueType(); TypeSymbol type = typeNeedsLifting ? MakeNullableOf(returnType) : returnType.Type; NullableFlowState state = returnType.ToTypeWithState().State.Join(operandState); return TypeWithState.Create(type, state); } private static TypeWithState GetNullableUnderlyingTypeIfNecessary(bool isLifted, TypeWithState typeWithState) { if (isLifted) { var type = typeWithState.Type; if (type?.IsNullableType() == true) { return type.GetNullableUnderlyingTypeWithAnnotations().ToTypeWithState(); } } return typeWithState; } private TypeWithState GetLiftedReturnTypeIfNecessary(bool isLifted, TypeWithAnnotations returnType, NullableFlowState operandState) { return isLifted ? GetLiftedReturnType(returnType, operandState) : returnType.ToTypeWithState(); } private TypeSymbol MakeNullableOf(TypeWithAnnotations underlying) { return compilation.GetSpecialType(SpecialType.System_Nullable_T).Construct(ImmutableArray.Create(underlying)); } private TypeWithState ClassifyAndVisitConversion( BoundExpression node, TypeWithAnnotations targetType, TypeWithState operandType, bool useLegacyWarnings, AssignmentKind assignmentKind, ParameterSymbol? parameterOpt, bool reportWarnings, bool fromExplicitCast, Location diagnosticLocation) { Debug.Assert(operandType.Type is object); Debug.Assert(diagnosticLocation != null); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var conversion = _conversions.ClassifyStandardConversion(null, operandType.Type, targetType.Type, ref discardedUseSiteInfo); if (reportWarnings && !conversion.Exists) { if (assignmentKind == AssignmentKind.Argument) { ReportNullabilityMismatchInArgument(diagnosticLocation, operandType.Type, parameterOpt, targetType.Type, forOutput: false); } else { ReportNullabilityMismatchInAssignment(diagnosticLocation, operandType.Type, targetType.Type); } } return VisitConversion( conversionOpt: null, conversionOperand: node, conversion, targetType, operandType, checkConversion: false, fromExplicitCast, useLegacyWarnings: useLegacyWarnings, assignmentKind, parameterOpt, reportTopLevelWarnings: reportWarnings, reportRemainingWarnings: !fromExplicitCast && reportWarnings, diagnosticLocationOpt: diagnosticLocation); } public override BoundNode? VisitDelegateCreationExpression(BoundDelegateCreationExpression node) { Debug.Assert(node.Type.IsDelegateType()); if (node.MethodOpt?.OriginalDefinition is LocalFunctionSymbol localFunc) { VisitLocalFunctionUse(localFunc); } var delegateType = (NamedTypeSymbol)node.Type; switch (node.Argument) { case BoundMethodGroup group: { VisitMethodGroup(group); var method = node.MethodOpt; if (method is object && delegateType.DelegateInvokeMethod is { } delegateInvokeMethod) { method = CheckMethodGroupReceiverNullability(group, delegateInvokeMethod.Parameters, method, node.IsExtensionMethod); if (!group.IsSuppressed) { ReportNullabilityMismatchWithTargetDelegate(group.Syntax.Location, delegateType, delegateInvokeMethod, method, node.IsExtensionMethod); } } SetAnalyzedNullability(group, default); } break; case BoundLambda lambda: { VisitLambda(lambda, delegateType); SetNotNullResult(lambda); if (!lambda.IsSuppressed) { ReportNullabilityMismatchWithTargetDelegate(lambda.Symbol.DiagnosticLocation, delegateType, lambda.UnboundLambda); } } break; case BoundExpression arg when arg.Type is { TypeKind: TypeKind.Delegate } argType: { var argTypeWithAnnotations = TypeWithAnnotations.Create(argType, NullableAnnotation.NotAnnotated); var argState = VisitRvalueWithState(arg); ReportNullableAssignmentIfNecessary(arg, argTypeWithAnnotations, argState, useLegacyWarnings: false); if (!arg.IsSuppressed && delegateType.DelegateInvokeMethod is { } delegateInvokeMethod && argType.DelegateInvokeMethod() is { } argInvokeMethod) { ReportNullabilityMismatchWithTargetDelegate(arg.Syntax.Location, delegateType, delegateInvokeMethod, argInvokeMethod, invokedAsExtensionMethod: false); } // Delegate creation will throw an exception if the argument is null LearnFromNonNullTest(arg, ref State); } break; default: VisitRvalue(node.Argument); break; } SetNotNullResult(node); return null; } public override BoundNode? VisitMethodGroup(BoundMethodGroup node) { Debug.Assert(!IsConditionalState); var receiverOpt = node.ReceiverOpt; if (receiverOpt != null) { VisitRvalue(receiverOpt); // Receiver nullability is checked when applying the method group conversion, // when we have a specific method, to avoid reporting null receiver warnings // for extension method delegates. Here, store the receiver state for that check. SetMethodGroupReceiverNullability(receiverOpt, ResultType); } SetNotNullResult(node); return null; } private bool TryGetMethodGroupReceiverNullability([NotNullWhen(true)] BoundExpression? receiverOpt, out TypeWithState type) { if (receiverOpt != null && _methodGroupReceiverMapOpt != null && _methodGroupReceiverMapOpt.TryGetValue(receiverOpt, out type)) { return true; } else { type = default; return false; } } private void SetMethodGroupReceiverNullability(BoundExpression receiver, TypeWithState type) { _methodGroupReceiverMapOpt ??= PooledDictionary<BoundExpression, TypeWithState>.GetInstance(); _methodGroupReceiverMapOpt[receiver] = type; } private MethodSymbol CheckMethodGroupReceiverNullability(BoundMethodGroup group, ImmutableArray<ParameterSymbol> parameters, MethodSymbol method, bool invokedAsExtensionMethod) { var receiverOpt = group.ReceiverOpt; if (TryGetMethodGroupReceiverNullability(receiverOpt, out TypeWithState receiverType)) { var syntax = group.Syntax; if (!invokedAsExtensionMethod) { method = (MethodSymbol)AsMemberOfType(receiverType.Type, method); } if (method.IsGenericMethod && HasImplicitTypeArguments(group.Syntax)) { var arguments = ArrayBuilder<BoundExpression>.GetInstance(); if (invokedAsExtensionMethod) { arguments.Add(CreatePlaceholderIfNecessary(receiverOpt, receiverType.ToTypeWithAnnotations(compilation))); } // Create placeholders for the arguments. (See Conversions.GetDelegateArguments() // which is used for that purpose in initial binding.) foreach (var parameter in parameters) { var parameterType = parameter.TypeWithAnnotations; arguments.Add(new BoundExpressionWithNullability(syntax, new BoundParameter(syntax, parameter), parameterType.NullableAnnotation, parameterType.Type)); } Debug.Assert(_binder is object); method = InferMethodTypeArguments(method, arguments.ToImmutableAndFree(), argumentRefKindsOpt: default, argsToParamsOpt: default, expanded: false); } if (invokedAsExtensionMethod) { CheckExtensionMethodThisNullability(receiverOpt, Conversion.Identity, method.Parameters[0], receiverType); } else { CheckPossibleNullReceiver(receiverOpt, receiverType, checkNullableValueType: false); } if (ConstraintsHelper.RequiresChecking(method)) { CheckMethodConstraints(syntax, method); } } return method; } public override BoundNode? VisitLambda(BoundLambda node) { // Note: actual lambda analysis happens after this call (primarily in VisitConversion). // Here we just indicate that a lambda expression produces a non-null value. SetNotNullResult(node); return null; } private void VisitLambda(BoundLambda node, NamedTypeSymbol? delegateTypeOpt, Optional<LocalState> initialState = default) { Debug.Assert(delegateTypeOpt?.IsDelegateType() != false); var delegateInvokeMethod = delegateTypeOpt?.DelegateInvokeMethod; UseDelegateInvokeParameterAndReturnTypes(node, delegateInvokeMethod, out bool useDelegateInvokeParameterTypes, out bool useDelegateInvokeReturnType); if (useDelegateInvokeParameterTypes && _snapshotBuilderOpt is object) { SetUpdatedSymbol(node, node.Symbol, delegateTypeOpt!); } AnalyzeLocalFunctionOrLambda( node, node.Symbol, initialState.HasValue ? initialState.Value : State.Clone(), delegateInvokeMethod, useDelegateInvokeParameterTypes, useDelegateInvokeReturnType); } private static void UseDelegateInvokeParameterAndReturnTypes(BoundLambda lambda, MethodSymbol? delegateInvokeMethod, out bool useDelegateInvokeParameterTypes, out bool useDelegateInvokeReturnType) { if (delegateInvokeMethod is null) { useDelegateInvokeParameterTypes = false; useDelegateInvokeReturnType = false; } else { var unboundLambda = lambda.UnboundLambda; useDelegateInvokeParameterTypes = !unboundLambda.HasExplicitlyTypedParameterList; useDelegateInvokeReturnType = !unboundLambda.HasExplicitReturnType(out _, out _); } } public override BoundNode? VisitUnboundLambda(UnboundLambda node) { // The presence of this node suggests an error was detected in an earlier phase. // Analyze the body to report any additional warnings. var lambda = node.BindForErrorRecovery(); VisitLambda(lambda, delegateTypeOpt: null); SetNotNullResult(node); return null; } public override BoundNode? VisitThisReference(BoundThisReference node) { VisitThisOrBaseReference(node); return null; } private void VisitThisOrBaseReference(BoundExpression node) { var rvalueResult = TypeWithState.Create(node.Type, NullableFlowState.NotNull); var lvalueResult = TypeWithAnnotations.Create(node.Type, NullableAnnotation.NotAnnotated); SetResult(node, rvalueResult, lvalueResult); } public override BoundNode? VisitParameter(BoundParameter node) { var parameter = node.ParameterSymbol; int slot = GetOrCreateSlot(parameter); var parameterType = GetDeclaredParameterResult(parameter); var typeWithState = GetParameterState(parameterType, parameter.FlowAnalysisAnnotations); SetResult(node, GetAdjustedResult(typeWithState, slot), parameterType); return null; } public override BoundNode? VisitAssignmentOperator(BoundAssignmentOperator node) { Debug.Assert(!IsConditionalState); var left = node.Left; switch (left) { // when binding initializers, we treat assignments to auto-properties or field-like events as direct assignments to the underlying field. // in order to track member state based on these initializers, we need to see the assignment in terms of the associated member case BoundFieldAccess { ExpressionSymbol: FieldSymbol { AssociatedSymbol: PropertySymbol autoProperty } } fieldAccess: left = new BoundPropertyAccess(fieldAccess.Syntax, fieldAccess.ReceiverOpt, autoProperty, LookupResultKind.Viable, autoProperty.Type, fieldAccess.HasErrors); break; case BoundFieldAccess { ExpressionSymbol: FieldSymbol { AssociatedSymbol: EventSymbol @event } } fieldAccess: left = new BoundEventAccess(fieldAccess.Syntax, fieldAccess.ReceiverOpt, @event, isUsableAsField: true, LookupResultKind.Viable, @event.Type, fieldAccess.HasErrors); break; } var right = node.Right; VisitLValue(left); // we may enter a conditional state for error scenarios on the LHS. Unsplit(); FlowAnalysisAnnotations leftAnnotations = GetLValueAnnotations(left); TypeWithAnnotations declaredType = LvalueResultType; TypeWithAnnotations leftLValueType = ApplyLValueAnnotations(declaredType, leftAnnotations); if (left.Kind == BoundKind.EventAccess && ((BoundEventAccess)left).EventSymbol.IsWindowsRuntimeEvent) { // Event assignment is a call to an Add method. (Note that assignment // of non-field-like events uses BoundEventAssignmentOperator // rather than BoundAssignmentOperator.) VisitRvalue(right); SetNotNullResult(node); } else { TypeWithState rightState; if (!node.IsRef) { var discarded = left is BoundDiscardExpression; rightState = VisitOptionalImplicitConversion(right, targetTypeOpt: discarded ? default : leftLValueType, UseLegacyWarnings(left, leftLValueType), trackMembers: true, AssignmentKind.Assignment); } else { rightState = VisitRefExpression(right, leftLValueType); } // If the LHS has annotations, we perform an additional check for nullable value types CheckDisallowedNullAssignment(rightState, leftAnnotations, right.Syntax.Location); AdjustSetValue(left, ref rightState); TrackNullableStateForAssignment(right, leftLValueType, MakeSlot(left), rightState, MakeSlot(right)); if (left is BoundDiscardExpression) { var lvalueType = rightState.ToTypeWithAnnotations(compilation); SetResult(left, rightState, lvalueType, isLvalue: true); SetResult(node, rightState, lvalueType); } else { SetResult(node, TypeWithState.Create(leftLValueType.Type, rightState.State), leftLValueType); } } return null; } private bool IsPropertyOutputMoreStrictThanInput(PropertySymbol property) { var type = property.TypeWithAnnotations; var annotations = IsAnalyzingAttribute ? FlowAnalysisAnnotations.None : property.GetFlowAnalysisAnnotations(); var lValueType = ApplyLValueAnnotations(type, annotations); if (lValueType.NullableAnnotation.IsOblivious() || !lValueType.CanBeAssignedNull) { return false; } var rValueType = ApplyUnconditionalAnnotations(type.ToTypeWithState(), annotations); return rValueType.IsNotNull; } /// <summary> /// When the allowed output of a property/indexer is not-null but the allowed input is maybe-null, we store a not-null value instead. /// This way, assignment of a legal input value results in a legal output value. /// This adjustment doesn't apply to oblivious properties/indexers. /// </summary> private void AdjustSetValue(BoundExpression left, ref TypeWithState rightState) { var property = left switch { BoundPropertyAccess propAccess => propAccess.PropertySymbol, BoundIndexerAccess indexerAccess => indexerAccess.Indexer, _ => null }; if (property is not null && IsPropertyOutputMoreStrictThanInput(property)) { rightState = rightState.WithNotNullState(); } } private FlowAnalysisAnnotations GetLValueAnnotations(BoundExpression expr) { // Annotations are ignored when binding an attribute to avoid cycles. (Members used // in attributes are error scenarios, so missing warnings should not be important.) if (IsAnalyzingAttribute) { return FlowAnalysisAnnotations.None; } var annotations = expr switch { BoundPropertyAccess property => property.PropertySymbol.GetFlowAnalysisAnnotations(), BoundIndexerAccess indexer => indexer.Indexer.GetFlowAnalysisAnnotations(), BoundFieldAccess field => getFieldAnnotations(field.FieldSymbol), BoundObjectInitializerMember { MemberSymbol: PropertySymbol prop } => prop.GetFlowAnalysisAnnotations(), BoundObjectInitializerMember { MemberSymbol: FieldSymbol field } => getFieldAnnotations(field), BoundParameter { ParameterSymbol: ParameterSymbol parameter } => ToInwardAnnotations(GetParameterAnnotations(parameter) & ~FlowAnalysisAnnotations.NotNull), // NotNull is enforced upon method exit _ => FlowAnalysisAnnotations.None }; return annotations & (FlowAnalysisAnnotations.DisallowNull | FlowAnalysisAnnotations.AllowNull); static FlowAnalysisAnnotations getFieldAnnotations(FieldSymbol field) { return field.AssociatedSymbol is PropertySymbol property ? property.GetFlowAnalysisAnnotations() : field.FlowAnalysisAnnotations; } } private static FlowAnalysisAnnotations ToInwardAnnotations(FlowAnalysisAnnotations outwardAnnotations) { var annotations = FlowAnalysisAnnotations.None; if ((outwardAnnotations & FlowAnalysisAnnotations.MaybeNull) != 0) { // MaybeNull and MaybeNullWhen count as MaybeNull annotations |= FlowAnalysisAnnotations.AllowNull; } if ((outwardAnnotations & FlowAnalysisAnnotations.NotNull) == FlowAnalysisAnnotations.NotNull) { // NotNullWhenTrue and NotNullWhenFalse don't count on their own. Only NotNull (ie. both flags) matters. annotations |= FlowAnalysisAnnotations.DisallowNull; } return annotations; } private static bool UseLegacyWarnings(BoundExpression expr, TypeWithAnnotations exprType) { switch (expr.Kind) { case BoundKind.Local: return expr.GetRefKind() == RefKind.None; case BoundKind.Parameter: RefKind kind = ((BoundParameter)expr).ParameterSymbol.RefKind; return kind == RefKind.None; default: return false; } } public override BoundNode? VisitDeconstructionAssignmentOperator(BoundDeconstructionAssignmentOperator node) { return VisitDeconstructionAssignmentOperator(node, rightResultOpt: null); } private BoundNode? VisitDeconstructionAssignmentOperator(BoundDeconstructionAssignmentOperator node, TypeWithState? rightResultOpt) { var previousDisableNullabilityAnalysis = _disableNullabilityAnalysis; _disableNullabilityAnalysis = true; var left = node.Left; var right = node.Right; var variables = GetDeconstructionAssignmentVariables(left); if (node.HasErrors) { // In the case of errors, simply visit the right as an r-value to update // any nullability state even though deconstruction is skipped. VisitRvalue(right.Operand); } else { VisitDeconstructionArguments(variables, right.Conversion, right.Operand, rightResultOpt); } variables.FreeAll(v => v.NestedVariables); // https://github.com/dotnet/roslyn/issues/33011: Result type should be inferred and the constraints should // be re-verified. Even though the standard tuple type has no constraints we support that scenario. Constraints_78 // has a test for this case that should start failing when this is fixed. SetNotNullResult(node); _disableNullabilityAnalysis = previousDisableNullabilityAnalysis; return null; } private void VisitDeconstructionArguments(ArrayBuilder<DeconstructionVariable> variables, Conversion conversion, BoundExpression right, TypeWithState? rightResultOpt = null) { Debug.Assert(conversion.Kind == ConversionKind.Deconstruction); if (!conversion.DeconstructionInfo.IsDefault) { VisitDeconstructMethodArguments(variables, conversion, right, rightResultOpt); } else { VisitTupleDeconstructionArguments(variables, conversion.UnderlyingConversions, right); } } private void VisitDeconstructMethodArguments(ArrayBuilder<DeconstructionVariable> variables, Conversion conversion, BoundExpression right, TypeWithState? rightResultOpt) { VisitRvalue(right); // If we were passed an explicit right result, use that rather than the visited result if (rightResultOpt.HasValue) { SetResultType(right, rightResultOpt.Value); } var rightResult = ResultType; var invocation = conversion.DeconstructionInfo.Invocation as BoundCall; var deconstructMethod = invocation?.Method; if (deconstructMethod is object) { Debug.Assert(invocation is object); Debug.Assert(rightResult.Type is object); int n = variables.Count; if (!invocation.InvokedAsExtensionMethod) { _ = CheckPossibleNullReceiver(right); // update the deconstruct method with any inferred type parameters of the containing type if (deconstructMethod.OriginalDefinition != deconstructMethod) { deconstructMethod = deconstructMethod.OriginalDefinition.AsMember((NamedTypeSymbol)rightResult.Type); } } else { if (deconstructMethod.IsGenericMethod) { // re-infer the deconstruct parameters based on the 'this' parameter ArrayBuilder<BoundExpression> placeholderArgs = ArrayBuilder<BoundExpression>.GetInstance(n + 1); placeholderArgs.Add(CreatePlaceholderIfNecessary(right, rightResult.ToTypeWithAnnotations(compilation))); for (int i = 0; i < n; i++) { placeholderArgs.Add(new BoundExpressionWithNullability(variables[i].Expression.Syntax, variables[i].Expression, NullableAnnotation.Oblivious, conversion.DeconstructionInfo.OutputPlaceholders[i].Type)); } deconstructMethod = InferMethodTypeArguments(deconstructMethod, placeholderArgs.ToImmutableAndFree(), invocation.ArgumentRefKindsOpt, invocation.ArgsToParamsOpt, invocation.Expanded); // check the constraints remain valid with the re-inferred parameter types if (ConstraintsHelper.RequiresChecking(deconstructMethod)) { CheckMethodConstraints(invocation.Syntax, deconstructMethod); } } } var parameters = deconstructMethod.Parameters; int offset = invocation.InvokedAsExtensionMethod ? 1 : 0; Debug.Assert(parameters.Length - offset == n); if (invocation.InvokedAsExtensionMethod) { // Check nullability for `this` parameter var argConversion = RemoveConversion(invocation.Arguments[0], includeExplicitConversions: false).conversion; CheckExtensionMethodThisNullability(right, argConversion, deconstructMethod.Parameters[0], rightResult); } for (int i = 0; i < n; i++) { var variable = variables[i]; var parameter = parameters[i + offset]; var underlyingConversion = conversion.UnderlyingConversions[i]; var nestedVariables = variable.NestedVariables; if (nestedVariables != null) { var nestedRight = CreatePlaceholderIfNecessary(invocation.Arguments[i + offset], parameter.TypeWithAnnotations); VisitDeconstructionArguments(nestedVariables, underlyingConversion, right: nestedRight); } else { VisitArgumentConversionAndInboundAssignmentsAndPreConditions(conversionOpt: null, variable.Expression, underlyingConversion, parameter.RefKind, parameter, parameter.TypeWithAnnotations, GetParameterAnnotations(parameter), new VisitArgumentResult(new VisitResult(variable.Type.ToTypeWithState(), variable.Type), stateForLambda: default), extensionMethodThisArgument: false); } } for (int i = 0; i < n; i++) { var variable = variables[i]; var parameter = parameters[i + offset]; var nestedVariables = variable.NestedVariables; if (nestedVariables == null) { VisitArgumentOutboundAssignmentsAndPostConditions( variable.Expression, parameter.RefKind, parameter, parameter.TypeWithAnnotations, GetRValueAnnotations(parameter), new VisitArgumentResult(new VisitResult(variable.Type.ToTypeWithState(), variable.Type), stateForLambda: default), notNullParametersOpt: null, compareExchangeInfoOpt: default); } } } } private void VisitTupleDeconstructionArguments(ArrayBuilder<DeconstructionVariable> variables, ImmutableArray<Conversion> conversions, BoundExpression right) { int n = variables.Count; var rightParts = GetDeconstructionRightParts(right); Debug.Assert(rightParts.Length == n); for (int i = 0; i < n; i++) { var variable = variables[i]; var underlyingConversion = conversions[i]; var rightPart = rightParts[i]; var nestedVariables = variable.NestedVariables; if (nestedVariables != null) { VisitDeconstructionArguments(nestedVariables, underlyingConversion, rightPart); } else { var lvalueType = variable.Type; var leftAnnotations = GetLValueAnnotations(variable.Expression); lvalueType = ApplyLValueAnnotations(lvalueType, leftAnnotations); TypeWithState operandType; TypeWithState valueType; int valueSlot; if (underlyingConversion.IsIdentity) { if (variable.Expression is BoundLocal { DeclarationKind: BoundLocalDeclarationKind.WithInferredType } local) { // when the LHS is a var declaration, we can just visit the right part to infer the type valueType = operandType = VisitRvalueWithState(rightPart); _variables.SetType(local.LocalSymbol, operandType.ToAnnotatedTypeWithAnnotations(compilation)); } else { operandType = default; valueType = VisitOptionalImplicitConversion(rightPart, lvalueType, useLegacyWarnings: true, trackMembers: true, AssignmentKind.Assignment); } valueSlot = MakeSlot(rightPart); } else { operandType = VisitRvalueWithState(rightPart); valueType = VisitConversion( conversionOpt: null, rightPart, underlyingConversion, lvalueType, operandType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: true, AssignmentKind.Assignment, reportTopLevelWarnings: true, reportRemainingWarnings: true, trackMembers: false); valueSlot = -1; } // If the LHS has annotations, we perform an additional check for nullable value types CheckDisallowedNullAssignment(valueType, leftAnnotations, right.Syntax.Location); int targetSlot = MakeSlot(variable.Expression); AdjustSetValue(variable.Expression, ref valueType); TrackNullableStateForAssignment(rightPart, lvalueType, targetSlot, valueType, valueSlot); // Conversion of T to Nullable<T> is equivalent to new Nullable<T>(t). if (targetSlot > 0 && underlyingConversion.Kind == ConversionKind.ImplicitNullable && AreNullableAndUnderlyingTypes(lvalueType.Type, operandType.Type, out TypeWithAnnotations underlyingType)) { valueSlot = MakeSlot(rightPart); if (valueSlot > 0) { var valueBeforeNullableWrapping = TypeWithState.Create(underlyingType.Type, NullableFlowState.NotNull); TrackNullableStateOfNullableValue(targetSlot, lvalueType.Type, rightPart, valueBeforeNullableWrapping, valueSlot); } } } } } private readonly struct DeconstructionVariable { internal readonly BoundExpression Expression; internal readonly TypeWithAnnotations Type; internal readonly ArrayBuilder<DeconstructionVariable>? NestedVariables; internal DeconstructionVariable(BoundExpression expression, TypeWithAnnotations type) { Expression = expression; Type = type; NestedVariables = null; } internal DeconstructionVariable(BoundExpression expression, ArrayBuilder<DeconstructionVariable> nestedVariables) { Expression = expression; Type = default; NestedVariables = nestedVariables; } } private ArrayBuilder<DeconstructionVariable> GetDeconstructionAssignmentVariables(BoundTupleExpression tuple) { var arguments = tuple.Arguments; var builder = ArrayBuilder<DeconstructionVariable>.GetInstance(arguments.Length); foreach (var argument in arguments) { builder.Add(getDeconstructionAssignmentVariable(argument)); } return builder; DeconstructionVariable getDeconstructionAssignmentVariable(BoundExpression expr) { switch (expr.Kind) { case BoundKind.TupleLiteral: case BoundKind.ConvertedTupleLiteral: return new DeconstructionVariable(expr, GetDeconstructionAssignmentVariables((BoundTupleExpression)expr)); default: VisitLValue(expr); return new DeconstructionVariable(expr, LvalueResultType); } } } /// <summary> /// Return the sub-expressions for the righthand side of a deconstruction /// assignment. cf. LocalRewriter.GetRightParts. /// </summary> private ImmutableArray<BoundExpression> GetDeconstructionRightParts(BoundExpression expr) { switch (expr.Kind) { case BoundKind.TupleLiteral: case BoundKind.ConvertedTupleLiteral: return ((BoundTupleExpression)expr).Arguments; case BoundKind.Conversion: { var conv = (BoundConversion)expr; switch (conv.ConversionKind) { case ConversionKind.Identity: case ConversionKind.ImplicitTupleLiteral: return GetDeconstructionRightParts(conv.Operand); } } break; } if (expr.Type is NamedTypeSymbol { IsTupleType: true } tupleType) { // https://github.com/dotnet/roslyn/issues/33011: Should include conversion.UnderlyingConversions[i]. // For instance, Boxing conversions (see Deconstruction_ImplicitBoxingConversion_02) and // ImplicitNullable conversions (see Deconstruction_ImplicitNullableConversion_02). var fields = tupleType.TupleElements; return fields.SelectAsArray((f, e) => (BoundExpression)new BoundFieldAccess(e.Syntax, e, f, constantValueOpt: null), expr); } throw ExceptionUtilities.Unreachable; } public override BoundNode? VisitIncrementOperator(BoundIncrementOperator node) { Debug.Assert(!IsConditionalState); var operandType = VisitRvalueWithState(node.Operand); var operandLvalue = LvalueResultType; bool setResult = false; if (this.State.Reachable) { // https://github.com/dotnet/roslyn/issues/29961 Update increment method based on operand type. MethodSymbol? incrementOperator = (node.OperatorKind.IsUserDefined() && node.MethodOpt?.ParameterCount == 1) ? node.MethodOpt : null; TypeWithAnnotations targetTypeOfOperandConversion; AssignmentKind assignmentKind = AssignmentKind.Assignment; ParameterSymbol? parameter = null; // Analyze operator call properly (honoring [Disallow|Allow|Maybe|NotNull] attribute annotations) https://github.com/dotnet/roslyn/issues/32671 // https://github.com/dotnet/roslyn/issues/29961 Update conversion method based on operand type. if (node.OperandConversion.IsUserDefined && node.OperandConversion.Method?.ParameterCount == 1) { targetTypeOfOperandConversion = node.OperandConversion.Method.ReturnTypeWithAnnotations; } else if (incrementOperator is object) { targetTypeOfOperandConversion = incrementOperator.Parameters[0].TypeWithAnnotations; assignmentKind = AssignmentKind.Argument; parameter = incrementOperator.Parameters[0]; } else { // Either a built-in increment, or an error case. targetTypeOfOperandConversion = default; } TypeWithState resultOfOperandConversionType; if (targetTypeOfOperandConversion.HasType) { // https://github.com/dotnet/roslyn/issues/29961 Should something special be done for targetTypeOfOperandConversion for lifted case? resultOfOperandConversionType = VisitConversion( conversionOpt: null, node.Operand, node.OperandConversion, targetTypeOfOperandConversion, operandType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, assignmentKind, parameter, reportTopLevelWarnings: true, reportRemainingWarnings: true); } else { resultOfOperandConversionType = operandType; } TypeWithState resultOfIncrementType; if (incrementOperator is null) { resultOfIncrementType = resultOfOperandConversionType; } else { resultOfIncrementType = incrementOperator.ReturnTypeWithAnnotations.ToTypeWithState(); } var operandTypeWithAnnotations = operandType.ToTypeWithAnnotations(compilation); resultOfIncrementType = VisitConversion( conversionOpt: null, node, node.ResultConversion, operandTypeWithAnnotations, resultOfIncrementType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Assignment); // https://github.com/dotnet/roslyn/issues/29961 Check node.Type.IsErrorType() instead? if (!node.HasErrors) { var op = node.OperatorKind.Operator(); TypeWithState resultType = (op == UnaryOperatorKind.PrefixIncrement || op == UnaryOperatorKind.PrefixDecrement) ? resultOfIncrementType : operandType; SetResultType(node, resultType); setResult = true; TrackNullableStateForAssignment(node, targetType: operandLvalue, targetSlot: MakeSlot(node.Operand), valueType: resultOfIncrementType); } } if (!setResult) { SetNotNullResult(node); } return null; } public override BoundNode? VisitCompoundAssignmentOperator(BoundCompoundAssignmentOperator node) { var left = node.Left; var right = node.Right; Visit(left); TypeWithAnnotations declaredType = LvalueResultType; TypeWithAnnotations leftLValueType = declaredType; TypeWithState leftResultType = ResultType; Debug.Assert(!IsConditionalState); TypeWithState leftOnRightType = GetAdjustedResult(leftResultType, MakeSlot(node.Left)); // https://github.com/dotnet/roslyn/issues/29962 Update operator based on inferred argument types. if ((object)node.Operator.LeftType != null) { // https://github.com/dotnet/roslyn/issues/29962 Ignoring top-level nullability of operator left parameter. leftOnRightType = VisitConversion( conversionOpt: null, node.Left, node.LeftConversion, TypeWithAnnotations.Create(node.Operator.LeftType), leftOnRightType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Assignment, reportTopLevelWarnings: false, reportRemainingWarnings: true); } else { leftOnRightType = default; } TypeWithState resultType; TypeWithState rightType = VisitRvalueWithState(right); if ((object)node.Operator.ReturnType != null) { if (node.Operator.Kind.IsUserDefined() && (object)node.Operator.Method != null && node.Operator.Method.ParameterCount == 2) { MethodSymbol method = node.Operator.Method; VisitArguments(node, ImmutableArray.Create(node.Left, right), method.ParameterRefKinds, method.Parameters, argsToParamsOpt: default, defaultArguments: default, expanded: true, invokedAsExtensionMethod: false, method); } resultType = InferResultNullability(node.Operator.Kind, node.Operator.Method, node.Operator.ReturnType, leftOnRightType, rightType); FlowAnalysisAnnotations leftAnnotations = GetLValueAnnotations(node.Left); leftLValueType = ApplyLValueAnnotations(leftLValueType, leftAnnotations); resultType = VisitConversion( conversionOpt: null, node, node.FinalConversion, leftLValueType, resultType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Assignment); // If the LHS has annotations, we perform an additional check for nullable value types CheckDisallowedNullAssignment(resultType, leftAnnotations, node.Syntax.Location); } else { resultType = TypeWithState.Create(node.Type, NullableFlowState.NotNull); } AdjustSetValue(left, ref resultType); TrackNullableStateForAssignment(node, leftLValueType, MakeSlot(node.Left), resultType); SetResultType(node, resultType); return null; } public override BoundNode? VisitFixedLocalCollectionInitializer(BoundFixedLocalCollectionInitializer node) { var initializer = node.Expression; if (initializer.Kind == BoundKind.AddressOfOperator) { initializer = ((BoundAddressOfOperator)initializer).Operand; } VisitRvalue(initializer); if (node.Expression.Kind == BoundKind.AddressOfOperator) { SetResultType(node.Expression, TypeWithState.Create(node.Expression.Type, ResultType.State)); } SetNotNullResult(node); return null; } public override BoundNode? VisitAddressOfOperator(BoundAddressOfOperator node) { Visit(node.Operand); SetNotNullResult(node); return null; } private void ReportArgumentWarnings(BoundExpression argument, TypeWithState argumentType, ParameterSymbol parameter) { var paramType = parameter.TypeWithAnnotations; ReportNullableAssignmentIfNecessary(argument, paramType, argumentType, useLegacyWarnings: false, AssignmentKind.Argument, parameterOpt: parameter); if (argumentType.Type is { } argType && IsNullabilityMismatch(paramType.Type, argType)) { ReportNullabilityMismatchInArgument(argument.Syntax, argType, parameter, paramType.Type, forOutput: false); } } private void ReportNullabilityMismatchInRefArgument(BoundExpression argument, TypeSymbol argumentType, ParameterSymbol parameter, TypeSymbol parameterType) { ReportDiagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, argument.Syntax, argumentType, parameterType, GetParameterAsDiagnosticArgument(parameter), GetContainingSymbolAsDiagnosticArgument(parameter)); } /// <summary> /// Report warning passing argument where nested nullability does not match /// parameter (e.g.: calling `void F(object[] o)` with `F(new[] { maybeNull })`). /// </summary> private void ReportNullabilityMismatchInArgument(SyntaxNode argument, TypeSymbol argumentType, ParameterSymbol parameter, TypeSymbol parameterType, bool forOutput) { ReportNullabilityMismatchInArgument(argument.GetLocation(), argumentType, parameter, parameterType, forOutput); } private void ReportNullabilityMismatchInArgument(Location argumentLocation, TypeSymbol argumentType, ParameterSymbol? parameterOpt, TypeSymbol parameterType, bool forOutput) { ReportDiagnostic(forOutput ? ErrorCode.WRN_NullabilityMismatchInArgumentForOutput : ErrorCode.WRN_NullabilityMismatchInArgument, argumentLocation, argumentType, parameterOpt?.Type.IsNonNullableValueType() == true && parameterType.IsNullableType() ? parameterOpt.Type : parameterType, // Compensate for operator lifting GetParameterAsDiagnosticArgument(parameterOpt), GetContainingSymbolAsDiagnosticArgument(parameterOpt)); } private TypeWithAnnotations GetDeclaredLocalResult(LocalSymbol local) { return _variables.TryGetType(local, out TypeWithAnnotations type) ? type : local.TypeWithAnnotations; } private TypeWithAnnotations GetDeclaredParameterResult(ParameterSymbol parameter) { return _variables.TryGetType(parameter, out TypeWithAnnotations type) ? type : parameter.TypeWithAnnotations; } public override BoundNode? VisitBaseReference(BoundBaseReference node) { VisitThisOrBaseReference(node); return null; } public override BoundNode? VisitFieldAccess(BoundFieldAccess node) { var updatedSymbol = VisitMemberAccess(node, node.ReceiverOpt, node.FieldSymbol); SplitIfBooleanConstant(node); SetUpdatedSymbol(node, node.FieldSymbol, updatedSymbol); return null; } public override BoundNode? VisitPropertyAccess(BoundPropertyAccess node) { var property = node.PropertySymbol; var updatedMember = VisitMemberAccess(node, node.ReceiverOpt, property); if (!IsAnalyzingAttribute) { if (_expressionIsRead) { ApplyMemberPostConditions(node.ReceiverOpt, property.GetMethod); } else { ApplyMemberPostConditions(node.ReceiverOpt, property.SetMethod); } } SetUpdatedSymbol(node, property, updatedMember); return null; } public override BoundNode? VisitIndexerAccess(BoundIndexerAccess node) { var receiverOpt = node.ReceiverOpt; var receiverType = VisitRvalueWithState(receiverOpt).Type; // https://github.com/dotnet/roslyn/issues/30598: Mark receiver as not null // after indices have been visited, and only if the receiver has not changed. _ = CheckPossibleNullReceiver(receiverOpt); var indexer = node.Indexer; if (receiverType is object) { // Update indexer based on inferred receiver type. indexer = (PropertySymbol)AsMemberOfType(receiverType, indexer); } VisitArguments(node, node.Arguments, node.ArgumentRefKindsOpt, indexer, node.ArgsToParamsOpt, node.DefaultArguments, node.Expanded); var resultType = ApplyUnconditionalAnnotations(indexer.TypeWithAnnotations.ToTypeWithState(), GetRValueAnnotations(indexer)); SetResult(node, resultType, indexer.TypeWithAnnotations); SetUpdatedSymbol(node, node.Indexer, indexer); return null; } public override BoundNode? VisitIndexOrRangePatternIndexerAccess(BoundIndexOrRangePatternIndexerAccess node) { BoundExpression receiver = node.Receiver; var receiverType = VisitRvalueWithState(receiver).Type; // https://github.com/dotnet/roslyn/issues/30598: Mark receiver as not null // after indices have been visited, and only if the receiver has not changed. _ = CheckPossibleNullReceiver(receiver); VisitRvalue(node.Argument); var patternSymbol = node.PatternSymbol; if (receiverType is object) { patternSymbol = AsMemberOfType(receiverType, patternSymbol); } SetLvalueResultType(node, patternSymbol.GetTypeOrReturnType()); SetUpdatedSymbol(node, node.PatternSymbol, patternSymbol); return null; } public override BoundNode? VisitEventAccess(BoundEventAccess node) { var updatedSymbol = VisitMemberAccess(node, node.ReceiverOpt, node.EventSymbol); SetUpdatedSymbol(node, node.EventSymbol, updatedSymbol); return null; } private Symbol VisitMemberAccess(BoundExpression node, BoundExpression? receiverOpt, Symbol member) { Debug.Assert(!IsConditionalState); var receiverType = (receiverOpt != null) ? VisitRvalueWithState(receiverOpt) : default; SpecialMember? nullableOfTMember = null; if (member.RequiresInstanceReceiver()) { member = AsMemberOfType(receiverType.Type, member); nullableOfTMember = GetNullableOfTMember(member); // https://github.com/dotnet/roslyn/issues/30598: For l-values, mark receiver as not null // after RHS has been visited, and only if the receiver has not changed. bool skipReceiverNullCheck = nullableOfTMember != SpecialMember.System_Nullable_T_get_Value; _ = CheckPossibleNullReceiver(receiverOpt, checkNullableValueType: !skipReceiverNullCheck); } var type = member.GetTypeOrReturnType(); var memberAnnotations = GetRValueAnnotations(member); var resultType = ApplyUnconditionalAnnotations(type.ToTypeWithState(), memberAnnotations); // We are supposed to track information for the node. Use whatever we managed to // accumulate so far. if (PossiblyNullableType(resultType.Type)) { int slot = MakeMemberSlot(receiverOpt, member); if (this.State.HasValue(slot)) { var state = this.State[slot]; resultType = TypeWithState.Create(resultType.Type, state); } } Debug.Assert(!IsConditionalState); if (nullableOfTMember == SpecialMember.System_Nullable_T_get_HasValue && !(receiverOpt is null)) { int containingSlot = MakeSlot(receiverOpt); if (containingSlot > 0) { Split(); this.StateWhenTrue[containingSlot] = NullableFlowState.NotNull; } } SetResult(node, resultType, type); return member; } private SpecialMember? GetNullableOfTMember(Symbol member) { if (member.Kind == SymbolKind.Property) { var getMethod = ((PropertySymbol)member.OriginalDefinition).GetMethod; if ((object)getMethod != null && getMethod.ContainingType.SpecialType == SpecialType.System_Nullable_T) { if (getMethod == compilation.GetSpecialTypeMember(SpecialMember.System_Nullable_T_get_Value)) { return SpecialMember.System_Nullable_T_get_Value; } if (getMethod == compilation.GetSpecialTypeMember(SpecialMember.System_Nullable_T_get_HasValue)) { return SpecialMember.System_Nullable_T_get_HasValue; } } } return null; } private int GetNullableOfTValueSlot(TypeSymbol containingType, int containingSlot, out Symbol? valueProperty, bool forceSlotEvenIfEmpty = false) { Debug.Assert(containingType.IsNullableType()); Debug.Assert(TypeSymbol.Equals(NominalSlotType(containingSlot), containingType, TypeCompareKind.ConsiderEverything2)); var getValue = (MethodSymbol)compilation.GetSpecialTypeMember(SpecialMember.System_Nullable_T_get_Value); valueProperty = getValue?.AsMember((NamedTypeSymbol)containingType)?.AssociatedSymbol; return (valueProperty is null) ? -1 : GetOrCreateSlot(valueProperty, containingSlot, forceSlotEvenIfEmpty: forceSlotEvenIfEmpty); } protected override void VisitForEachExpression(BoundForEachStatement node) { if (node.Expression.Kind != BoundKind.Conversion) { // If we're in this scenario, there was a binding error, and we should suppress any further warnings. Debug.Assert(node.HasErrors); VisitRvalue(node.Expression); return; } var (expr, conversion) = RemoveConversion(node.Expression, includeExplicitConversions: false); SnapshotWalkerThroughConversionGroup(node.Expression, expr); // There are 7 ways that a foreach can be created: // 1. The collection type is an array type. For this, initial binding will generate an implicit reference conversion to // IEnumerable, and we do not need to do any reinferring of enumerators here. // 2. The collection type is dynamic. For this we do the same as 1. // 3. The collection type implements the GetEnumerator pattern. For this, there is an identity conversion. Because // this identity conversion uses nested types from initial binding, we cannot trust them and must instead use // the type of the expression returned from VisitResult to reinfer the enumerator information. // 4. The collection type implements IEnumerable<T>. Only a few cases can hit this without being caught by number 3, // such as a type with a private implementation of IEnumerable<T>, or a type parameter constrained to that type. // In these cases, there will be an implicit conversion to IEnumerable<T>, but this will use types from // initial binding. For this scenario, we need to look through the list of implemented interfaces on the type and // find the version of IEnumerable<T> that it has after nullable analysis, as type substitution could have changed // nested nullability of type parameters. See ForEach_22 for a concrete example of this. // 5. The collection type implements IEnumerable (non-generic). Because this version isn't generic, we don't need to // do any reinference, and the existing conversion can stand as is. // 6. The target framework's System.String doesn't implement IEnumerable. This is a compat case: System.String normally // does implement IEnumerable, but there are certain target frameworks where this isn't the case. The compiler will // still emit code for foreach in these scenarios. // 7. The collection type implements the GetEnumerator pattern via an extension GetEnumerator. For this, there will be // conversion to the parameter of the extension method. // 8. Some binding error occurred, and some other error has already been reported. Usually this doesn't have any kind // of conversion on top, but if there was an explicit conversion in code then we could get past the initial check // for a BoundConversion node. var resultTypeWithState = VisitRvalueWithState(expr); var resultType = resultTypeWithState.Type; Debug.Assert(resultType is object); SetAnalyzedNullability(expr, _visitResult); TypeWithAnnotations targetTypeWithAnnotations; MethodSymbol? reinferredGetEnumeratorMethod = null; if (node.EnumeratorInfoOpt?.GetEnumeratorInfo is { Method: { IsExtensionMethod: true, Parameters: var parameters } } enumeratorMethodInfo) { // this is case 7 // We do not need to do this same analysis for non-extension methods because they do not have generic parameters that // can be inferred from usage like extension methods can. We don't warn about default arguments at the call site, so // there's nothing that can be learned from the non-extension case. var (method, results, _) = VisitArguments( node, enumeratorMethodInfo.Arguments, refKindsOpt: default, parameters, argsToParamsOpt: enumeratorMethodInfo.ArgsToParamsOpt, defaultArguments: enumeratorMethodInfo.DefaultArguments, expanded: false, invokedAsExtensionMethod: true, enumeratorMethodInfo.Method); targetTypeWithAnnotations = results[0].LValueType; reinferredGetEnumeratorMethod = method; } else if (conversion.IsIdentity || (conversion.Kind == ConversionKind.ExplicitReference && resultType.SpecialType == SpecialType.System_String)) { // This is case 3 or 6. targetTypeWithAnnotations = resultTypeWithState.ToTypeWithAnnotations(compilation); } else if (conversion.IsImplicit) { bool isAsync = node.AwaitOpt != null; if (node.Expression.Type!.SpecialType == SpecialType.System_Collections_IEnumerable) { // If this is a conversion to IEnumerable (non-generic), nothing to do. This is cases 1, 2, and 5. targetTypeWithAnnotations = TypeWithAnnotations.Create(node.Expression.Type); } else if (ForEachLoopBinder.IsIEnumerableT(node.Expression.Type.OriginalDefinition, isAsync, compilation)) { // This is case 4. We need to look for the IEnumerable<T> that this reinferred expression implements, // so that we pick up any nested type substitutions that could have occurred. var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; targetTypeWithAnnotations = TypeWithAnnotations.Create(ForEachLoopBinder.GetIEnumerableOfT(resultType, isAsync, compilation, ref discardedUseSiteInfo, out bool foundMultiple)); Debug.Assert(!foundMultiple); Debug.Assert(targetTypeWithAnnotations.HasType); } else { // This is case 8. There was not a successful binding, as a successful binding will _always_ generate one of the // above conversions. Just return, as we want to suppress further errors. return; } } else { // This is also case 8. return; } var convertedResult = VisitConversion( GetConversionIfApplicable(node.Expression, expr), expr, conversion, targetTypeWithAnnotations, resultTypeWithState, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Assignment); bool reportedDiagnostic = node.EnumeratorInfoOpt?.GetEnumeratorInfo.Method is { IsExtensionMethod: true } ? false : CheckPossibleNullReceiver(expr); SetAnalyzedNullability(node.Expression, new VisitResult(convertedResult, convertedResult.ToTypeWithAnnotations(compilation))); TypeWithState currentPropertyGetterTypeWithState; if (node.EnumeratorInfoOpt is null) { currentPropertyGetterTypeWithState = default; } else if (resultType is ArrayTypeSymbol arrayType) { // Even though arrays use the IEnumerator pattern, we use the array element type as the foreach target type, so // directly get our source type from there instead of doing method reinference. currentPropertyGetterTypeWithState = arrayType.ElementTypeWithAnnotations.ToTypeWithState(); } else if (resultType.SpecialType == SpecialType.System_String) { // There are frameworks where System.String does not implement IEnumerable, but we still lower it to a for loop // using the indexer over the individual characters anyway. So the type must be not annotated char. currentPropertyGetterTypeWithState = TypeWithAnnotations.Create(node.EnumeratorInfoOpt.ElementType, NullableAnnotation.NotAnnotated).ToTypeWithState(); } else { // Reinfer the return type of the node.Expression.GetEnumerator().Current property, so that if // the collection changed nested generic types we pick up those changes. reinferredGetEnumeratorMethod ??= (MethodSymbol)AsMemberOfType(convertedResult.Type, node.EnumeratorInfoOpt.GetEnumeratorInfo.Method); var enumeratorReturnType = GetReturnTypeWithState(reinferredGetEnumeratorMethod); if (enumeratorReturnType.State != NullableFlowState.NotNull) { if (!reportedDiagnostic && !(node.Expression is BoundConversion { Operand: { IsSuppressed: true } })) { ReportDiagnostic(ErrorCode.WRN_NullReferenceReceiver, expr.Syntax.GetLocation()); } } var currentPropertyGetter = (MethodSymbol)AsMemberOfType(enumeratorReturnType.Type, node.EnumeratorInfoOpt.CurrentPropertyGetter); currentPropertyGetterTypeWithState = ApplyUnconditionalAnnotations( currentPropertyGetter.ReturnTypeWithAnnotations.ToTypeWithState(), currentPropertyGetter.ReturnTypeFlowAnalysisAnnotations); // Analyze `await MoveNextAsync()` if (node.AwaitOpt is { AwaitableInstancePlaceholder: BoundAwaitableValuePlaceholder moveNextPlaceholder } awaitMoveNextInfo) { var moveNextAsyncMethod = (MethodSymbol)AsMemberOfType(reinferredGetEnumeratorMethod.ReturnType, node.EnumeratorInfoOpt.MoveNextInfo.Method); EnsureAwaitablePlaceholdersInitialized(); var result = new VisitResult(GetReturnTypeWithState(moveNextAsyncMethod), moveNextAsyncMethod.ReturnTypeWithAnnotations); _awaitablePlaceholdersOpt.Add(moveNextPlaceholder, (moveNextPlaceholder, result)); Visit(awaitMoveNextInfo); _awaitablePlaceholdersOpt.Remove(moveNextPlaceholder); } // Analyze `await DisposeAsync()` if (node.EnumeratorInfoOpt is { NeedsDisposal: true, DisposeAwaitableInfo: BoundAwaitableInfo awaitDisposalInfo }) { var disposalPlaceholder = awaitDisposalInfo.AwaitableInstancePlaceholder; bool addedPlaceholder = false; if (node.EnumeratorInfoOpt.PatternDisposeInfo is { Method: var originalDisposeMethod }) // no statically known Dispose method if doing a runtime check { Debug.Assert(disposalPlaceholder is not null); var disposeAsyncMethod = (MethodSymbol)AsMemberOfType(reinferredGetEnumeratorMethod.ReturnType, originalDisposeMethod); EnsureAwaitablePlaceholdersInitialized(); var result = new VisitResult(GetReturnTypeWithState(disposeAsyncMethod), disposeAsyncMethod.ReturnTypeWithAnnotations); _awaitablePlaceholdersOpt.Add(disposalPlaceholder, (disposalPlaceholder, result)); addedPlaceholder = true; } Visit(awaitDisposalInfo); if (addedPlaceholder) { _awaitablePlaceholdersOpt!.Remove(disposalPlaceholder!); } } } SetResultType(expression: null, currentPropertyGetterTypeWithState); } public override void VisitForEachIterationVariables(BoundForEachStatement node) { // ResultType should have been set by VisitForEachExpression, called just before this. var sourceState = node.EnumeratorInfoOpt == null ? default : ResultType; TypeWithAnnotations sourceType = sourceState.ToTypeWithAnnotations(compilation); #pragma warning disable IDE0055 // Fix formatting var variableLocation = node.Syntax switch { ForEachStatementSyntax statement => statement.Identifier.GetLocation(), ForEachVariableStatementSyntax variableStatement => variableStatement.Variable.GetLocation(), _ => throw ExceptionUtilities.UnexpectedValue(node.Syntax) }; #pragma warning restore IDE0055 // Fix formatting if (node.DeconstructionOpt is object) { var assignment = node.DeconstructionOpt.DeconstructionAssignment; // Visit the assignment as a deconstruction with an explicit type VisitDeconstructionAssignmentOperator(assignment, sourceState.HasNullType ? (TypeWithState?)null : sourceState); // https://github.com/dotnet/roslyn/issues/35010: if the iteration variable is a tuple deconstruction, we need to put something in the tree Visit(node.IterationVariableType); } else { Visit(node.IterationVariableType); foreach (var iterationVariable in node.IterationVariables) { var state = NullableFlowState.NotNull; if (!sourceState.HasNullType) { TypeWithAnnotations destinationType = iterationVariable.TypeWithAnnotations; TypeWithState result = sourceState; TypeWithState resultForType = sourceState; if (iterationVariable.IsRef) { // foreach (ref DestinationType variable in collection) if (IsNullabilityMismatch(sourceType, destinationType)) { var foreachSyntax = (ForEachStatementSyntax)node.Syntax; ReportNullabilityMismatchInAssignment(foreachSyntax.Type, sourceType, destinationType); } } else if (iterationVariable is SourceLocalSymbol { IsVar: true }) { // foreach (var variable in collection) destinationType = sourceState.ToAnnotatedTypeWithAnnotations(compilation); _variables.SetType(iterationVariable, destinationType); resultForType = destinationType.ToTypeWithState(); } else { // foreach (DestinationType variable in collection) // and asynchronous variants var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; Conversion conversion = node.ElementConversion.Kind == ConversionKind.UnsetConversionKind ? _conversions.ClassifyImplicitConversionFromType(sourceType.Type, destinationType.Type, ref discardedUseSiteInfo) : node.ElementConversion; result = VisitConversion( conversionOpt: null, conversionOperand: node.IterationVariableType, conversion, destinationType, sourceState, checkConversion: true, fromExplicitCast: !conversion.IsImplicit, useLegacyWarnings: true, AssignmentKind.ForEachIterationVariable, reportTopLevelWarnings: true, reportRemainingWarnings: true, diagnosticLocationOpt: variableLocation); } // In non-error cases we'll only run this loop a single time. In error cases we'll set the nullability of the VariableType multiple times, but at least end up with something SetAnalyzedNullability(node.IterationVariableType, new VisitResult(resultForType, destinationType), isLvalue: true); state = result.State; } int slot = GetOrCreateSlot(iterationVariable); if (slot > 0) { this.State[slot] = state; } } } } public override BoundNode? VisitFromEndIndexExpression(BoundFromEndIndexExpression node) { var result = base.VisitFromEndIndexExpression(node); SetNotNullResult(node); return result; } public override BoundNode? VisitObjectInitializerMember(BoundObjectInitializerMember node) { // Should be handled by VisitObjectCreationExpression. throw ExceptionUtilities.Unreachable; } public override BoundNode? VisitDynamicObjectInitializerMember(BoundDynamicObjectInitializerMember node) { SetNotNullResult(node); return null; } public override BoundNode? VisitBadExpression(BoundBadExpression node) { foreach (var child in node.ChildBoundNodes) { // https://github.com/dotnet/roslyn/issues/35042, we need to implement similar workarounds for object, collection, and dynamic initializers. if (child is BoundLambda lambda) { TakeIncrementalSnapshot(lambda); VisitLambda(lambda, delegateTypeOpt: null); VisitRvalueEpilogue(lambda); } else { VisitRvalue(child as BoundExpression); } } var type = TypeWithAnnotations.Create(node.Type); SetLvalueResultType(node, type); return null; } public override BoundNode? VisitTypeExpression(BoundTypeExpression node) { var result = base.VisitTypeExpression(node); if (node.BoundContainingTypeOpt != null) { VisitTypeExpression(node.BoundContainingTypeOpt); } SetNotNullResult(node); return result; } public override BoundNode? VisitTypeOrValueExpression(BoundTypeOrValueExpression node) { // These should not appear after initial binding except in error cases. var result = base.VisitTypeOrValueExpression(node); SetNotNullResult(node); return result; } public override BoundNode? VisitUnaryOperator(BoundUnaryOperator node) { Debug.Assert(!IsConditionalState); TypeWithState resultType; switch (node.OperatorKind) { case UnaryOperatorKind.BoolLogicalNegation: Visit(node.Operand); if (IsConditionalState) SetConditionalState(StateWhenFalse, StateWhenTrue); resultType = adjustForLifting(ResultType); break; case UnaryOperatorKind.DynamicTrue: // We cannot use VisitCondition, because the operand is not of type bool. // Yet we want to keep the result split if it was split. So we simply visit. Visit(node.Operand); resultType = adjustForLifting(ResultType); break; case UnaryOperatorKind.DynamicLogicalNegation: // We cannot use VisitCondition, because the operand is not of type bool. // Yet we want to keep the result split if it was split. So we simply visit. Visit(node.Operand); // If the state is split, the result is `bool` at runtime and we invert it here. if (IsConditionalState) SetConditionalState(StateWhenFalse, StateWhenTrue); resultType = adjustForLifting(ResultType); break; default: if (node.OperatorKind.IsUserDefined() && node.MethodOpt is MethodSymbol method && method.ParameterCount == 1) { var (operand, conversion) = RemoveConversion(node.Operand, includeExplicitConversions: false); VisitRvalue(operand); var operandResult = ResultType; bool isLifted = node.OperatorKind.IsLifted(); var operandType = GetNullableUnderlyingTypeIfNecessary(isLifted, operandResult); // Update method based on inferred operand type. method = (MethodSymbol)AsMemberOfType(operandType.Type!.StrippedType(), method); // Analyze operator call properly (honoring [Disallow|Allow|Maybe|NotNull] attribute annotations) https://github.com/dotnet/roslyn/issues/32671 var parameter = method.Parameters[0]; _ = VisitConversion( node.Operand as BoundConversion, operand, conversion, parameter.TypeWithAnnotations, operandType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, assignmentKind: AssignmentKind.Argument, parameterOpt: parameter); resultType = GetLiftedReturnTypeIfNecessary(isLifted, method.ReturnTypeWithAnnotations, operandResult.State); SetUpdatedSymbol(node, node.MethodOpt, method); } else { VisitRvalue(node.Operand); resultType = adjustForLifting(ResultType); } break; } SetResultType(node, resultType); return null; TypeWithState adjustForLifting(TypeWithState argumentResult) => TypeWithState.Create(node.Type, node.OperatorKind.IsLifted() ? argumentResult.State : NullableFlowState.NotNull); } public override BoundNode? VisitPointerIndirectionOperator(BoundPointerIndirectionOperator node) { var result = base.VisitPointerIndirectionOperator(node); var type = TypeWithAnnotations.Create(node.Type); SetLvalueResultType(node, type); return result; } public override BoundNode? VisitPointerElementAccess(BoundPointerElementAccess node) { var result = base.VisitPointerElementAccess(node); var type = TypeWithAnnotations.Create(node.Type); SetLvalueResultType(node, type); return result; } public override BoundNode? VisitRefTypeOperator(BoundRefTypeOperator node) { VisitRvalue(node.Operand); SetNotNullResult(node); return null; } public override BoundNode? VisitMakeRefOperator(BoundMakeRefOperator node) { var result = base.VisitMakeRefOperator(node); SetNotNullResult(node); return result; } public override BoundNode? VisitRefValueOperator(BoundRefValueOperator node) { var result = base.VisitRefValueOperator(node); var type = TypeWithAnnotations.Create(node.Type, node.NullableAnnotation); SetLvalueResultType(node, type); return result; } private TypeWithState InferResultNullability(BoundUserDefinedConditionalLogicalOperator node) { if (node.OperatorKind.IsLifted()) { // https://github.com/dotnet/roslyn/issues/33879 Conversions: Lifted operator // Should this use the updated flow type and state? How should it compute nullability? return TypeWithState.Create(node.Type, NullableFlowState.NotNull); } // Update method based on inferred operand types: see https://github.com/dotnet/roslyn/issues/29605. // Analyze operator result properly (honoring [Maybe|NotNull] and [Maybe|NotNullWhen] attribute annotations) https://github.com/dotnet/roslyn/issues/32671 if ((object)node.LogicalOperator != null && node.LogicalOperator.ParameterCount == 2) { return GetReturnTypeWithState(node.LogicalOperator); } else { return default; } } protected override void AfterLeftChildOfBinaryLogicalOperatorHasBeenVisited(BoundExpression node, BoundExpression right, bool isAnd, bool isBool, ref LocalState leftTrue, ref LocalState leftFalse) { Debug.Assert(!IsConditionalState); TypeWithState leftType = ResultType; // https://github.com/dotnet/roslyn/issues/29605 Update operator methods based on inferred operand types. MethodSymbol? logicalOperator = null; MethodSymbol? trueFalseOperator = null; BoundExpression? left = null; switch (node.Kind) { case BoundKind.BinaryOperator: Debug.Assert(!((BoundBinaryOperator)node).OperatorKind.IsUserDefined()); break; case BoundKind.UserDefinedConditionalLogicalOperator: var binary = (BoundUserDefinedConditionalLogicalOperator)node; if (binary.LogicalOperator != null && binary.LogicalOperator.ParameterCount == 2) { logicalOperator = binary.LogicalOperator; left = binary.Left; trueFalseOperator = isAnd ? binary.FalseOperator : binary.TrueOperator; if ((object)trueFalseOperator != null && trueFalseOperator.ParameterCount != 1) { trueFalseOperator = null; } } break; default: throw ExceptionUtilities.UnexpectedValue(node.Kind); } Debug.Assert(trueFalseOperator is null || logicalOperator is object); Debug.Assert(logicalOperator is null || left is object); // Analyze operator call properly (honoring [Disallow|Allow|Maybe|NotNull] attribute annotations) https://github.com/dotnet/roslyn/issues/32671 if (trueFalseOperator is object) { ReportArgumentWarnings(left!, leftType, trueFalseOperator.Parameters[0]); } if (logicalOperator is object) { ReportArgumentWarnings(left!, leftType, logicalOperator.Parameters[0]); } Visit(right); TypeWithState rightType = ResultType; SetResultType(node, InferResultNullabilityOfBinaryLogicalOperator(node, leftType, rightType)); if (logicalOperator is object) { ReportArgumentWarnings(right, rightType, logicalOperator.Parameters[1]); } AfterRightChildOfBinaryLogicalOperatorHasBeenVisited(node, right, isAnd, isBool, ref leftTrue, ref leftFalse); } private TypeWithState InferResultNullabilityOfBinaryLogicalOperator(BoundExpression node, TypeWithState leftType, TypeWithState rightType) { return node switch { BoundBinaryOperator binary => InferResultNullability(binary.OperatorKind, binary.Method, binary.Type, leftType, rightType), BoundUserDefinedConditionalLogicalOperator userDefined => InferResultNullability(userDefined), _ => throw ExceptionUtilities.UnexpectedValue(node) }; } public override BoundNode? VisitAwaitExpression(BoundAwaitExpression node) { var result = base.VisitAwaitExpression(node); var awaitableInfo = node.AwaitableInfo; var placeholder = awaitableInfo.AwaitableInstancePlaceholder; Debug.Assert(placeholder is object); EnsureAwaitablePlaceholdersInitialized(); _awaitablePlaceholdersOpt.Add(placeholder, (node.Expression, _visitResult)); Visit(awaitableInfo); _awaitablePlaceholdersOpt.Remove(placeholder); if (node.Type.IsValueType || node.HasErrors || awaitableInfo.GetResult is null) { SetNotNullResult(node); } else { // It is possible for the awaiter type returned from GetAwaiter to not be a named type. e.g. it could be a type parameter. // Proper handling of this is additional work which only benefits a very uncommon scenario, // so we will just use the originally bound GetResult method in this case. var getResult = awaitableInfo.GetResult; var reinferredGetResult = _visitResult.RValueType.Type is NamedTypeSymbol taskAwaiterType ? getResult.OriginalDefinition.AsMember(taskAwaiterType) : getResult; SetResultType(node, reinferredGetResult.ReturnTypeWithAnnotations.ToTypeWithState()); } return result; } public override BoundNode? VisitTypeOfOperator(BoundTypeOfOperator node) { var result = base.VisitTypeOfOperator(node); SetResultType(node, TypeWithState.Create(node.Type, NullableFlowState.NotNull)); return result; } public override BoundNode? VisitMethodInfo(BoundMethodInfo node) { var result = base.VisitMethodInfo(node); SetNotNullResult(node); return result; } public override BoundNode? VisitFieldInfo(BoundFieldInfo node) { var result = base.VisitFieldInfo(node); SetNotNullResult(node); return result; } public override BoundNode? VisitDefaultLiteral(BoundDefaultLiteral node) { // Can occur in error scenarios and lambda scenarios var result = base.VisitDefaultLiteral(node); SetResultType(node, TypeWithState.Create(node.Type, NullableFlowState.MaybeDefault)); return result; } public override BoundNode? VisitDefaultExpression(BoundDefaultExpression node) { Debug.Assert(!this.IsConditionalState); var result = base.VisitDefaultExpression(node); TypeSymbol type = node.Type; if (EmptyStructTypeCache.IsTrackableStructType(type)) { int slot = GetOrCreatePlaceholderSlot(node); if (slot > 0) { this.State[slot] = NullableFlowState.NotNull; InheritNullableStateOfTrackableStruct(type, slot, valueSlot: -1, isDefaultValue: true); } } // https://github.com/dotnet/roslyn/issues/33344: this fails to produce an updated tuple type for a default expression // (should produce nullable element types for those elements that are of reference types) SetResultType(node, TypeWithState.ForType(type)); return result; } public override BoundNode? VisitIsOperator(BoundIsOperator node) { Debug.Assert(!this.IsConditionalState); var operand = node.Operand; var typeExpr = node.TargetType; VisitPossibleConditionalAccess(operand, out var conditionalStateWhenNotNull); Unsplit(); LocalState stateWhenNotNull; if (!conditionalStateWhenNotNull.IsConditionalState) { stateWhenNotNull = conditionalStateWhenNotNull.State; } else { stateWhenNotNull = conditionalStateWhenNotNull.StateWhenTrue; Join(ref stateWhenNotNull, ref conditionalStateWhenNotNull.StateWhenFalse); } Debug.Assert(node.Type.SpecialType == SpecialType.System_Boolean); SetConditionalState(stateWhenNotNull, State); if (typeExpr.Type?.SpecialType == SpecialType.System_Object) { LearnFromNullTest(operand, ref StateWhenFalse); } VisitTypeExpression(typeExpr); SetNotNullResult(node); return null; } public override BoundNode? VisitAsOperator(BoundAsOperator node) { var argumentType = VisitRvalueWithState(node.Operand); NullableFlowState resultState = NullableFlowState.NotNull; var type = node.Type; if (type.CanContainNull()) { switch (node.Conversion.Kind) { case ConversionKind.Identity: case ConversionKind.ImplicitReference: case ConversionKind.Boxing: case ConversionKind.ImplicitNullable: resultState = argumentType.State; break; default: resultState = NullableFlowState.MaybeDefault; break; } } VisitTypeExpression(node.TargetType); SetResultType(node, TypeWithState.Create(type, resultState)); return null; } public override BoundNode? VisitSizeOfOperator(BoundSizeOfOperator node) { var result = base.VisitSizeOfOperator(node); VisitTypeExpression(node.SourceType); SetNotNullResult(node); return result; } public override BoundNode? VisitArgList(BoundArgList node) { var result = base.VisitArgList(node); Debug.Assert(node.Type.SpecialType == SpecialType.System_RuntimeArgumentHandle); SetNotNullResult(node); return result; } public override BoundNode? VisitArgListOperator(BoundArgListOperator node) { VisitArgumentsEvaluate(node.Syntax, node.Arguments, node.ArgumentRefKindsOpt, parametersOpt: default, argsToParamsOpt: default, defaultArguments: default, expanded: false); Debug.Assert(node.Type is null); SetNotNullResult(node); return null; } public override BoundNode? VisitLiteral(BoundLiteral node) { Debug.Assert(!IsConditionalState); var result = base.VisitLiteral(node); SetResultType(node, TypeWithState.Create(node.Type, node.Type?.CanContainNull() != false && node.ConstantValue?.IsNull == true ? NullableFlowState.MaybeDefault : NullableFlowState.NotNull)); return result; } public override BoundNode? VisitPreviousSubmissionReference(BoundPreviousSubmissionReference node) { var result = base.VisitPreviousSubmissionReference(node); Debug.Assert(node.WasCompilerGenerated); SetNotNullResult(node); return result; } public override BoundNode? VisitHostObjectMemberReference(BoundHostObjectMemberReference node) { var result = base.VisitHostObjectMemberReference(node); Debug.Assert(node.WasCompilerGenerated); SetNotNullResult(node); return result; } public override BoundNode? VisitPseudoVariable(BoundPseudoVariable node) { var result = base.VisitPseudoVariable(node); SetNotNullResult(node); return result; } public override BoundNode? VisitRangeExpression(BoundRangeExpression node) { var result = base.VisitRangeExpression(node); SetNotNullResult(node); return result; } public override BoundNode? VisitRangeVariable(BoundRangeVariable node) { VisitWithoutDiagnostics(node.Value); SetNotNullResult(node); // https://github.com/dotnet/roslyn/issues/29863 Need to review this return null; } public override BoundNode? VisitLabel(BoundLabel node) { var result = base.VisitLabel(node); SetUnknownResultNullability(node); return result; } public override BoundNode? VisitDynamicMemberAccess(BoundDynamicMemberAccess node) { var receiver = node.Receiver; VisitRvalue(receiver); _ = CheckPossibleNullReceiver(receiver); Debug.Assert(node.Type.IsDynamic()); var result = TypeWithAnnotations.Create(node.Type); SetLvalueResultType(node, result); return null; } public override BoundNode? VisitDynamicInvocation(BoundDynamicInvocation node) { var expr = node.Expression; VisitRvalue(expr); // If the expression was a MethodGroup, check nullability of receiver. var receiverOpt = (expr as BoundMethodGroup)?.ReceiverOpt; if (TryGetMethodGroupReceiverNullability(receiverOpt, out TypeWithState receiverType)) { CheckPossibleNullReceiver(receiverOpt, receiverType, checkNullableValueType: false); } VisitArgumentsEvaluate(node.Syntax, node.Arguments, node.ArgumentRefKindsOpt, parametersOpt: default, argsToParamsOpt: default, defaultArguments: default, expanded: false); Debug.Assert(node.Type.IsDynamic()); Debug.Assert(node.Type.IsReferenceType); var result = TypeWithAnnotations.Create(node.Type, NullableAnnotation.Oblivious); SetLvalueResultType(node, result); return null; } public override BoundNode? VisitEventAssignmentOperator(BoundEventAssignmentOperator node) { var receiverOpt = node.ReceiverOpt; VisitRvalue(receiverOpt); Debug.Assert(!IsConditionalState); var @event = node.Event; if ([email protected]) { @event = (EventSymbol)AsMemberOfType(ResultType.Type, @event); // https://github.com/dotnet/roslyn/issues/30598: Mark receiver as not null // after arguments have been visited, and only if the receiver has not changed. _ = CheckPossibleNullReceiver(receiverOpt); SetUpdatedSymbol(node, node.Event, @event); } VisitRvalue(node.Argument); // https://github.com/dotnet/roslyn/issues/31018: Check for delegate mismatch. if (node.Argument.ConstantValue?.IsNull != true && MakeMemberSlot(receiverOpt, @event) is > 0 and var memberSlot) { this.State[memberSlot] = node.IsAddition ? this.State[memberSlot].Meet(ResultType.State) : NullableFlowState.MaybeNull; } SetNotNullResult(node); // https://github.com/dotnet/roslyn/issues/29969 Review whether this is the correct result return null; } public override BoundNode? VisitDynamicObjectCreationExpression(BoundDynamicObjectCreationExpression node) { Debug.Assert(!IsConditionalState); var arguments = node.Arguments; var argumentResults = VisitArgumentsEvaluate(node.Syntax, arguments, node.ArgumentRefKindsOpt, parametersOpt: default, argsToParamsOpt: default, defaultArguments: default, expanded: false); VisitObjectOrDynamicObjectCreation(node, arguments, argumentResults, node.InitializerExpressionOpt); return null; } public override BoundNode? VisitObjectInitializerExpression(BoundObjectInitializerExpression node) { // Only reachable from bad expression. Otherwise handled in VisitObjectCreationExpression(). // https://github.com/dotnet/roslyn/issues/35042: Do we need to analyze child expressions anyway for the public API? SetNotNullResult(node); return null; } public override BoundNode? VisitCollectionInitializerExpression(BoundCollectionInitializerExpression node) { // Only reachable from bad expression. Otherwise handled in VisitObjectCreationExpression(). // https://github.com/dotnet/roslyn/issues/35042: Do we need to analyze child expressions anyway for the public API? SetNotNullResult(node); return null; } public override BoundNode? VisitDynamicCollectionElementInitializer(BoundDynamicCollectionElementInitializer node) { // Only reachable from bad expression. Otherwise handled in VisitObjectCreationExpression(). // https://github.com/dotnet/roslyn/issues/35042: Do we need to analyze child expressions anyway for the public API? SetNotNullResult(node); return null; } public override BoundNode? VisitImplicitReceiver(BoundImplicitReceiver node) { var result = base.VisitImplicitReceiver(node); SetNotNullResult(node); return result; } public override BoundNode? VisitAnonymousPropertyDeclaration(BoundAnonymousPropertyDeclaration node) { throw ExceptionUtilities.Unreachable; } public override BoundNode? VisitNoPiaObjectCreationExpression(BoundNoPiaObjectCreationExpression node) { var result = base.VisitNoPiaObjectCreationExpression(node); SetResultType(node, TypeWithState.Create(node.Type, NullableFlowState.NotNull)); return result; } public override BoundNode? VisitNewT(BoundNewT node) { VisitObjectOrDynamicObjectCreation(node, ImmutableArray<BoundExpression>.Empty, ImmutableArray<VisitArgumentResult>.Empty, node.InitializerExpressionOpt); return null; } public override BoundNode? VisitArrayInitialization(BoundArrayInitialization node) { var result = base.VisitArrayInitialization(node); SetNotNullResult(node); return result; } private void SetUnknownResultNullability(BoundExpression expression) { SetResultType(expression, TypeWithState.Create(expression.Type, default)); } public override BoundNode? VisitStackAllocArrayCreation(BoundStackAllocArrayCreation node) { var result = base.VisitStackAllocArrayCreation(node); Debug.Assert(node.Type is null || node.Type.IsErrorType() || node.Type.IsRefLikeType); SetNotNullResult(node); return result; } public override BoundNode? VisitDynamicIndexerAccess(BoundDynamicIndexerAccess node) { var receiver = node.Receiver; VisitRvalue(receiver); // https://github.com/dotnet/roslyn/issues/30598: Mark receiver as not null // after indices have been visited, and only if the receiver has not changed. _ = CheckPossibleNullReceiver(receiver); VisitArgumentsEvaluate(node.Syntax, node.Arguments, node.ArgumentRefKindsOpt, parametersOpt: default, argsToParamsOpt: default, defaultArguments: default, expanded: false); Debug.Assert(node.Type.IsDynamic()); var result = TypeWithAnnotations.Create(node.Type, NullableAnnotation.Oblivious); SetLvalueResultType(node, result); return null; } private bool CheckPossibleNullReceiver(BoundExpression? receiverOpt, bool checkNullableValueType = false) { return CheckPossibleNullReceiver(receiverOpt, ResultType, checkNullableValueType); } private bool CheckPossibleNullReceiver(BoundExpression? receiverOpt, TypeWithState resultType, bool checkNullableValueType) { Debug.Assert(!this.IsConditionalState); bool reportedDiagnostic = false; if (receiverOpt != null && this.State.Reachable) { var resultTypeSymbol = resultType.Type; if (resultTypeSymbol is null) { return false; } #if DEBUG Debug.Assert(receiverOpt.Type is null || AreCloseEnough(receiverOpt.Type, resultTypeSymbol)); #endif if (!ReportPossibleNullReceiverIfNeeded(resultTypeSymbol, resultType.State, checkNullableValueType, receiverOpt.Syntax, out reportedDiagnostic)) { return reportedDiagnostic; } LearnFromNonNullTest(receiverOpt, ref this.State); } return reportedDiagnostic; } // Returns false if the type wasn't interesting private bool ReportPossibleNullReceiverIfNeeded(TypeSymbol type, NullableFlowState state, bool checkNullableValueType, SyntaxNode syntax, out bool reportedDiagnostic) { reportedDiagnostic = false; if (state.MayBeNull()) { bool isValueType = type.IsValueType; if (isValueType && (!checkNullableValueType || !type.IsNullableTypeOrTypeParameter() || type.GetNullableUnderlyingType().IsErrorType())) { return false; } ReportDiagnostic(isValueType ? ErrorCode.WRN_NullableValueTypeMayBeNull : ErrorCode.WRN_NullReferenceReceiver, syntax); reportedDiagnostic = true; } return true; } private void CheckExtensionMethodThisNullability(BoundExpression expr, Conversion conversion, ParameterSymbol parameter, TypeWithState result) { VisitArgumentConversionAndInboundAssignmentsAndPreConditions( conversionOpt: null, expr, conversion, parameter.RefKind, parameter, parameter.TypeWithAnnotations, GetParameterAnnotations(parameter), new VisitArgumentResult(new VisitResult(result, result.ToTypeWithAnnotations(compilation)), stateForLambda: default), extensionMethodThisArgument: true); } private static bool IsNullabilityMismatch(TypeWithAnnotations type1, TypeWithAnnotations type2) { // Note, when we are paying attention to nullability, we ignore oblivious mismatch. // See TypeCompareKind.ObliviousNullableModifierMatchesAny return type1.Equals(type2, TypeCompareKind.AllIgnoreOptions) && !type1.Equals(type2, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.IgnoreNullableModifiersForReferenceTypes); } private static bool IsNullabilityMismatch(TypeSymbol type1, TypeSymbol type2) { // Note, when we are paying attention to nullability, we ignore oblivious mismatch. // See TypeCompareKind.ObliviousNullableModifierMatchesAny return type1.Equals(type2, TypeCompareKind.AllIgnoreOptions) && !type1.Equals(type2, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.IgnoreNullableModifiersForReferenceTypes); } public override BoundNode? VisitQueryClause(BoundQueryClause node) { var result = base.VisitQueryClause(node); SetNotNullResult(node); // https://github.com/dotnet/roslyn/issues/29863 Implement nullability analysis in LINQ queries return result; } public override BoundNode? VisitNameOfOperator(BoundNameOfOperator node) { var result = base.VisitNameOfOperator(node); SetResultType(node, TypeWithState.Create(node.Type, NullableFlowState.NotNull)); return result; } public override BoundNode? VisitNamespaceExpression(BoundNamespaceExpression node) { var result = base.VisitNamespaceExpression(node); SetUnknownResultNullability(node); return result; } // https://github.com/dotnet/roslyn/issues/54583 // Better handle the constructor propagation //public override BoundNode? VisitInterpolatedString(BoundInterpolatedString node) //{ //} public override BoundNode? VisitUnconvertedInterpolatedString(BoundUnconvertedInterpolatedString node) { // This is only involved with unbound lambdas or when visiting the source of a converted tuple literal var result = base.VisitUnconvertedInterpolatedString(node); SetResultType(node, TypeWithState.Create(node.Type, NullableFlowState.NotNull)); return result; } public override BoundNode? VisitStringInsert(BoundStringInsert node) { var result = base.VisitStringInsert(node); SetUnknownResultNullability(node); return result; } public override BoundNode? VisitInterpolatedStringHandlerPlaceholder(BoundInterpolatedStringHandlerPlaceholder node) { SetNotNullResult(node); return null; } public override BoundNode? VisitInterpolatedStringArgumentPlaceholder(BoundInterpolatedStringArgumentPlaceholder node) { SetNotNullResult(node); return null; } public override BoundNode? VisitConvertedStackAllocExpression(BoundConvertedStackAllocExpression node) { var result = base.VisitConvertedStackAllocExpression(node); SetNotNullResult(node); return result; } public override BoundNode? VisitDiscardExpression(BoundDiscardExpression node) { var result = TypeWithAnnotations.Create(node.Type); var rValueType = TypeWithState.ForType(node.Type); SetResult(node, rValueType, result); return null; } public override BoundNode? VisitThrowExpression(BoundThrowExpression node) { VisitThrow(node.Expression); SetResultType(node, default); return null; } public override BoundNode? VisitThrowStatement(BoundThrowStatement node) { VisitThrow(node.ExpressionOpt); return null; } private void VisitThrow(BoundExpression? expr) { if (expr != null) { var result = VisitRvalueWithState(expr); // Cases: // null // null! // Other (typed) expression, including suppressed ones if (result.MayBeNull) { ReportDiagnostic(ErrorCode.WRN_ThrowPossibleNull, expr.Syntax); } } SetUnreachable(); } public override BoundNode? VisitYieldReturnStatement(BoundYieldReturnStatement node) { BoundExpression expr = node.Expression; if (expr == null) { return null; } var method = (MethodSymbol)CurrentSymbol; TypeWithAnnotations elementType = InMethodBinder.GetIteratorElementTypeFromReturnType(compilation, RefKind.None, method.ReturnType, errorLocation: null, diagnostics: null); _ = VisitOptionalImplicitConversion(expr, elementType, useLegacyWarnings: false, trackMembers: false, AssignmentKind.Return); return null; } protected override void VisitCatchBlock(BoundCatchBlock node, ref LocalState finallyState) { TakeIncrementalSnapshot(node); if (node.Locals.Length > 0) { LocalSymbol local = node.Locals[0]; if (local.DeclarationKind == LocalDeclarationKind.CatchVariable) { int slot = GetOrCreateSlot(local); if (slot > 0) this.State[slot] = NullableFlowState.NotNull; } } if (node.ExceptionSourceOpt != null) { VisitWithoutDiagnostics(node.ExceptionSourceOpt); } base.VisitCatchBlock(node, ref finallyState); } public override BoundNode? VisitLockStatement(BoundLockStatement node) { VisitRvalue(node.Argument); _ = CheckPossibleNullReceiver(node.Argument); VisitStatement(node.Body); return null; } public override BoundNode? VisitAttribute(BoundAttribute node) { VisitArguments(node, node.ConstructorArguments, ImmutableArray<RefKind>.Empty, node.Constructor, argsToParamsOpt: node.ConstructorArgumentsToParamsOpt, defaultArguments: default, expanded: node.ConstructorExpanded, invokedAsExtensionMethod: false); foreach (var assignment in node.NamedArguments) { Visit(assignment); } SetNotNullResult(node); return null; } public override BoundNode? VisitExpressionWithNullability(BoundExpressionWithNullability node) { var typeWithAnnotations = TypeWithAnnotations.Create(node.Type, node.NullableAnnotation); SetResult(node.Expression, typeWithAnnotations.ToTypeWithState(), typeWithAnnotations); return null; } public override BoundNode? VisitDeconstructValuePlaceholder(BoundDeconstructValuePlaceholder node) { SetNotNullResult(node); return null; } public override BoundNode? VisitObjectOrCollectionValuePlaceholder(BoundObjectOrCollectionValuePlaceholder node) { SetNotNullResult(node); return null; } [MemberNotNull(nameof(_awaitablePlaceholdersOpt))] private void EnsureAwaitablePlaceholdersInitialized() { _awaitablePlaceholdersOpt ??= PooledDictionary<BoundAwaitableValuePlaceholder, (BoundExpression AwaitableExpression, VisitResult Result)>.GetInstance(); } public override BoundNode? VisitAwaitableValuePlaceholder(BoundAwaitableValuePlaceholder node) { if (_awaitablePlaceholdersOpt != null && _awaitablePlaceholdersOpt.TryGetValue(node, out var value)) { var result = value.Result; SetResult(node, result.RValueType, result.LValueType); } else { SetNotNullResult(node); } return null; } public override BoundNode? VisitAwaitableInfo(BoundAwaitableInfo node) { Visit(node.AwaitableInstancePlaceholder); Visit(node.GetAwaiter); return null; } public override BoundNode? VisitFunctionPointerInvocation(BoundFunctionPointerInvocation node) { _ = Visit(node.InvokedExpression); Debug.Assert(ResultType is TypeWithState { Type: FunctionPointerTypeSymbol { }, State: NullableFlowState.NotNull }); _ = VisitArguments( node, node.Arguments, node.ArgumentRefKindsOpt, node.FunctionPointer.Signature, argsToParamsOpt: default, defaultArguments: default, expanded: false, invokedAsExtensionMethod: false); var returnTypeWithAnnotations = node.FunctionPointer.Signature.ReturnTypeWithAnnotations; SetResult(node, returnTypeWithAnnotations.ToTypeWithState(), returnTypeWithAnnotations); return null; } protected override string Dump(LocalState state) { return state.Dump(_variables); } protected override bool Meet(ref LocalState self, ref LocalState other) { if (!self.Reachable) return false; if (!other.Reachable) { self = other.Clone(); return true; } Normalize(ref self); Normalize(ref other); return self.Meet(in other); } protected override bool Join(ref LocalState self, ref LocalState other) { if (!other.Reachable) return false; if (!self.Reachable) { self = other.Clone(); return true; } Normalize(ref self); Normalize(ref other); return self.Join(in other); } private void Join(ref PossiblyConditionalState other) { var otherIsConditional = other.IsConditionalState; if (otherIsConditional) { Split(); } if (IsConditionalState) { Join(ref StateWhenTrue, ref otherIsConditional ? ref other.StateWhenTrue : ref other.State); Join(ref StateWhenFalse, ref otherIsConditional ? ref other.StateWhenFalse : ref other.State); } else { Debug.Assert(!otherIsConditional); Join(ref State, ref other.State); } } private LocalState CloneAndUnsplit(ref PossiblyConditionalState conditionalState) { if (!conditionalState.IsConditionalState) { return conditionalState.State.Clone(); } var state = conditionalState.StateWhenTrue.Clone(); Join(ref state, ref conditionalState.StateWhenFalse); return state; } private void SetPossiblyConditionalState(in PossiblyConditionalState conditionalState) { if (!conditionalState.IsConditionalState) { SetState(conditionalState.State); } else { SetConditionalState(conditionalState.StateWhenTrue, conditionalState.StateWhenFalse); } } internal sealed class LocalStateSnapshot { internal readonly int Id; internal readonly LocalStateSnapshot? Container; internal readonly BitVector State; internal LocalStateSnapshot(int id, LocalStateSnapshot? container, BitVector state) { Id = id; Container = container; State = state; } } /// <summary> /// A bit array containing the nullability of variables associated with a method scope. If the method is a /// nested function (a lambda or a local function), there is a reference to the corresponding instance for /// the containing method scope. The instances in the chain are associated with a corresponding /// <see cref="Variables"/> chain, and the <see cref="Id"/> field in this type matches <see cref="Variables.Id"/>. /// </summary> [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] internal struct LocalState : ILocalDataFlowState { private sealed class Boxed { internal LocalState Value; internal Boxed(LocalState value) { Value = value; } } internal readonly int Id; private readonly Boxed? _container; // The representation of a state is a bit vector with two bits per slot: // (false, false) => NotNull, (false, true) => MaybeNull, (true, true) => MaybeDefault. // Slot 0 is used to represent whether the state is reachable (true) or not. private BitVector _state; private LocalState(int id, Boxed? container, BitVector state) { Id = id; _container = container; _state = state; } internal static LocalState Create(LocalStateSnapshot snapshot) { var container = snapshot.Container is null ? null : new Boxed(Create(snapshot.Container)); return new LocalState(snapshot.Id, container, snapshot.State.Clone()); } internal LocalStateSnapshot CreateSnapshot() { return new LocalStateSnapshot(Id, _container?.Value.CreateSnapshot(), _state.Clone()); } public bool Reachable => _state[0]; public bool NormalizeToBottom => false; public static LocalState ReachableState(Variables variables) { return CreateReachableOrUnreachableState(variables, reachable: true); } public static LocalState UnreachableState(Variables variables) { return CreateReachableOrUnreachableState(variables, reachable: false); } private static LocalState CreateReachableOrUnreachableState(Variables variables, bool reachable) { var container = variables.Container is null ? null : new Boxed(CreateReachableOrUnreachableState(variables.Container, reachable)); int capacity = reachable ? variables.NextAvailableIndex : 1; return new LocalState(variables.Id, container, CreateBitVector(capacity, reachable)); } public LocalState CreateNestedMethodState(Variables variables) { Debug.Assert(Id == variables.Container!.Id); return new LocalState(variables.Id, container: new Boxed(this), CreateBitVector(capacity: variables.NextAvailableIndex, reachable: true)); } private static BitVector CreateBitVector(int capacity, bool reachable) { if (capacity < 1) capacity = 1; BitVector state = BitVector.Create(capacity * 2); state[0] = reachable; return state; } private int Capacity => _state.Capacity / 2; private void EnsureCapacity(int capacity) { _state.EnsureCapacity(capacity * 2); } public bool HasVariable(int slot) { if (slot <= 0) { return false; } (int id, int index) = Variables.DeconstructSlot(slot); return HasVariable(id, index); } private bool HasVariable(int id, int index) { if (Id > id) { return _container!.Value.HasValue(id, index); } else { return Id == id; } } public bool HasValue(int slot) { if (slot <= 0) { return false; } (int id, int index) = Variables.DeconstructSlot(slot); return HasValue(id, index); } private bool HasValue(int id, int index) { if (Id != id) { Debug.Assert(Id > id); return _container!.Value.HasValue(id, index); } else { return index < Capacity; } } public void Normalize(NullableWalker walker, Variables variables) { if (Id != variables.Id) { Debug.Assert(Id < variables.Id); Normalize(walker, variables.Container!); } else { _container?.Value.Normalize(walker, variables.Container!); int start = Capacity; EnsureCapacity(variables.NextAvailableIndex); Populate(walker, start); } } public void PopulateAll(NullableWalker walker) { _container?.Value.PopulateAll(walker); Populate(walker, start: 1); } private void Populate(NullableWalker walker, int start) { int capacity = Capacity; for (int index = start; index < capacity; index++) { int slot = Variables.ConstructSlot(Id, index); SetValue(Id, index, walker.GetDefaultState(ref this, slot)); } } public NullableFlowState this[int slot] { get { (int id, int index) = Variables.DeconstructSlot(slot); return GetValue(id, index); } set { (int id, int index) = Variables.DeconstructSlot(slot); SetValue(id, index, value); } } private NullableFlowState GetValue(int id, int index) { if (Id != id) { Debug.Assert(Id > id); return _container!.Value.GetValue(id, index); } else { if (index < Capacity && this.Reachable) { index *= 2; var result = (_state[index + 1], _state[index]) switch { (false, false) => NullableFlowState.NotNull, (false, true) => NullableFlowState.MaybeNull, (true, false) => throw ExceptionUtilities.UnexpectedValue(index), (true, true) => NullableFlowState.MaybeDefault }; return result; } return NullableFlowState.NotNull; } } private void SetValue(int id, int index, NullableFlowState value) { if (Id != id) { Debug.Assert(Id > id); _container!.Value.SetValue(id, index, value); } else { // No states should be modified in unreachable code, as there is only one unreachable state. if (!this.Reachable) return; index *= 2; _state[index] = (value != NullableFlowState.NotNull); _state[index + 1] = (value == NullableFlowState.MaybeDefault); } } internal void ForEach<TArg>(Action<int, TArg> action, TArg arg) { _container?.Value.ForEach(action, arg); for (int index = 1; index < Capacity; index++) { action(Variables.ConstructSlot(Id, index), arg); } } internal LocalState GetStateForVariables(int id) { var state = this; while (state.Id != id) { state = state._container!.Value; } return state; } /// <summary> /// Produce a duplicate of this flow analysis state. /// </summary> /// <returns></returns> public LocalState Clone() { var container = _container is null ? null : new Boxed(_container.Value.Clone()); return new LocalState(Id, container, _state.Clone()); } public bool Join(in LocalState other) { Debug.Assert(Id == other.Id); bool result = false; if (_container is { } && _container.Value.Join(in other._container!.Value)) { result = true; } if (_state.UnionWith(in other._state)) { result = true; } return result; } public bool Meet(in LocalState other) { Debug.Assert(Id == other.Id); bool result = false; if (_container is { } && _container.Value.Meet(in other._container!.Value)) { result = true; } if (_state.IntersectWith(in other._state)) { result = true; } return result; } internal string GetDebuggerDisplay() { var pooledBuilder = PooledStringBuilder.GetInstance(); var builder = pooledBuilder.Builder; builder.Append(" "); int n = Math.Min(Capacity, 8); for (int i = n - 1; i >= 0; i--) builder.Append(_state[i * 2] ? '?' : '!'); return pooledBuilder.ToStringAndFree(); } internal string Dump(Variables variables) { if (!this.Reachable) return "unreachable"; if (Id != variables.Id) return "invalid"; var builder = PooledStringBuilder.GetInstance(); Dump(builder, variables); return builder.ToStringAndFree(); } private void Dump(StringBuilder builder, Variables variables) { _container?.Value.Dump(builder, variables.Container!); for (int index = 1; index < Capacity; index++) { if (getName(Variables.ConstructSlot(Id, index)) is string name) { builder.Append(name); var annotation = GetValue(Id, index) switch { NullableFlowState.MaybeNull => "?", NullableFlowState.MaybeDefault => "??", _ => "!" }; builder.Append(annotation); } } string? getName(int slot) { VariableIdentifier id = variables[slot]; var name = id.Symbol.Name; int containingSlot = id.ContainingSlot; return containingSlot > 0 ? getName(containingSlot) + "." + name : name; } } } internal sealed class LocalFunctionState : AbstractLocalFunctionState { /// <summary> /// Defines the starting state used in the local function body to /// produce diagnostics and determine types. /// </summary> public LocalState StartingState; public LocalFunctionState(LocalState unreachableState) : base(unreachableState.Clone(), unreachableState.Clone()) { StartingState = unreachableState; } } protected override LocalFunctionState CreateLocalFunctionState(LocalFunctionSymbol symbol) { var variables = (symbol.ContainingSymbol is MethodSymbol containingMethod ? _variables.GetVariablesForMethodScope(containingMethod) : null) ?? _variables.GetRootScope(); return new LocalFunctionState(LocalState.UnreachableState(variables)); } private sealed class NullabilityInfoTypeComparer : IEqualityComparer<(NullabilityInfo info, TypeSymbol? type)> { public static readonly NullabilityInfoTypeComparer Instance = new NullabilityInfoTypeComparer(); public bool Equals((NullabilityInfo info, TypeSymbol? type) x, (NullabilityInfo info, TypeSymbol? type) y) { return x.info.Equals(y.info) && Symbols.SymbolEqualityComparer.ConsiderEverything.Equals(x.type, y.type); } public int GetHashCode((NullabilityInfo info, TypeSymbol? type) obj) { return obj.GetHashCode(); } } private sealed class ExpressionAndSymbolEqualityComparer : IEqualityComparer<(BoundNode? expr, Symbol symbol)> { internal static readonly ExpressionAndSymbolEqualityComparer Instance = new ExpressionAndSymbolEqualityComparer(); private ExpressionAndSymbolEqualityComparer() { } public bool Equals((BoundNode? expr, Symbol symbol) x, (BoundNode? expr, Symbol symbol) y) { RoslynDebug.Assert(x.symbol is object); RoslynDebug.Assert(y.symbol is object); // We specifically use reference equality for the symbols here because the BoundNode should be immutable. // We should be storing and retrieving the exact same instance of the symbol, not just an "equivalent" // symbol. return x.expr == y.expr && (object)x.symbol == y.symbol; } public int GetHashCode((BoundNode? expr, Symbol symbol) obj) { RoslynDebug.Assert(obj.symbol is object); return Hash.Combine(obj.expr, obj.symbol.GetHashCode()); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// Nullability flow analysis. /// </summary> [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] internal sealed partial class NullableWalker : LocalDataFlowPass<NullableWalker.LocalState, NullableWalker.LocalFunctionState> { /// <summary> /// Used to copy variable slots and types from the NullableWalker for the containing method /// or lambda to the NullableWalker created for a nested lambda or local function. /// </summary> internal sealed class VariableState { // Consider referencing the Variables instance directly from the original NullableWalker // rather than cloning. (Items are added to the collections but never replaced so the // collections are lazily populated but otherwise immutable. We'd probably want a // clone when analyzing from speculative semantic model though.) internal readonly VariablesSnapshot Variables; // The nullable state of all variables captured at the point where the function or lambda appeared. internal readonly LocalStateSnapshot VariableNullableStates; internal VariableState(VariablesSnapshot variables, LocalStateSnapshot variableNullableStates) { Variables = variables; VariableNullableStates = variableNullableStates; } } /// <summary> /// Data recorded for a particular analysis run. /// </summary> internal readonly struct Data { /// <summary> /// Number of entries tracked during analysis. /// </summary> internal readonly int TrackedEntries; /// <summary> /// True if analysis was required; false if analysis was optional and results dropped. /// </summary> internal readonly bool RequiredAnalysis; internal Data(int trackedEntries, bool requiredAnalysis) { TrackedEntries = trackedEntries; RequiredAnalysis = requiredAnalysis; } } /// <summary> /// Represents the result of visiting an expression. /// Contains a result type which tells us whether the expression may be null, /// and an l-value type which tells us whether we can assign null to the expression. /// </summary> [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] private readonly struct VisitResult { public readonly TypeWithState RValueType; public readonly TypeWithAnnotations LValueType; public VisitResult(TypeWithState rValueType, TypeWithAnnotations lValueType) { RValueType = rValueType; LValueType = lValueType; // https://github.com/dotnet/roslyn/issues/34993: Doesn't hold true for Tuple_Assignment_10. See if we can make it hold true //Debug.Assert((RValueType.Type is null && LValueType.TypeSymbol is null) || // RValueType.Type.Equals(LValueType.TypeSymbol, TypeCompareKind.ConsiderEverything | TypeCompareKind.AllIgnoreOptions)); } public VisitResult(TypeSymbol? type, NullableAnnotation annotation, NullableFlowState state) { RValueType = TypeWithState.Create(type, state); LValueType = TypeWithAnnotations.Create(type, annotation); Debug.Assert(TypeSymbol.Equals(RValueType.Type, LValueType.Type, TypeCompareKind.ConsiderEverything)); } internal string GetDebuggerDisplay() => $"{{LValue: {LValueType.GetDebuggerDisplay()}, RValue: {RValueType.GetDebuggerDisplay()}}}"; } /// <summary> /// Represents the result of visiting an argument expression. /// In addition to storing the <see cref="VisitResult"/>, also stores the <see cref="LocalState"/> /// for reanalyzing a lambda. /// </summary> [DebuggerDisplay("{VisitResult.GetDebuggerDisplay(), nq}")] private readonly struct VisitArgumentResult { public readonly VisitResult VisitResult; public readonly Optional<LocalState> StateForLambda; public TypeWithState RValueType => VisitResult.RValueType; public TypeWithAnnotations LValueType => VisitResult.LValueType; public VisitArgumentResult(VisitResult visitResult, Optional<LocalState> stateForLambda) { VisitResult = visitResult; StateForLambda = stateForLambda; } } private Variables _variables; /// <summary> /// Binder for symbol being analyzed. /// </summary> private readonly Binder _binder; /// <summary> /// Conversions with nullability and unknown matching any. /// </summary> private readonly Conversions _conversions; /// <summary> /// 'true' if non-nullable member warnings should be issued at return points. /// One situation where this is 'false' is when we are analyzing field initializers and there is a constructor symbol in the type. /// </summary> private readonly bool _useConstructorExitWarnings; /// <summary> /// If true, the parameter types and nullability from _delegateInvokeMethod is used for /// initial parameter state. If false, the signature of CurrentSymbol is used instead. /// </summary> private bool _useDelegateInvokeParameterTypes; /// <summary> /// If true, the return type and nullability from _delegateInvokeMethod is used. /// If false, the signature of CurrentSymbol is used instead. /// </summary> private bool _useDelegateInvokeReturnType; /// <summary> /// Method signature used for return or parameter types. Distinct from CurrentSymbol signature /// when CurrentSymbol is a lambda and type is inferred from MethodTypeInferrer. /// </summary> private MethodSymbol? _delegateInvokeMethod; /// <summary> /// Return statements and the result types from analyzing the returned expressions. Used when inferring lambda return type in MethodTypeInferrer. /// </summary> private ArrayBuilder<(BoundReturnStatement, TypeWithAnnotations)>? _returnTypesOpt; /// <summary> /// Invalid type, used only to catch Visit methods that do not set /// _result.Type. See VisitExpressionWithoutStackGuard. /// </summary> private static readonly TypeWithState _invalidType = TypeWithState.Create(ErrorTypeSymbol.UnknownResultType, NullableFlowState.NotNull); /// <summary> /// Contains the map of expressions to inferred nullabilities and types used by the optional rewriter phase of the /// compiler. /// </summary> private readonly ImmutableDictionary<BoundExpression, (NullabilityInfo Info, TypeSymbol? Type)>.Builder? _analyzedNullabilityMapOpt; /// <summary> /// Manages creating snapshots of the walker as appropriate. Null if we're not taking snapshots of /// this walker. /// </summary> private readonly SnapshotManager.Builder? _snapshotBuilderOpt; // https://github.com/dotnet/roslyn/issues/35043: remove this when all expression are supported private bool _disableNullabilityAnalysis; /// <summary> /// State of method group receivers, used later when analyzing the conversion to a delegate. /// (Could be replaced by _analyzedNullabilityMapOpt if that map is always available.) /// </summary> private PooledDictionary<BoundExpression, TypeWithState>? _methodGroupReceiverMapOpt; /// <summary> /// State of awaitable expressions, for substitution in placeholders within GetAwaiter calls. /// </summary> private PooledDictionary<BoundAwaitableValuePlaceholder, (BoundExpression AwaitableExpression, VisitResult Result)>? _awaitablePlaceholdersOpt; /// <summary> /// Variables instances for each lambda or local function defined within the analyzed region. /// </summary> private PooledDictionary<MethodSymbol, Variables>? _nestedFunctionVariables; private PooledDictionary<BoundExpression, ImmutableArray<(LocalState State, TypeWithState ResultType, bool EndReachable)>>? _conditionalInfoForConversionOpt; /// <summary> /// Map from a target-typed conditional expression (such as a target-typed conditional or switch) to the nullable state on each branch. This /// is then used by VisitConversion to properly set the state before each branch when visiting a conversion applied to such a construct. These /// states will be the state after visiting the underlying arm value, but before visiting the conversion on top of the arm value. /// </summary> private PooledDictionary<BoundExpression, ImmutableArray<(LocalState State, TypeWithState ResultType, bool EndReachable)>> ConditionalInfoForConversion => _conditionalInfoForConversionOpt ??= PooledDictionary<BoundExpression, ImmutableArray<(LocalState, TypeWithState, bool)>>.GetInstance(); /// <summary> /// True if we're analyzing speculative code. This turns off some initialization steps /// that would otherwise be taken. /// </summary> private readonly bool _isSpeculative; /// <summary> /// True if this walker was created using an initial state. /// </summary> private readonly bool _hasInitialState; #if DEBUG /// <summary> /// Contains the expressions that should not be inserted into <see cref="_analyzedNullabilityMapOpt"/>. /// </summary> private static readonly ImmutableArray<BoundKind> s_skippedExpressions = ImmutableArray.Create(BoundKind.ArrayInitialization, BoundKind.ObjectInitializerExpression, BoundKind.CollectionInitializerExpression, BoundKind.DynamicCollectionElementInitializer); #endif /// <summary> /// The result and l-value type of the last visited expression. /// </summary> private VisitResult _visitResult; /// <summary> /// The visit result of the receiver for the current conditional access. /// /// For example: A conditional invocation uses a placeholder as a receiver. By storing the /// visit result from the actual receiver ahead of time, we can give this placeholder a correct result. /// </summary> private VisitResult _currentConditionalReceiverVisitResult; /// <summary> /// The result type represents the state of the last visited expression. /// </summary> private TypeWithState ResultType { get => _visitResult.RValueType; } private void SetResultType(BoundExpression? expression, TypeWithState type, bool updateAnalyzedNullability = true) { SetResult(expression, resultType: type, lvalueType: type.ToTypeWithAnnotations(compilation), updateAnalyzedNullability: updateAnalyzedNullability); } /// <summary> /// Force the inference of the LValueResultType from ResultType. /// </summary> private void UseRvalueOnly(BoundExpression? expression) { SetResult(expression, ResultType, ResultType.ToTypeWithAnnotations(compilation), isLvalue: false); } private TypeWithAnnotations LvalueResultType { get => _visitResult.LValueType; } private void SetLvalueResultType(BoundExpression? expression, TypeWithAnnotations type) { SetResult(expression, resultType: type.ToTypeWithState(), lvalueType: type); } /// <summary> /// Force the inference of the ResultType from LValueResultType. /// </summary> private void UseLvalueOnly(BoundExpression? expression) { SetResult(expression, LvalueResultType.ToTypeWithState(), LvalueResultType, isLvalue: true); } private void SetInvalidResult() => SetResult(expression: null, _invalidType, _invalidType.ToTypeWithAnnotations(compilation), updateAnalyzedNullability: false); private void SetResult(BoundExpression? expression, TypeWithState resultType, TypeWithAnnotations lvalueType, bool updateAnalyzedNullability = true, bool? isLvalue = null) { _visitResult = new VisitResult(resultType, lvalueType); if (updateAnalyzedNullability) { SetAnalyzedNullability(expression, _visitResult, isLvalue); } } private bool ShouldMakeNotNullRvalue(BoundExpression node) => node.IsSuppressed || node.HasAnyErrors || !IsReachable(); /// <summary> /// Sets the analyzed nullability of the expression to be the given result. /// </summary> private void SetAnalyzedNullability(BoundExpression? expr, VisitResult result, bool? isLvalue = null) { if (expr == null || _disableNullabilityAnalysis) return; #if DEBUG // https://github.com/dotnet/roslyn/issues/34993: This assert is essential for ensuring that we aren't // changing the observable results of GetTypeInfo beyond nullability information. //Debug.Assert(AreCloseEnough(expr.Type, result.RValueType.Type), // $"Cannot change the type of {expr} from {expr.Type} to {result.RValueType.Type}"); #endif if (_analyzedNullabilityMapOpt != null) { // https://github.com/dotnet/roslyn/issues/34993: enable and verify these assertions #if false if (_analyzedNullabilityMapOpt.TryGetValue(expr, out var existing)) { if (!(result.RValueType.State == NullableFlowState.NotNull && ShouldMakeNotNullRvalue(expr, State.Reachable))) { switch (isLvalue) { case true: Debug.Assert(existing.Info.Annotation == result.LValueType.NullableAnnotation.ToPublicAnnotation(), $"Tried to update the nullability of {expr} from {existing.Info.Annotation} to {result.LValueType.NullableAnnotation}"); break; case false: Debug.Assert(existing.Info.FlowState == result.RValueType.State, $"Tried to update the nullability of {expr} from {existing.Info.FlowState} to {result.RValueType.State}"); break; case null: Debug.Assert(existing.Info.Equals((NullabilityInfo)result), $"Tried to update the nullability of {expr} from ({existing.Info.Annotation}, {existing.Info.FlowState}) to ({result.LValueType.NullableAnnotation}, {result.RValueType.State})"); break; } } } #endif _analyzedNullabilityMapOpt[expr] = (new NullabilityInfo(result.LValueType.ToPublicAnnotation(), result.RValueType.State.ToPublicFlowState()), // https://github.com/dotnet/roslyn/issues/35046 We're dropping the result if the type doesn't match up completely // with the existing type expr.Type?.Equals(result.RValueType.Type, TypeCompareKind.AllIgnoreOptions) == true ? result.RValueType.Type : expr.Type); } } /// <summary> /// Placeholder locals, e.g. for objects being constructed. /// </summary> private PooledDictionary<object, PlaceholderLocal>? _placeholderLocalsOpt; /// <summary> /// For methods with annotations, we'll need to visit the arguments twice. /// Once for diagnostics and once for result state (but disabling diagnostics). /// </summary> private bool _disableDiagnostics = false; /// <summary> /// Whether we are going to read the currently visited expression. /// </summary> private bool _expressionIsRead = true; /// <summary> /// Used to allow <see cref="MakeSlot(BoundExpression)"/> to substitute the correct slot for a <see cref="BoundConditionalReceiver"/> when /// it's encountered. /// </summary> private int _lastConditionalAccessSlot = -1; private bool IsAnalyzingAttribute => methodMainNode.Kind == BoundKind.Attribute; protected override void Free() { _nestedFunctionVariables?.Free(); _awaitablePlaceholdersOpt?.Free(); _methodGroupReceiverMapOpt?.Free(); _placeholderLocalsOpt?.Free(); _variables.Free(); Debug.Assert(_conditionalInfoForConversionOpt is null or { Count: 0 }); _conditionalInfoForConversionOpt?.Free(); base.Free(); } private NullableWalker( CSharpCompilation compilation, Symbol? symbol, bool useConstructorExitWarnings, bool useDelegateInvokeParameterTypes, bool useDelegateInvokeReturnType, MethodSymbol? delegateInvokeMethodOpt, BoundNode node, Binder binder, Conversions conversions, Variables? variables, ArrayBuilder<(BoundReturnStatement, TypeWithAnnotations)>? returnTypesOpt, ImmutableDictionary<BoundExpression, (NullabilityInfo, TypeSymbol?)>.Builder? analyzedNullabilityMapOpt, SnapshotManager.Builder? snapshotBuilderOpt, bool isSpeculative = false) : base(compilation, symbol, node, EmptyStructTypeCache.CreatePrecise(), trackUnassignments: true) { Debug.Assert(!useDelegateInvokeParameterTypes || delegateInvokeMethodOpt is object); _variables = variables ?? Variables.Create(symbol); _binder = binder; _conversions = (Conversions)conversions.WithNullability(true); _useConstructorExitWarnings = useConstructorExitWarnings; _useDelegateInvokeParameterTypes = useDelegateInvokeParameterTypes; _useDelegateInvokeReturnType = useDelegateInvokeReturnType; _delegateInvokeMethod = delegateInvokeMethodOpt; _analyzedNullabilityMapOpt = analyzedNullabilityMapOpt; _returnTypesOpt = returnTypesOpt; _snapshotBuilderOpt = snapshotBuilderOpt; _isSpeculative = isSpeculative; _hasInitialState = variables is { }; } public string GetDebuggerDisplay() { if (this.IsConditionalState) { return $"{{{GetType().Name} WhenTrue:{Dump(StateWhenTrue)} WhenFalse:{Dump(StateWhenFalse)}{"}"}"; } else { return $"{{{GetType().Name} {Dump(State)}{"}"}"; } } // For purpose of nullability analysis, awaits create pending branches, so async usings and foreachs do too public sealed override bool AwaitUsingAndForeachAddsPendingBranch => true; protected override void EnsureSufficientExecutionStack(int recursionDepth) { if (recursionDepth > StackGuard.MaxUncheckedRecursionDepth && compilation.NullableAnalysisData is { MaxRecursionDepth: var depth } && depth > 0 && recursionDepth > depth) { throw new InsufficientExecutionStackException(); } base.EnsureSufficientExecutionStack(recursionDepth); } protected override bool ConvertInsufficientExecutionStackExceptionToCancelledByStackGuardException() { return true; } protected override bool TryGetVariable(VariableIdentifier identifier, out int slot) { return _variables.TryGetValue(identifier, out slot); } protected override int AddVariable(VariableIdentifier identifier) { return _variables.Add(identifier); } protected override ImmutableArray<PendingBranch> Scan(ref bool badRegion) { if (_returnTypesOpt != null) { _returnTypesOpt.Clear(); } this.Diagnostics.Clear(); this.regionPlace = RegionPlace.Before; if (!_isSpeculative) { ParameterSymbol methodThisParameter = MethodThisParameter; EnterParameters(); // assign parameters if (methodThisParameter is object) { EnterParameter(methodThisParameter, methodThisParameter.TypeWithAnnotations); } makeNotNullMembersMaybeNull(); // We need to create a snapshot even of the first node, because we want to have the state of the initial parameters. _snapshotBuilderOpt?.TakeIncrementalSnapshot(methodMainNode, State); } ImmutableArray<PendingBranch> pendingReturns = base.Scan(ref badRegion); if ((_symbol as MethodSymbol)?.IsConstructor() != true || _useConstructorExitWarnings) { EnforceDoesNotReturn(syntaxOpt: null); enforceMemberNotNull(syntaxOpt: null, this.State); enforceNotNull(null, this.State); foreach (var pendingReturn in pendingReturns) { enforceMemberNotNull(syntaxOpt: pendingReturn.Branch.Syntax, pendingReturn.State); if (pendingReturn.Branch is BoundReturnStatement returnStatement) { enforceNotNull(returnStatement.Syntax, pendingReturn.State); enforceNotNullWhenForPendingReturn(pendingReturn, returnStatement); enforceMemberNotNullWhenForPendingReturn(pendingReturn, returnStatement); } } } return pendingReturns; void enforceMemberNotNull(SyntaxNode? syntaxOpt, LocalState state) { if (!state.Reachable) { return; } var method = _symbol as MethodSymbol; if (method is object) { if (method.IsConstructor()) { Debug.Assert(_useConstructorExitWarnings); var thisSlot = 0; if (method.RequiresInstanceReceiver) { method.TryGetThisParameter(out var thisParameter); Debug.Assert(thisParameter is object); thisSlot = GetOrCreateSlot(thisParameter); } // https://github.com/dotnet/roslyn/issues/46718: give diagnostics on return points, not constructor signature var exitLocation = method.DeclaringSyntaxReferences.IsEmpty ? null : method.Locations.FirstOrDefault(); foreach (var member in method.ContainingType.GetMembersUnordered()) { checkMemberStateOnConstructorExit(method, member, state, thisSlot, exitLocation); } } else { do { foreach (var memberName in method.NotNullMembers) { enforceMemberNotNullOnMember(syntaxOpt, state, method, memberName); } method = method.OverriddenMethod; } while (method != null); } } } void checkMemberStateOnConstructorExit(MethodSymbol constructor, Symbol member, LocalState state, int thisSlot, Location? exitLocation) { var isStatic = !constructor.RequiresInstanceReceiver(); if (member.IsStatic != isStatic) { return; } // This is not required for correctness, but in the case where the member has // an initializer, we know we've assigned to the member and // have given any applicable warnings about a bad value going in. // Therefore we skip this check when the member has an initializer to reduce noise. if (HasInitializer(member)) { return; } TypeWithAnnotations fieldType; FieldSymbol? field; Symbol symbol; switch (member) { case FieldSymbol f: fieldType = f.TypeWithAnnotations; field = f; symbol = (Symbol?)(f.AssociatedSymbol as PropertySymbol) ?? f; break; case EventSymbol e: fieldType = e.TypeWithAnnotations; field = e.AssociatedField; symbol = e; if (field is null) { return; } break; default: return; } if (field.IsConst) { return; } if (fieldType.Type.IsValueType || fieldType.Type.IsErrorType()) { return; } var annotations = symbol.GetFlowAnalysisAnnotations(); if ((annotations & FlowAnalysisAnnotations.AllowNull) != 0) { // We assume that if a member has AllowNull then the user // does not care that we exit at a point where the member might be null. return; } fieldType = ApplyUnconditionalAnnotations(fieldType, annotations); if (!fieldType.NullableAnnotation.IsNotAnnotated()) { return; } var slot = GetOrCreateSlot(symbol, thisSlot); if (slot < 0) { return; } var memberState = state[slot]; var badState = fieldType.Type.IsPossiblyNullableReferenceTypeTypeParameter() && (annotations & FlowAnalysisAnnotations.NotNull) == 0 ? NullableFlowState.MaybeDefault : NullableFlowState.MaybeNull; if (memberState >= badState) // is 'memberState' as bad as or worse than 'badState'? { Diagnostics.Add(ErrorCode.WRN_UninitializedNonNullableField, exitLocation ?? symbol.Locations.FirstOrNone(), symbol.Kind.Localize(), symbol.Name); } } void enforceMemberNotNullOnMember(SyntaxNode? syntaxOpt, LocalState state, MethodSymbol method, string memberName) { foreach (var member in method.ContainingType.GetMembers(memberName)) { if (memberHasBadState(member, state)) { // Member '{name}' must have a non-null value when exiting. Diagnostics.Add(ErrorCode.WRN_MemberNotNull, syntaxOpt?.GetLocation() ?? methodMainNode.Syntax.GetLastToken().GetLocation(), member.Name); } } } void enforceMemberNotNullWhenForPendingReturn(PendingBranch pendingReturn, BoundReturnStatement returnStatement) { if (pendingReturn.IsConditionalState) { if (returnStatement.ExpressionOpt is { ConstantValue: { IsBoolean: true, BooleanValue: bool value } }) { enforceMemberNotNullWhen(returnStatement.Syntax, sense: value, pendingReturn.State); return; } if (!pendingReturn.StateWhenTrue.Reachable || !pendingReturn.StateWhenFalse.Reachable) { return; } if (_symbol is MethodSymbol method) { foreach (var memberName in method.NotNullWhenTrueMembers) { enforceMemberNotNullWhenIfAffected(returnStatement.Syntax, sense: true, method.ContainingType.GetMembers(memberName), pendingReturn.StateWhenTrue, pendingReturn.StateWhenFalse); } foreach (var memberName in method.NotNullWhenFalseMembers) { enforceMemberNotNullWhenIfAffected(returnStatement.Syntax, sense: false, method.ContainingType.GetMembers(memberName), pendingReturn.StateWhenFalse, pendingReturn.StateWhenTrue); } } } else if (returnStatement.ExpressionOpt is { ConstantValue: { IsBoolean: true, BooleanValue: bool value } }) { enforceMemberNotNullWhen(returnStatement.Syntax, sense: value, pendingReturn.State); } } void enforceMemberNotNullWhenIfAffected(SyntaxNode? syntaxOpt, bool sense, ImmutableArray<Symbol> members, LocalState state, LocalState otherState) { foreach (var member in members) { // For non-constant values, only complain if we were able to analyze a difference for this member between two branches if (memberHasBadState(member, state) != memberHasBadState(member, otherState)) { reportMemberIfBadConditionalState(syntaxOpt, sense, member, state); } } } void enforceMemberNotNullWhen(SyntaxNode? syntaxOpt, bool sense, LocalState state) { if (_symbol is MethodSymbol method) { var notNullMembers = sense ? method.NotNullWhenTrueMembers : method.NotNullWhenFalseMembers; foreach (var memberName in notNullMembers) { foreach (var member in method.ContainingType.GetMembers(memberName)) { reportMemberIfBadConditionalState(syntaxOpt, sense, member, state); } } } } void reportMemberIfBadConditionalState(SyntaxNode? syntaxOpt, bool sense, Symbol member, LocalState state) { if (memberHasBadState(member, state)) { // Member '{name}' must have a non-null value when exiting with '{sense}'. Diagnostics.Add(ErrorCode.WRN_MemberNotNullWhen, syntaxOpt?.GetLocation() ?? methodMainNode.Syntax.GetLastToken().GetLocation(), member.Name, sense ? "true" : "false"); } } bool memberHasBadState(Symbol member, LocalState state) { switch (member.Kind) { case SymbolKind.Field: case SymbolKind.Property: if (getSlotForFieldOrPropertyOrEvent(member) is int memberSlot && memberSlot > 0) { var parameterState = state[memberSlot]; return !parameterState.IsNotNull(); } else { return false; } case SymbolKind.Event: case SymbolKind.Method: break; } return false; } void makeNotNullMembersMaybeNull() { if (_symbol is MethodSymbol method) { if (method.IsConstructor()) { if (needsDefaultInitialStateForMembers()) { foreach (var member in method.ContainingType.GetMembersUnordered()) { if (member.IsStatic != method.IsStatic) { continue; } var memberToInitialize = member; switch (member) { case PropertySymbol: // skip any manually implemented properties. continue; case FieldSymbol { IsConst: true }: continue; case FieldSymbol { AssociatedSymbol: PropertySymbol prop }: // this is a property where assigning 'default' causes us to simply update // the state to the output state of the property // thus we skip setting an initial state for it here if (IsPropertyOutputMoreStrictThanInput(prop)) { continue; } // We want to initialize auto-property state to the default state, but not computed properties. memberToInitialize = prop; break; default: break; } var memberSlot = getSlotForFieldOrPropertyOrEvent(memberToInitialize); if (memberSlot > 0) { var type = memberToInitialize.GetTypeOrReturnType(); if (!type.NullableAnnotation.IsOblivious()) { this.State[memberSlot] = type.Type.IsPossiblyNullableReferenceTypeTypeParameter() ? NullableFlowState.MaybeDefault : NullableFlowState.MaybeNull; } } } } } else { do { makeMembersMaybeNull(method, method.NotNullMembers); makeMembersMaybeNull(method, method.NotNullWhenTrueMembers); makeMembersMaybeNull(method, method.NotNullWhenFalseMembers); method = method.OverriddenMethod; } while (method != null); } } bool needsDefaultInitialStateForMembers() { if (_hasInitialState) { return false; } // We don't use a default initial state for value type instance constructors without `: this()` because // any usages of uninitialized fields will get definite assignment errors anyway. if (!method.HasThisConstructorInitializer(out _) && (!method.ContainingType.IsValueType || method.IsStatic)) { return true; } return method.IncludeFieldInitializersInBody(); } } void makeMembersMaybeNull(MethodSymbol method, ImmutableArray<string> members) { foreach (var memberName in members) { makeMemberMaybeNull(method, memberName); } } void makeMemberMaybeNull(MethodSymbol method, string memberName) { var type = method.ContainingType; foreach (var member in type.GetMembers(memberName)) { if (getSlotForFieldOrPropertyOrEvent(member) is int memberSlot && memberSlot > 0) { this.State[memberSlot] = NullableFlowState.MaybeNull; } } } void enforceNotNullWhenForPendingReturn(PendingBranch pendingReturn, BoundReturnStatement returnStatement) { var parameters = this.MethodParameters; if (!parameters.IsEmpty) { if (pendingReturn.IsConditionalState) { if (returnStatement.ExpressionOpt is { ConstantValue: { IsBoolean: true, BooleanValue: bool value } }) { enforceParameterNotNullWhen(returnStatement.Syntax, parameters, sense: value, stateWhen: pendingReturn.State); return; } if (!pendingReturn.StateWhenTrue.Reachable || !pendingReturn.StateWhenFalse.Reachable) { return; } foreach (var parameter in parameters) { // For non-constant values, only complain if we were able to analyze a difference for this parameter between two branches if (GetOrCreateSlot(parameter) is > 0 and var slot && pendingReturn.StateWhenTrue[slot] != pendingReturn.StateWhenFalse[slot]) { reportParameterIfBadConditionalState(returnStatement.Syntax, parameter, sense: true, stateWhen: pendingReturn.StateWhenTrue); reportParameterIfBadConditionalState(returnStatement.Syntax, parameter, sense: false, stateWhen: pendingReturn.StateWhenFalse); } } } else if (returnStatement.ExpressionOpt is { ConstantValue: { IsBoolean: true, BooleanValue: bool value } }) { // example: return (bool)true; enforceParameterNotNullWhen(returnStatement.Syntax, parameters, sense: value, stateWhen: pendingReturn.State); return; } } } void reportParameterIfBadConditionalState(SyntaxNode syntax, ParameterSymbol parameter, bool sense, LocalState stateWhen) { if (parameterHasBadConditionalState(parameter, sense, stateWhen)) { // Parameter '{name}' must have a non-null value when exiting with '{sense}'. Diagnostics.Add(ErrorCode.WRN_ParameterConditionallyDisallowsNull, syntax.Location, parameter.Name, sense ? "true" : "false"); } } void enforceNotNull(SyntaxNode? syntaxOpt, LocalState state) { if (!state.Reachable) { return; } foreach (var parameter in this.MethodParameters) { var slot = GetOrCreateSlot(parameter); if (slot <= 0) { continue; } var annotations = parameter.FlowAnalysisAnnotations; var hasNotNull = (annotations & FlowAnalysisAnnotations.NotNull) == FlowAnalysisAnnotations.NotNull; var parameterState = state[slot]; if (hasNotNull && parameterState.MayBeNull()) { // Parameter '{name}' must have a non-null value when exiting. Diagnostics.Add(ErrorCode.WRN_ParameterDisallowsNull, syntaxOpt?.GetLocation() ?? methodMainNode.Syntax.GetLastToken().GetLocation(), parameter.Name); } else { EnforceNotNullIfNotNull(syntaxOpt, state, this.MethodParameters, parameter.NotNullIfParameterNotNull, parameterState, parameter); } } } void enforceParameterNotNullWhen(SyntaxNode syntax, ImmutableArray<ParameterSymbol> parameters, bool sense, LocalState stateWhen) { if (!stateWhen.Reachable) { return; } foreach (var parameter in parameters) { reportParameterIfBadConditionalState(syntax, parameter, sense, stateWhen); } } bool parameterHasBadConditionalState(ParameterSymbol parameter, bool sense, LocalState stateWhen) { var refKind = parameter.RefKind; if (refKind != RefKind.Out && refKind != RefKind.Ref) { return false; } var slot = GetOrCreateSlot(parameter); if (slot > 0) { var parameterState = stateWhen[slot]; // On a parameter marked with MaybeNullWhen, we would have not reported an assignment warning. // We should only check if an assignment warning would have been warranted ignoring the MaybeNullWhen. FlowAnalysisAnnotations annotations = parameter.FlowAnalysisAnnotations; if (sense) { bool hasNotNullWhenTrue = (annotations & FlowAnalysisAnnotations.NotNull) == FlowAnalysisAnnotations.NotNullWhenTrue; bool hasMaybeNullWhenFalse = (annotations & FlowAnalysisAnnotations.MaybeNull) == FlowAnalysisAnnotations.MaybeNullWhenFalse; return (hasNotNullWhenTrue && parameterState.MayBeNull()) || (hasMaybeNullWhenFalse && ShouldReportNullableAssignment(parameter.TypeWithAnnotations, parameterState)); } else { bool hasNotNullWhenFalse = (annotations & FlowAnalysisAnnotations.NotNull) == FlowAnalysisAnnotations.NotNullWhenFalse; bool hasMaybeNullWhenTrue = (annotations & FlowAnalysisAnnotations.MaybeNull) == FlowAnalysisAnnotations.MaybeNullWhenTrue; return (hasNotNullWhenFalse && parameterState.MayBeNull()) || (hasMaybeNullWhenTrue && ShouldReportNullableAssignment(parameter.TypeWithAnnotations, parameterState)); } } return false; } int getSlotForFieldOrPropertyOrEvent(Symbol member) { if (member.Kind != SymbolKind.Field && member.Kind != SymbolKind.Property && member.Kind != SymbolKind.Event) { return -1; } int containingSlot = 0; if (!member.IsStatic) { if (MethodThisParameter is null) { return -1; } containingSlot = GetOrCreateSlot(MethodThisParameter); if (containingSlot < 0) { return -1; } Debug.Assert(containingSlot > 0); } return GetOrCreateSlot(member, containingSlot); } } private void EnforceNotNullIfNotNull(SyntaxNode? syntaxOpt, LocalState state, ImmutableArray<ParameterSymbol> parameters, ImmutableHashSet<string> inputParamNames, NullableFlowState outputState, ParameterSymbol? outputParam) { if (inputParamNames.IsEmpty || outputState.IsNotNull()) { return; } foreach (var inputParam in parameters) { if (inputParamNames.Contains(inputParam.Name) && GetOrCreateSlot(inputParam) is > 0 and int inputSlot && state[inputSlot].IsNotNull()) { var location = syntaxOpt?.GetLocation() ?? methodMainNode.Syntax.GetLastToken().GetLocation(); if (outputParam is object) { // Parameter '{0}' must have a non-null value when exiting because parameter '{1}' is non-null. Diagnostics.Add(ErrorCode.WRN_ParameterNotNullIfNotNull, location, outputParam.Name, inputParam.Name); } else if (CurrentSymbol is MethodSymbol { IsAsync: false }) { // Return value must be non-null because parameter '{0}' is non-null. Diagnostics.Add(ErrorCode.WRN_ReturnNotNullIfNotNull, location, inputParam.Name); } break; } } } private void EnforceDoesNotReturn(SyntaxNode? syntaxOpt) { // DoesNotReturn is only supported in member methods if (CurrentSymbol is MethodSymbol { ContainingSymbol: TypeSymbol _ } method && ((method.FlowAnalysisAnnotations & FlowAnalysisAnnotations.DoesNotReturn) == FlowAnalysisAnnotations.DoesNotReturn) && this.IsReachable()) { // A method marked [DoesNotReturn] should not return. ReportDiagnostic(ErrorCode.WRN_ShouldNotReturn, syntaxOpt?.GetLocation() ?? methodMainNode.Syntax.GetLastToken().GetLocation()); } } /// <summary> /// Analyzes a method body if settings indicate we should. /// </summary> internal static void AnalyzeIfNeeded( CSharpCompilation compilation, MethodSymbol method, BoundNode node, DiagnosticBag diagnostics, bool useConstructorExitWarnings, VariableState? initialNullableState, bool getFinalNullableState, out VariableState? finalNullableState) { if (!HasRequiredLanguageVersion(compilation) || !compilation.IsNullableAnalysisEnabledIn(method)) { if (compilation.IsNullableAnalysisEnabledAlways) { // Once we address https://github.com/dotnet/roslyn/issues/46579 we should also always pass `getFinalNullableState: true` in debug mode. // We will likely always need to write a 'null' out for the out parameter in this code path, though, because // we don't want to introduce behavior differences between debug and release builds Analyze(compilation, method, node, new DiagnosticBag(), useConstructorExitWarnings: false, initialNullableState: null, getFinalNullableState: false, out _, requiresAnalysis: false); } finalNullableState = null; return; } Analyze(compilation, method, node, diagnostics, useConstructorExitWarnings, initialNullableState, getFinalNullableState, out finalNullableState); } private static void Analyze( CSharpCompilation compilation, MethodSymbol method, BoundNode node, DiagnosticBag diagnostics, bool useConstructorExitWarnings, VariableState? initialNullableState, bool getFinalNullableState, out VariableState? finalNullableState, bool requiresAnalysis = true) { if (method.IsImplicitlyDeclared && !method.IsImplicitConstructor && !method.IsScriptInitializer) { finalNullableState = null; return; } Debug.Assert(node.SyntaxTree is object); var binder = method is SynthesizedSimpleProgramEntryPointSymbol entryPoint ? entryPoint.GetBodyBinder(ignoreAccessibility: false) : compilation.GetBinderFactory(node.SyntaxTree).GetBinder(node.Syntax); var conversions = binder.Conversions; Analyze(compilation, method, node, binder, conversions, diagnostics, useConstructorExitWarnings, useDelegateInvokeParameterTypes: false, useDelegateInvokeReturnType: false, delegateInvokeMethodOpt: null, initialState: initialNullableState, analyzedNullabilityMapOpt: null, snapshotBuilderOpt: null, returnTypesOpt: null, getFinalNullableState, finalNullableState: out finalNullableState, requiresAnalysis); } /// <summary> /// Gets the "after initializers state" which should be used at the beginning of nullable analysis /// of certain constructors. Only used for semantic model and debug verification. /// </summary> internal static VariableState? GetAfterInitializersState(CSharpCompilation compilation, Symbol? symbol) { if (symbol is MethodSymbol method && method.IncludeFieldInitializersInBody() && method.ContainingType is SourceMemberContainerTypeSymbol containingType) { var unusedDiagnostics = DiagnosticBag.GetInstance(); Binder.ProcessedFieldInitializers initializers = default; Binder.BindFieldInitializers(compilation, null, method.IsStatic ? containingType.StaticInitializers : containingType.InstanceInitializers, BindingDiagnosticBag.Discarded, ref initializers); NullableWalker.AnalyzeIfNeeded( compilation, method, InitializerRewriter.RewriteConstructor(initializers.BoundInitializers, method), unusedDiagnostics, useConstructorExitWarnings: false, initialNullableState: null, getFinalNullableState: true, out var afterInitializersState); unusedDiagnostics.Free(); return afterInitializersState; } return null; } /// <summary> /// Analyzes a set of bound nodes, recording updated nullability information. This method is only /// used when nullable is explicitly enabled for all methods but disabled otherwise to verify that /// correct semantic information is being recorded for all bound nodes. The results are thrown away. /// </summary> internal static void AnalyzeWithoutRewrite( CSharpCompilation compilation, Symbol? symbol, BoundNode node, Binder binder, DiagnosticBag diagnostics, bool createSnapshots) { _ = AnalyzeWithSemanticInfo(compilation, symbol, node, binder, initialState: GetAfterInitializersState(compilation, symbol), diagnostics, createSnapshots, requiresAnalysis: false); } /// <summary> /// Analyzes a set of bound nodes, recording updated nullability information, and returns an /// updated BoundNode with the information populated. /// </summary> internal static BoundNode AnalyzeAndRewrite( CSharpCompilation compilation, Symbol? symbol, BoundNode node, Binder binder, VariableState? initialState, DiagnosticBag diagnostics, bool createSnapshots, out SnapshotManager? snapshotManager, ref ImmutableDictionary<Symbol, Symbol>? remappedSymbols) { ImmutableDictionary<BoundExpression, (NullabilityInfo, TypeSymbol?)> analyzedNullabilitiesMap; (snapshotManager, analyzedNullabilitiesMap) = AnalyzeWithSemanticInfo(compilation, symbol, node, binder, initialState, diagnostics, createSnapshots, requiresAnalysis: true); return Rewrite(analyzedNullabilitiesMap, snapshotManager, node, ref remappedSymbols); } private static (SnapshotManager?, ImmutableDictionary<BoundExpression, (NullabilityInfo, TypeSymbol?)>) AnalyzeWithSemanticInfo( CSharpCompilation compilation, Symbol? symbol, BoundNode node, Binder binder, VariableState? initialState, DiagnosticBag diagnostics, bool createSnapshots, bool requiresAnalysis) { var analyzedNullabilities = ImmutableDictionary.CreateBuilder<BoundExpression, (NullabilityInfo, TypeSymbol?)>(EqualityComparer<BoundExpression>.Default, NullabilityInfoTypeComparer.Instance); // Attributes don't have a symbol, which is what SnapshotBuilder uses as an index for maintaining global state. // Until we have a workaround for this, disable snapshots for null symbols. // https://github.com/dotnet/roslyn/issues/36066 var snapshotBuilder = createSnapshots && symbol != null ? new SnapshotManager.Builder() : null; Analyze( compilation, symbol, node, binder, binder.Conversions, diagnostics, useConstructorExitWarnings: true, useDelegateInvokeParameterTypes: false, useDelegateInvokeReturnType: false, delegateInvokeMethodOpt: null, initialState, analyzedNullabilities, snapshotBuilder, returnTypesOpt: null, getFinalNullableState: false, out _, requiresAnalysis); var analyzedNullabilitiesMap = analyzedNullabilities.ToImmutable(); var snapshotManager = snapshotBuilder?.ToManagerAndFree(); #if DEBUG // https://github.com/dotnet/roslyn/issues/34993 Enable for all calls if (isNullableAnalysisEnabledAnywhere(compilation)) { DebugVerifier.Verify(analyzedNullabilitiesMap, snapshotManager, node); } static bool isNullableAnalysisEnabledAnywhere(CSharpCompilation compilation) { if (compilation.Options.NullableContextOptions != NullableContextOptions.Disable) { return true; } return compilation.SyntaxTrees.Any(tree => ((CSharpSyntaxTree)tree).IsNullableAnalysisEnabled(new Text.TextSpan(0, tree.Length)) == true); } #endif return (snapshotManager, analyzedNullabilitiesMap); } internal static BoundNode AnalyzeAndRewriteSpeculation( int position, BoundNode node, Binder binder, SnapshotManager originalSnapshots, out SnapshotManager newSnapshots, ref ImmutableDictionary<Symbol, Symbol>? remappedSymbols) { var analyzedNullabilities = ImmutableDictionary.CreateBuilder<BoundExpression, (NullabilityInfo, TypeSymbol?)>(EqualityComparer<BoundExpression>.Default, NullabilityInfoTypeComparer.Instance); var newSnapshotBuilder = new SnapshotManager.Builder(); var (variables, localState) = originalSnapshots.GetSnapshot(position); var symbol = variables.Symbol; var walker = new NullableWalker( binder.Compilation, symbol, useConstructorExitWarnings: false, useDelegateInvokeParameterTypes: false, useDelegateInvokeReturnType: false, delegateInvokeMethodOpt: null, node, binder, binder.Conversions, Variables.Create(variables), returnTypesOpt: null, analyzedNullabilities, newSnapshotBuilder, isSpeculative: true); try { Analyze(walker, symbol, diagnostics: null, LocalState.Create(localState), snapshotBuilderOpt: newSnapshotBuilder); } finally { walker.Free(); } var analyzedNullabilitiesMap = analyzedNullabilities.ToImmutable(); newSnapshots = newSnapshotBuilder.ToManagerAndFree(); #if DEBUG DebugVerifier.Verify(analyzedNullabilitiesMap, newSnapshots, node); #endif return Rewrite(analyzedNullabilitiesMap, newSnapshots, node, ref remappedSymbols); } private static BoundNode Rewrite(ImmutableDictionary<BoundExpression, (NullabilityInfo, TypeSymbol?)> updatedNullabilities, SnapshotManager? snapshotManager, BoundNode node, ref ImmutableDictionary<Symbol, Symbol>? remappedSymbols) { var remappedSymbolsBuilder = ImmutableDictionary.CreateBuilder<Symbol, Symbol>(Symbols.SymbolEqualityComparer.ConsiderEverything, Symbols.SymbolEqualityComparer.ConsiderEverything); if (remappedSymbols is object) { // When we're rewriting for the speculative model, there will be a set of originally-mapped symbols, and we need to // use them in addition to any symbols found during this pass of the walker. remappedSymbolsBuilder.AddRange(remappedSymbols); } var rewriter = new NullabilityRewriter(updatedNullabilities, snapshotManager, remappedSymbolsBuilder); var rewrittenNode = rewriter.Visit(node); remappedSymbols = remappedSymbolsBuilder.ToImmutable(); return rewrittenNode; } private static bool HasRequiredLanguageVersion(CSharpCompilation compilation) { return compilation.LanguageVersion >= MessageID.IDS_FeatureNullableReferenceTypes.RequiredVersion(); } /// <summary> /// Returns true if the nullable analysis is needed for the region represented by <paramref name="syntaxNode"/>. /// The syntax node is used to determine the overall nullable context for the region. /// </summary> internal static bool NeedsAnalysis(CSharpCompilation compilation, SyntaxNode syntaxNode) { return HasRequiredLanguageVersion(compilation) && (compilation.IsNullableAnalysisEnabledIn(syntaxNode) || compilation.IsNullableAnalysisEnabledAlways); } /// <summary>Analyzes a node in a "one-off" context, such as for attributes or parameter default values.</summary> /// <remarks><paramref name="syntax"/> is the syntax span used to determine the overall nullable context.</remarks> internal static void AnalyzeIfNeeded( Binder binder, BoundNode node, SyntaxNode syntax, DiagnosticBag diagnostics) { bool requiresAnalysis = true; var compilation = binder.Compilation; if (!HasRequiredLanguageVersion(compilation) || !compilation.IsNullableAnalysisEnabledIn(syntax)) { if (!compilation.IsNullableAnalysisEnabledAlways) { return; } diagnostics = new DiagnosticBag(); requiresAnalysis = false; } Analyze( compilation, symbol: null, node, binder, binder.Conversions, diagnostics, useConstructorExitWarnings: false, useDelegateInvokeParameterTypes: false, useDelegateInvokeReturnType: false, delegateInvokeMethodOpt: null, initialState: null, analyzedNullabilityMapOpt: null, snapshotBuilderOpt: null, returnTypesOpt: null, getFinalNullableState: false, out _, requiresAnalysis); } internal static void Analyze( CSharpCompilation compilation, BoundLambda lambda, Conversions conversions, DiagnosticBag diagnostics, MethodSymbol? delegateInvokeMethodOpt, VariableState initialState, ArrayBuilder<(BoundReturnStatement, TypeWithAnnotations)>? returnTypesOpt) { var symbol = lambda.Symbol; var variables = Variables.Create(initialState.Variables).CreateNestedMethodScope(symbol); UseDelegateInvokeParameterAndReturnTypes(lambda, delegateInvokeMethodOpt, out bool useDelegateInvokeParameterTypes, out bool useDelegateInvokeReturnType); var walker = new NullableWalker( compilation, symbol, useConstructorExitWarnings: false, useDelegateInvokeParameterTypes: useDelegateInvokeParameterTypes, useDelegateInvokeReturnType: useDelegateInvokeReturnType, delegateInvokeMethodOpt: delegateInvokeMethodOpt, lambda.Body, lambda.Binder, conversions, variables, returnTypesOpt, analyzedNullabilityMapOpt: null, snapshotBuilderOpt: null); try { var localState = LocalState.Create(initialState.VariableNullableStates).CreateNestedMethodState(variables); Analyze(walker, symbol, diagnostics, localState, snapshotBuilderOpt: null); } finally { walker.Free(); } } private static void Analyze( CSharpCompilation compilation, Symbol? symbol, BoundNode node, Binder binder, Conversions conversions, DiagnosticBag diagnostics, bool useConstructorExitWarnings, bool useDelegateInvokeParameterTypes, bool useDelegateInvokeReturnType, MethodSymbol? delegateInvokeMethodOpt, VariableState? initialState, ImmutableDictionary<BoundExpression, (NullabilityInfo, TypeSymbol?)>.Builder? analyzedNullabilityMapOpt, SnapshotManager.Builder? snapshotBuilderOpt, ArrayBuilder<(BoundReturnStatement, TypeWithAnnotations)>? returnTypesOpt, bool getFinalNullableState, out VariableState? finalNullableState, bool requiresAnalysis = true) { Debug.Assert(diagnostics != null); var walker = new NullableWalker(compilation, symbol, useConstructorExitWarnings, useDelegateInvokeParameterTypes, useDelegateInvokeReturnType, delegateInvokeMethodOpt, node, binder, conversions, initialState is null ? null : Variables.Create(initialState.Variables), returnTypesOpt, analyzedNullabilityMapOpt, snapshotBuilderOpt); finalNullableState = null; try { Analyze(walker, symbol, diagnostics, initialState is null ? (Optional<LocalState>)default : LocalState.Create(initialState.VariableNullableStates), snapshotBuilderOpt, requiresAnalysis); if (getFinalNullableState) { Debug.Assert(!walker.IsConditionalState); finalNullableState = GetVariableState(walker._variables, walker.State); } } finally { walker.Free(); } } private static void Analyze( NullableWalker walker, Symbol? symbol, DiagnosticBag? diagnostics, Optional<LocalState> initialState, SnapshotManager.Builder? snapshotBuilderOpt, bool requiresAnalysis = true) { Debug.Assert(snapshotBuilderOpt is null || symbol is object); var previousSlot = snapshotBuilderOpt?.EnterNewWalker(symbol!) ?? -1; try { bool badRegion = false; ImmutableArray<PendingBranch> returns = walker.Analyze(ref badRegion, initialState); diagnostics?.AddRange(walker.Diagnostics); Debug.Assert(!badRegion); } catch (CancelledByStackGuardException ex) when (diagnostics != null) { ex.AddAnError(diagnostics); } finally { snapshotBuilderOpt?.ExitWalker(walker.SaveSharedState(), previousSlot); } walker.RecordNullableAnalysisData(symbol, requiresAnalysis); } private void RecordNullableAnalysisData(Symbol? symbol, bool requiredAnalysis) { if (compilation.NullableAnalysisData?.Data is { } state) { var key = (object?)symbol ?? methodMainNode.Syntax; if (state.TryGetValue(key, out var result)) { Debug.Assert(result.RequiredAnalysis == requiredAnalysis); } else { state.TryAdd(key, new Data(_variables.GetTotalVariableCount(), requiredAnalysis)); } } } private SharedWalkerState SaveSharedState() { return new SharedWalkerState(_variables.CreateSnapshot()); } private void TakeIncrementalSnapshot(BoundNode? node) { Debug.Assert(!IsConditionalState); _snapshotBuilderOpt?.TakeIncrementalSnapshot(node, State); } private void SetUpdatedSymbol(BoundNode node, Symbol originalSymbol, Symbol updatedSymbol) { if (_snapshotBuilderOpt is null) { return; } var lambdaIsExactMatch = false; if (node is BoundLambda boundLambda && originalSymbol is LambdaSymbol l && updatedSymbol is NamedTypeSymbol n) { if (!AreLambdaAndNewDelegateSimilar(l, n)) { return; } lambdaIsExactMatch = updatedSymbol.Equals(boundLambda.Type!.GetDelegateType(), TypeCompareKind.ConsiderEverything); } #if DEBUG Debug.Assert(node is object); Debug.Assert(AreCloseEnough(originalSymbol, updatedSymbol), $"Attempting to set {node.Syntax} from {originalSymbol.ToDisplayString()} to {updatedSymbol.ToDisplayString()}"); #endif if (lambdaIsExactMatch || Symbol.Equals(originalSymbol, updatedSymbol, TypeCompareKind.ConsiderEverything)) { // If the symbol is reset, remove the updated symbol so we don't needlessly update the // bound node later on. We do this unconditionally, as Remove will just return false // if the key wasn't in the dictionary. _snapshotBuilderOpt.RemoveSymbolIfPresent(node, originalSymbol); } else { _snapshotBuilderOpt.SetUpdatedSymbol(node, originalSymbol, updatedSymbol); } } protected override void Normalize(ref LocalState state) { if (!state.Reachable) return; state.Normalize(this, _variables); } private NullableFlowState GetDefaultState(ref LocalState state, int slot) { Debug.Assert(slot > 0); if (!state.Reachable) return NullableFlowState.NotNull; var variable = _variables[slot]; var symbol = variable.Symbol; switch (symbol.Kind) { case SymbolKind.Local: { var local = (LocalSymbol)symbol; if (!_variables.TryGetType(local, out TypeWithAnnotations localType)) { localType = local.TypeWithAnnotations; } return localType.ToTypeWithState().State; } case SymbolKind.Parameter: { var parameter = (ParameterSymbol)symbol; if (!_variables.TryGetType(parameter, out TypeWithAnnotations parameterType)) { parameterType = parameter.TypeWithAnnotations; } return GetParameterState(parameterType, parameter.FlowAnalysisAnnotations).State; } case SymbolKind.Field: case SymbolKind.Property: case SymbolKind.Event: return GetDefaultState(symbol); case SymbolKind.ErrorType: return NullableFlowState.NotNull; default: throw ExceptionUtilities.UnexpectedValue(symbol.Kind); } } protected override bool TryGetReceiverAndMember(BoundExpression expr, out BoundExpression? receiver, [NotNullWhen(true)] out Symbol? member) { receiver = null; member = null; switch (expr.Kind) { case BoundKind.FieldAccess: { var fieldAccess = (BoundFieldAccess)expr; var fieldSymbol = fieldAccess.FieldSymbol; member = fieldSymbol; if (fieldSymbol.IsFixedSizeBuffer) { return false; } if (fieldSymbol.IsStatic) { return true; } receiver = fieldAccess.ReceiverOpt; break; } case BoundKind.EventAccess: { var eventAccess = (BoundEventAccess)expr; var eventSymbol = eventAccess.EventSymbol; // https://github.com/dotnet/roslyn/issues/29901 Use AssociatedField for field-like events? member = eventSymbol; if (eventSymbol.IsStatic) { return true; } receiver = eventAccess.ReceiverOpt; break; } case BoundKind.PropertyAccess: { var propAccess = (BoundPropertyAccess)expr; var propSymbol = propAccess.PropertySymbol; member = propSymbol; if (propSymbol.IsStatic) { return true; } receiver = propAccess.ReceiverOpt; break; } } Debug.Assert(member?.RequiresInstanceReceiver() ?? true); return member is object && receiver is object && receiver.Kind != BoundKind.TypeExpression && receiver.Type is object; } protected override int MakeSlot(BoundExpression node) { int result = makeSlot(node); #if DEBUG if (result != -1) { // Check that the slot represents a value of an equivalent type to the node TypeSymbol slotType = NominalSlotType(result); TypeSymbol? nodeType = node.Type; var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var conversionsWithoutNullability = this.compilation.Conversions; Debug.Assert(node.HasErrors || nodeType!.IsErrorType() || conversionsWithoutNullability.HasIdentityOrImplicitReferenceConversion(slotType, nodeType, ref discardedUseSiteInfo) || conversionsWithoutNullability.HasBoxingConversion(slotType, nodeType, ref discardedUseSiteInfo)); } #endif return result; int makeSlot(BoundExpression node) { switch (node.Kind) { case BoundKind.ThisReference: case BoundKind.BaseReference: { var method = getTopLevelMethod(_symbol as MethodSymbol); var thisParameter = method?.ThisParameter; return thisParameter is object ? GetOrCreateSlot(thisParameter) : -1; } case BoundKind.Conversion: { int slot = getPlaceholderSlot(node); if (slot > 0) { return slot; } var conv = (BoundConversion)node; switch (conv.Conversion.Kind) { case ConversionKind.ExplicitNullable: { var operand = conv.Operand; var operandType = operand.Type; var convertedType = conv.Type; if (AreNullableAndUnderlyingTypes(operandType, convertedType, out _)) { // Explicit conversion of Nullable<T> to T is equivalent to Nullable<T>.Value. // For instance, in the following, when evaluating `((A)a).B` we need to recognize // the nullability of `(A)a` (not nullable) and the slot (the slot for `a.Value`). // struct A { B? B; } // struct B { } // if (a?.B != null) _ = ((A)a).B.Value; // no warning int containingSlot = MakeSlot(operand); return containingSlot < 0 ? -1 : GetNullableOfTValueSlot(operandType, containingSlot, out _); } } break; case ConversionKind.Identity: case ConversionKind.DefaultLiteral: case ConversionKind.ImplicitReference: case ConversionKind.ImplicitTupleLiteral: case ConversionKind.Boxing: // No need to create a slot for the boxed value (in the Boxing case) since assignment already // clones slots and there is not another scenario where creating a slot is observable. return MakeSlot(conv.Operand); } } break; case BoundKind.DefaultLiteral: case BoundKind.DefaultExpression: case BoundKind.ObjectCreationExpression: case BoundKind.DynamicObjectCreationExpression: case BoundKind.AnonymousObjectCreationExpression: case BoundKind.NewT: case BoundKind.TupleLiteral: case BoundKind.ConvertedTupleLiteral: return getPlaceholderSlot(node); case BoundKind.ConditionalAccess: return getPlaceholderSlot(node); case BoundKind.ConditionalReceiver: return _lastConditionalAccessSlot; default: { int slot = getPlaceholderSlot(node); return (slot > 0) ? slot : base.MakeSlot(node); } } return -1; } int getPlaceholderSlot(BoundExpression expr) { if (_placeholderLocalsOpt != null && _placeholderLocalsOpt.TryGetValue(expr, out var placeholder)) { return GetOrCreateSlot(placeholder); } return -1; } static MethodSymbol? getTopLevelMethod(MethodSymbol? method) { while (method is object) { var container = method.ContainingSymbol; if (container.Kind == SymbolKind.NamedType) { return method; } method = container as MethodSymbol; } return null; } } protected override int GetOrCreateSlot(Symbol symbol, int containingSlot = 0, bool forceSlotEvenIfEmpty = false, bool createIfMissing = true) { if (containingSlot > 0 && !IsSlotMember(containingSlot, symbol)) return -1; return base.GetOrCreateSlot(symbol, containingSlot, forceSlotEvenIfEmpty, createIfMissing); } private void VisitAndUnsplitAll<T>(ImmutableArray<T> nodes) where T : BoundNode { if (nodes.IsDefault) { return; } foreach (var node in nodes) { Visit(node); Unsplit(); } } private void VisitWithoutDiagnostics(BoundNode? node) { var previousDiagnostics = _disableDiagnostics; _disableDiagnostics = true; Visit(node); _disableDiagnostics = previousDiagnostics; } protected override void VisitRvalue(BoundExpression? node, bool isKnownToBeAnLvalue = false) { Visit(node); VisitRvalueEpilogue(node); } /// <summary> /// The contents of this method, particularly <see cref="UseRvalueOnly"/>, are problematic when /// inlined. The methods themselves are small but they end up allocating significantly larger /// frames due to the use of biggish value types within them. The <see cref="VisitRvalue"/> method /// is used on a hot path for fluent calls and this size change is enough that it causes us /// to exceed our thresholds in EndToEndTests.OverflowOnFluentCall. /// </summary> [MethodImpl(MethodImplOptions.NoInlining)] private void VisitRvalueEpilogue(BoundExpression? node) { Unsplit(); UseRvalueOnly(node); // drop lvalue part } private TypeWithState VisitRvalueWithState(BoundExpression? node) { VisitRvalue(node); return ResultType; } private TypeWithAnnotations VisitLvalueWithAnnotations(BoundExpression node) { VisitLValue(node); Unsplit(); return LvalueResultType; } private static object GetTypeAsDiagnosticArgument(TypeSymbol? typeOpt) { return typeOpt ?? (object)"<null>"; } private static object GetParameterAsDiagnosticArgument(ParameterSymbol? parameterOpt) { return parameterOpt is null ? (object)"" : new FormattedSymbol(parameterOpt, SymbolDisplayFormat.ShortFormat); } private static object GetContainingSymbolAsDiagnosticArgument(ParameterSymbol? parameterOpt) { var containingSymbol = parameterOpt?.ContainingSymbol; return containingSymbol is null ? (object)"" : new FormattedSymbol(containingSymbol, SymbolDisplayFormat.MinimallyQualifiedFormat); } private enum AssignmentKind { Assignment, Return, Argument, ForEachIterationVariable } /// <summary> /// Should we warn for assigning this state into this type? /// /// This should often be checked together with <seealso cref="IsDisallowedNullAssignment(TypeWithState, FlowAnalysisAnnotations)"/> /// It catches putting a `null` into a `[DisallowNull]int?` for example, which cannot simply be represented as a non-nullable target type. /// </summary> private static bool ShouldReportNullableAssignment(TypeWithAnnotations type, NullableFlowState state) { if (!type.HasType || type.Type.IsValueType) { return false; } switch (type.NullableAnnotation) { case NullableAnnotation.Oblivious: case NullableAnnotation.Annotated: return false; } switch (state) { case NullableFlowState.NotNull: return false; case NullableFlowState.MaybeNull: if (type.Type.IsTypeParameterDisallowingAnnotationInCSharp8() && !(type.Type is TypeParameterSymbol { IsNotNullable: true })) { return false; } break; } return true; } /// <summary> /// Reports top-level nullability problem in assignment. /// Any conversion of the value should have been applied. /// </summary> private void ReportNullableAssignmentIfNecessary( BoundExpression? value, TypeWithAnnotations targetType, TypeWithState valueType, bool useLegacyWarnings, AssignmentKind assignmentKind = AssignmentKind.Assignment, ParameterSymbol? parameterOpt = null, Location? location = null) { // Callers should apply any conversions before calling this method // (see https://github.com/dotnet/roslyn/issues/39867). if (targetType.HasType && !targetType.Type.Equals(valueType.Type, TypeCompareKind.AllIgnoreOptions)) { return; } if (value == null || // This prevents us from giving undesired warnings for synthesized arguments for optional parameters, // but allows us to give warnings for synthesized assignments to record properties and for parameter default values at the declaration site. (value.WasCompilerGenerated && assignmentKind == AssignmentKind.Argument) || !ShouldReportNullableAssignment(targetType, valueType.State)) { return; } location ??= value.Syntax.GetLocation(); var unwrappedValue = SkipReferenceConversions(value); if (unwrappedValue.IsSuppressed) { return; } if (value.ConstantValue?.IsNull == true && !useLegacyWarnings) { // Report warning converting null literal to non-nullable reference type. // target (e.g.: `object F() => null;` or calling `void F(object y)` with `F(null)`). ReportDiagnostic(assignmentKind == AssignmentKind.Return ? ErrorCode.WRN_NullReferenceReturn : ErrorCode.WRN_NullAsNonNullable, location); } else if (assignmentKind == AssignmentKind.Argument) { ReportDiagnostic(ErrorCode.WRN_NullReferenceArgument, location, GetParameterAsDiagnosticArgument(parameterOpt), GetContainingSymbolAsDiagnosticArgument(parameterOpt)); LearnFromNonNullTest(value, ref State); } else if (useLegacyWarnings) { if (isMaybeDefaultValue(valueType) && !allowUnconstrainedTypeParameterAnnotations(compilation)) { // No W warning reported assigning or casting [MaybeNull]T value to T // because there is no syntax for declaring the target type as [MaybeNull]T. return; } ReportNonSafetyDiagnostic(location); } else { ReportDiagnostic(assignmentKind == AssignmentKind.Return ? ErrorCode.WRN_NullReferenceReturn : ErrorCode.WRN_NullReferenceAssignment, location); } static bool isMaybeDefaultValue(TypeWithState valueType) { return valueType.Type?.TypeKind == TypeKind.TypeParameter && valueType.State == NullableFlowState.MaybeDefault; } static bool allowUnconstrainedTypeParameterAnnotations(CSharpCompilation compilation) { // Check IDS_FeatureDefaultTypeParameterConstraint feature since `T?` and `where ... : default` // are treated as a single feature, even though the errors reported for the two cases are distinct. var requiredVersion = MessageID.IDS_FeatureDefaultTypeParameterConstraint.RequiredVersion(); return requiredVersion <= compilation.LanguageVersion; } } internal static bool AreParameterAnnotationsCompatible( RefKind refKind, TypeWithAnnotations overriddenType, FlowAnalysisAnnotations overriddenAnnotations, TypeWithAnnotations overridingType, FlowAnalysisAnnotations overridingAnnotations, bool forRef = false) { // We've already checked types and annotations, let's check nullability attributes as well // Return value is treated as an `out` parameter (or `ref` if it is a `ref` return) if (refKind == RefKind.Ref) { // ref variables are invariant return AreParameterAnnotationsCompatible(RefKind.None, overriddenType, overriddenAnnotations, overridingType, overridingAnnotations, forRef: true) && AreParameterAnnotationsCompatible(RefKind.Out, overriddenType, overriddenAnnotations, overridingType, overridingAnnotations); } if (refKind == RefKind.None || refKind == RefKind.In) { // pre-condition attributes // Check whether we can assign a value from overridden parameter to overriding var valueState = GetParameterState(overriddenType, overriddenAnnotations); if (isBadAssignment(valueState, overridingType, overridingAnnotations)) { return false; } // unconditional post-condition attributes on inputs bool overridingHasNotNull = (overridingAnnotations & FlowAnalysisAnnotations.NotNull) == FlowAnalysisAnnotations.NotNull; bool overriddenHasNotNull = (overriddenAnnotations & FlowAnalysisAnnotations.NotNull) == FlowAnalysisAnnotations.NotNull; if (overriddenHasNotNull && !overridingHasNotNull && !forRef) { // Overriding doesn't conform to contract of overridden (ie. promise not to return if parameter is null) return false; } bool overridingHasMaybeNull = (overridingAnnotations & FlowAnalysisAnnotations.MaybeNull) == FlowAnalysisAnnotations.MaybeNull; bool overriddenHasMaybeNull = (overriddenAnnotations & FlowAnalysisAnnotations.MaybeNull) == FlowAnalysisAnnotations.MaybeNull; if (overriddenHasMaybeNull && !overridingHasMaybeNull && !forRef) { // Overriding doesn't conform to contract of overridden (ie. promise to only return if parameter is null) return false; } } if (refKind == RefKind.Out) { // post-condition attributes (`Maybe/NotNull` and `Maybe/NotNullWhen`) if (!canAssignOutputValueWhen(true) || !canAssignOutputValueWhen(false)) { return false; } } return true; bool canAssignOutputValueWhen(bool sense) { var valueWhen = ApplyUnconditionalAnnotations( overridingType.ToTypeWithState(), makeUnconditionalAnnotation(overridingAnnotations, sense)); var destAnnotationsWhen = ToInwardAnnotations(makeUnconditionalAnnotation(overriddenAnnotations, sense)); if (isBadAssignment(valueWhen, overriddenType, destAnnotationsWhen)) { // Can't assign value from overriding to overridden in 'sense' case return false; } return true; } static bool isBadAssignment(TypeWithState valueState, TypeWithAnnotations destinationType, FlowAnalysisAnnotations destinationAnnotations) { if (ShouldReportNullableAssignment( ApplyLValueAnnotations(destinationType, destinationAnnotations), valueState.State)) { return true; } if (IsDisallowedNullAssignment(valueState, destinationAnnotations)) { return true; } return false; } // Convert both conditional annotations to unconditional ones or nothing static FlowAnalysisAnnotations makeUnconditionalAnnotation(FlowAnalysisAnnotations annotations, bool sense) { if (sense) { var unconditionalAnnotationWhenTrue = makeUnconditionalAnnotationCore(annotations, FlowAnalysisAnnotations.NotNullWhenTrue, FlowAnalysisAnnotations.NotNull); return makeUnconditionalAnnotationCore(unconditionalAnnotationWhenTrue, FlowAnalysisAnnotations.MaybeNullWhenTrue, FlowAnalysisAnnotations.MaybeNull); } var unconditionalAnnotationWhenFalse = makeUnconditionalAnnotationCore(annotations, FlowAnalysisAnnotations.NotNullWhenFalse, FlowAnalysisAnnotations.NotNull); return makeUnconditionalAnnotationCore(unconditionalAnnotationWhenFalse, FlowAnalysisAnnotations.MaybeNullWhenFalse, FlowAnalysisAnnotations.MaybeNull); } // Convert Maybe/NotNullWhen into Maybe/NotNull or nothing static FlowAnalysisAnnotations makeUnconditionalAnnotationCore(FlowAnalysisAnnotations annotations, FlowAnalysisAnnotations conditionalAnnotation, FlowAnalysisAnnotations replacementAnnotation) { if ((annotations & conditionalAnnotation) != 0) { return annotations | replacementAnnotation; } return annotations & ~replacementAnnotation; } } private static bool IsDefaultValue(BoundExpression expr) { switch (expr.Kind) { case BoundKind.Conversion: { var conversion = (BoundConversion)expr; var conversionKind = conversion.Conversion.Kind; return (conversionKind == ConversionKind.DefaultLiteral || conversionKind == ConversionKind.NullLiteral) && IsDefaultValue(conversion.Operand); } case BoundKind.DefaultLiteral: case BoundKind.DefaultExpression: return true; default: return false; } } private void ReportNullabilityMismatchInAssignment(SyntaxNode syntaxNode, object sourceType, object destinationType) { ReportDiagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, syntaxNode, sourceType, destinationType); } private void ReportNullabilityMismatchInAssignment(Location location, object sourceType, object destinationType) { ReportDiagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, location, sourceType, destinationType); } /// <summary> /// Update tracked value on assignment. /// </summary> private void TrackNullableStateForAssignment( BoundExpression? valueOpt, TypeWithAnnotations targetType, int targetSlot, TypeWithState valueType, int valueSlot = -1) { Debug.Assert(!IsConditionalState); if (this.State.Reachable) { if (!targetType.HasType) { return; } if (targetSlot <= 0 || targetSlot == valueSlot) { return; } if (!this.State.HasValue(targetSlot)) Normalize(ref this.State); var newState = valueType.State; SetStateAndTrackForFinally(ref this.State, targetSlot, newState); InheritDefaultState(targetType.Type, targetSlot); // https://github.com/dotnet/roslyn/issues/33428: Can the areEquivalentTypes check be removed // if InheritNullableStateOfMember asserts the member is valid for target and value? if (areEquivalentTypes(targetType, valueType)) { if (targetType.Type.IsReferenceType || targetType.TypeKind == TypeKind.TypeParameter || targetType.IsNullableType()) { if (valueSlot > 0) { InheritNullableStateOfTrackableType(targetSlot, valueSlot, skipSlot: targetSlot); } } else if (EmptyStructTypeCache.IsTrackableStructType(targetType.Type)) { InheritNullableStateOfTrackableStruct(targetType.Type, targetSlot, valueSlot, isDefaultValue: !(valueOpt is null) && IsDefaultValue(valueOpt), skipSlot: targetSlot); } } } static bool areEquivalentTypes(TypeWithAnnotations target, TypeWithState assignedValue) => target.Type.Equals(assignedValue.Type, TypeCompareKind.AllIgnoreOptions); } private void ReportNonSafetyDiagnostic(Location location) { ReportDiagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, location); } private void ReportDiagnostic(ErrorCode errorCode, SyntaxNode syntaxNode, params object[] arguments) { ReportDiagnostic(errorCode, syntaxNode.GetLocation(), arguments); } private void ReportDiagnostic(ErrorCode errorCode, Location location, params object[] arguments) { Debug.Assert(ErrorFacts.NullableWarnings.Contains(MessageProvider.Instance.GetIdForErrorCode((int)errorCode))); if (IsReachable() && !_disableDiagnostics) { Diagnostics.Add(errorCode, location, arguments); } } private void InheritNullableStateOfTrackableStruct(TypeSymbol targetType, int targetSlot, int valueSlot, bool isDefaultValue, int skipSlot = -1) { Debug.Assert(targetSlot > 0); Debug.Assert(EmptyStructTypeCache.IsTrackableStructType(targetType)); if (skipSlot < 0) { skipSlot = targetSlot; } if (!isDefaultValue && valueSlot > 0) { InheritNullableStateOfTrackableType(targetSlot, valueSlot, skipSlot); } else { foreach (var field in _emptyStructTypeCache.GetStructInstanceFields(targetType)) { InheritNullableStateOfMember(targetSlot, valueSlot, field, isDefaultValue: isDefaultValue, skipSlot); } } } private bool IsSlotMember(int slot, Symbol possibleMember) { TypeSymbol possibleBase = possibleMember.ContainingType; TypeSymbol possibleDerived = NominalSlotType(slot); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var conversionsWithoutNullability = _conversions.WithNullability(false); return conversionsWithoutNullability.HasIdentityOrImplicitReferenceConversion(possibleDerived, possibleBase, ref discardedUseSiteInfo) || conversionsWithoutNullability.HasBoxingConversion(possibleDerived, possibleBase, ref discardedUseSiteInfo); } // 'skipSlot' is the original target slot that should be skipped in case of cycles. private void InheritNullableStateOfMember(int targetContainerSlot, int valueContainerSlot, Symbol member, bool isDefaultValue, int skipSlot) { Debug.Assert(targetContainerSlot > 0); Debug.Assert(skipSlot > 0); // Ensure member is valid for target and value. if (!IsSlotMember(targetContainerSlot, member)) return; TypeWithAnnotations fieldOrPropertyType = member.GetTypeOrReturnType(); if (fieldOrPropertyType.Type.IsReferenceType || fieldOrPropertyType.TypeKind == TypeKind.TypeParameter || fieldOrPropertyType.IsNullableType()) { int targetMemberSlot = GetOrCreateSlot(member, targetContainerSlot); if (targetMemberSlot > 0) { NullableFlowState value = isDefaultValue ? NullableFlowState.MaybeNull : fieldOrPropertyType.ToTypeWithState().State; int valueMemberSlot = -1; if (valueContainerSlot > 0) { valueMemberSlot = VariableSlot(member, valueContainerSlot); if (valueMemberSlot == skipSlot) { return; } value = this.State.HasValue(valueMemberSlot) ? this.State[valueMemberSlot] : NullableFlowState.NotNull; } SetStateAndTrackForFinally(ref this.State, targetMemberSlot, value); if (valueMemberSlot > 0) { InheritNullableStateOfTrackableType(targetMemberSlot, valueMemberSlot, skipSlot); } } } else if (EmptyStructTypeCache.IsTrackableStructType(fieldOrPropertyType.Type)) { int targetMemberSlot = GetOrCreateSlot(member, targetContainerSlot); if (targetMemberSlot > 0) { int valueMemberSlot = (valueContainerSlot > 0) ? GetOrCreateSlot(member, valueContainerSlot) : -1; if (valueMemberSlot == skipSlot) { return; } InheritNullableStateOfTrackableStruct(fieldOrPropertyType.Type, targetMemberSlot, valueMemberSlot, isDefaultValue: isDefaultValue, skipSlot); } } } private TypeSymbol NominalSlotType(int slot) { return _variables[slot].Symbol.GetTypeOrReturnType().Type; } /// <summary> /// Whenever assigning a variable, and that variable is not declared at the point the state is being set, /// and the new state is not <see cref="NullableFlowState.NotNull"/>, this method should be called to perform the /// state setting and to ensure the mutation is visible outside the finally block when the mutation occurs in a /// finally block. /// </summary> private void SetStateAndTrackForFinally(ref LocalState state, int slot, NullableFlowState newState) { state[slot] = newState; if (newState != NullableFlowState.NotNull && NonMonotonicState.HasValue) { var tryState = NonMonotonicState.Value; if (tryState.HasVariable(slot)) { tryState[slot] = newState.Join(tryState[slot]); NonMonotonicState = tryState; } } } protected override void JoinTryBlockState(ref LocalState self, ref LocalState other) { var tryState = other.GetStateForVariables(self.Id); Join(ref self, ref tryState); } private void InheritDefaultState(TypeSymbol targetType, int targetSlot) { Debug.Assert(targetSlot > 0); // Reset the state of any members of the target. var members = ArrayBuilder<(VariableIdentifier, int)>.GetInstance(); _variables.GetMembers(members, targetSlot); foreach (var (variable, slot) in members) { var symbol = AsMemberOfType(targetType, variable.Symbol); SetStateAndTrackForFinally(ref this.State, slot, GetDefaultState(symbol)); InheritDefaultState(symbol.GetTypeOrReturnType().Type, slot); } members.Free(); } private NullableFlowState GetDefaultState(Symbol symbol) => ApplyUnconditionalAnnotations(symbol.GetTypeOrReturnType().ToTypeWithState(), GetRValueAnnotations(symbol)).State; private void InheritNullableStateOfTrackableType(int targetSlot, int valueSlot, int skipSlot) { Debug.Assert(targetSlot > 0); Debug.Assert(valueSlot > 0); // Clone the state for members that have been set on the value. var members = ArrayBuilder<(VariableIdentifier, int)>.GetInstance(); _variables.GetMembers(members, valueSlot); foreach (var (variable, slot) in members) { var member = variable.Symbol; Debug.Assert(member.Kind == SymbolKind.Field || member.Kind == SymbolKind.Property || member.Kind == SymbolKind.Event); InheritNullableStateOfMember(targetSlot, valueSlot, member, isDefaultValue: false, skipSlot); } members.Free(); } protected override LocalState TopState() { var state = LocalState.ReachableState(_variables); state.PopulateAll(this); return state; } protected override LocalState UnreachableState() { return LocalState.UnreachableState(_variables); } protected override LocalState ReachableBottomState() { // Create a reachable state in which all variables are known to be non-null. return LocalState.ReachableState(_variables); } private void EnterParameters() { if (!(CurrentSymbol is MethodSymbol methodSymbol)) { return; } if (methodSymbol is SynthesizedRecordConstructor) { if (_hasInitialState) { // A record primary constructor's parameters are entered before analyzing initializers. // On the second pass, the correct parameter states (potentially modified by initializers) // are contained in the initial state. return; } } else if (methodSymbol.IsConstructor()) { if (!_hasInitialState) { // For most constructors, we only enter parameters after analyzing initializers. return; } } // The partial definition part may include optional parameters whose default values we want to simulate assigning at the beginning of the method methodSymbol = methodSymbol.PartialDefinitionPart ?? methodSymbol; var methodParameters = methodSymbol.Parameters; var signatureParameters = (_useDelegateInvokeParameterTypes ? _delegateInvokeMethod! : methodSymbol).Parameters; // save a state representing the possibility that parameter default values were not assigned to the parameters. var parameterDefaultsNotAssignedState = State.Clone(); for (int i = 0; i < methodParameters.Length; i++) { var parameter = methodParameters[i]; // In error scenarios, the method can potentially have more parameters than the signature. If so, use the parameter type for those // errored parameters var parameterType = i >= signatureParameters.Length ? parameter.TypeWithAnnotations : signatureParameters[i].TypeWithAnnotations; EnterParameter(parameter, parameterType); } Join(ref State, ref parameterDefaultsNotAssignedState); } private void EnterParameter(ParameterSymbol parameter, TypeWithAnnotations parameterType) { _variables.SetType(parameter, parameterType); if (parameter.RefKind != RefKind.Out) { int slot = GetOrCreateSlot(parameter); Debug.Assert(!IsConditionalState); if (slot > 0) { var state = GetParameterState(parameterType, parameter.FlowAnalysisAnnotations).State; this.State[slot] = state; if (EmptyStructTypeCache.IsTrackableStructType(parameterType.Type)) { InheritNullableStateOfTrackableStruct( parameterType.Type, slot, valueSlot: -1, isDefaultValue: parameter.ExplicitDefaultConstantValue?.IsNull == true); } } } } public override BoundNode? VisitParameterEqualsValue(BoundParameterEqualsValue equalsValue) { var parameter = equalsValue.Parameter; var parameterAnnotations = GetParameterAnnotations(parameter); var parameterLValueType = ApplyLValueAnnotations(parameter.TypeWithAnnotations, parameterAnnotations); var resultType = VisitOptionalImplicitConversion( equalsValue.Value, parameterLValueType, useLegacyWarnings: false, trackMembers: false, assignmentKind: AssignmentKind.Assignment); // If the LHS has annotations, we perform an additional check for nullable value types CheckDisallowedNullAssignment(resultType, parameterAnnotations, equalsValue.Value.Syntax.Location); return null; } internal static TypeWithState GetParameterState(TypeWithAnnotations parameterType, FlowAnalysisAnnotations parameterAnnotations) { if ((parameterAnnotations & FlowAnalysisAnnotations.AllowNull) != 0) { return TypeWithState.Create(parameterType.Type, NullableFlowState.MaybeDefault); } if ((parameterAnnotations & FlowAnalysisAnnotations.DisallowNull) != 0) { return TypeWithState.Create(parameterType.Type, NullableFlowState.NotNull); } return parameterType.ToTypeWithState(); } public sealed override BoundNode? VisitReturnStatement(BoundReturnStatement node) { Debug.Assert(!IsConditionalState); var expr = node.ExpressionOpt; if (expr == null) { EnforceDoesNotReturn(node.Syntax); PendingBranches.Add(new PendingBranch(node, this.State, label: null)); SetUnreachable(); return null; } // Should not convert to method return type when inferring return type (when _returnTypesOpt != null). if (_returnTypesOpt == null && TryGetReturnType(out TypeWithAnnotations returnType, out FlowAnalysisAnnotations returnAnnotations)) { if (node.RefKind == RefKind.None && returnType.Type.SpecialType == SpecialType.System_Boolean) { // visit the expression without unsplitting, then check parameters marked with flow analysis attributes Visit(expr); } else { TypeWithState returnState; if (node.RefKind == RefKind.None) { returnState = VisitOptionalImplicitConversion(expr, returnType, useLegacyWarnings: false, trackMembers: false, AssignmentKind.Return); } else { // return ref expr; returnState = VisitRefExpression(expr, returnType); } // If the return has annotations, we perform an additional check for nullable value types CheckDisallowedNullAssignment(returnState, ToInwardAnnotations(returnAnnotations), node.Syntax.Location, boundValueOpt: expr); } } else { var result = VisitRvalueWithState(expr); if (_returnTypesOpt != null) { _returnTypesOpt.Add((node, result.ToTypeWithAnnotations(compilation))); } } EnforceDoesNotReturn(node.Syntax); if (IsConditionalState) { var joinedState = this.StateWhenTrue.Clone(); Join(ref joinedState, ref this.StateWhenFalse); PendingBranches.Add(new PendingBranch(node, joinedState, label: null, this.IsConditionalState, this.StateWhenTrue, this.StateWhenFalse)); } else { PendingBranches.Add(new PendingBranch(node, this.State, label: null)); } Unsplit(); if (CurrentSymbol is MethodSymbol method) { EnforceNotNullIfNotNull(node.Syntax, this.State, method.Parameters, method.ReturnNotNullIfParameterNotNull, ResultType.State, outputParam: null); } SetUnreachable(); return null; } private TypeWithState VisitRefExpression(BoundExpression expr, TypeWithAnnotations destinationType) { Visit(expr); TypeWithState resultType = ResultType; if (!expr.IsSuppressed && RemoveConversion(expr, includeExplicitConversions: false).expression.Kind != BoundKind.ThrowExpression) { var lvalueResultType = LvalueResultType; if (IsNullabilityMismatch(lvalueResultType, destinationType)) { // declared types must match ReportNullabilityMismatchInAssignment(expr.Syntax, lvalueResultType, destinationType); } else { // types match, but state would let a null in ReportNullableAssignmentIfNecessary(expr, destinationType, resultType, useLegacyWarnings: false); } } return resultType; } private bool TryGetReturnType(out TypeWithAnnotations type, out FlowAnalysisAnnotations annotations) { var method = CurrentSymbol as MethodSymbol; if (method is null) { type = default; annotations = FlowAnalysisAnnotations.None; return false; } var delegateOrMethod = _useDelegateInvokeReturnType ? _delegateInvokeMethod! : method; var returnType = delegateOrMethod.ReturnTypeWithAnnotations; Debug.Assert((object)returnType != LambdaSymbol.ReturnTypeIsBeingInferred); if (returnType.IsVoidType()) { type = default; annotations = FlowAnalysisAnnotations.None; return false; } if (!method.IsAsync) { annotations = delegateOrMethod.ReturnTypeFlowAnalysisAnnotations; type = ApplyUnconditionalAnnotations(returnType, annotations); return true; } if (method.IsAsyncEffectivelyReturningGenericTask(compilation)) { type = ((NamedTypeSymbol)returnType.Type).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.Single(); annotations = FlowAnalysisAnnotations.None; return true; } type = default; annotations = FlowAnalysisAnnotations.None; return false; } public override BoundNode? VisitLocal(BoundLocal node) { var local = node.LocalSymbol; int slot = GetOrCreateSlot(local); var type = GetDeclaredLocalResult(local); if (!node.Type.Equals(type.Type, TypeCompareKind.ConsiderEverything | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes | TypeCompareKind.IgnoreDynamicAndTupleNames)) { // When the local is used before or during initialization, there can potentially be a mismatch between node.LocalSymbol.Type and node.Type. We // need to prefer node.Type as we shouldn't be changing the type of the BoundLocal node during rewrite. // https://github.com/dotnet/roslyn/issues/34158 Debug.Assert(node.Type.IsErrorType() || type.Type.IsErrorType()); type = TypeWithAnnotations.Create(node.Type, type.NullableAnnotation); } SetResult(node, GetAdjustedResult(type.ToTypeWithState(), slot), type); SplitIfBooleanConstant(node); return null; } public override BoundNode? VisitBlock(BoundBlock node) { DeclareLocals(node.Locals); VisitStatementsWithLocalFunctions(node); return null; } private void VisitStatementsWithLocalFunctions(BoundBlock block) { // Since the nullable flow state affects type information, and types can be queried by // the semantic model, there needs to be a single flow state input to a local function // that cannot be path-dependent. To decide the local starting state we Meet the state // of captured variables from all the uses of the local function, computing the // conservative combination of all potential starting states. // // For performance we split the analysis into two phases: the first phase where we // analyze everything except the local functions, hoping to visit all of the uses of the // local function, and then a pass where we visit the local functions. If there's no // recursion or calls between the local functions, the starting state of the local // function should be stable and we don't need a second pass. if (!TrackingRegions && !block.LocalFunctions.IsDefaultOrEmpty) { // First visit everything else foreach (var stmt in block.Statements) { if (stmt.Kind != BoundKind.LocalFunctionStatement) { VisitStatement(stmt); } } // Now visit the local function bodies foreach (var stmt in block.Statements) { if (stmt is BoundLocalFunctionStatement localFunc) { VisitLocalFunctionStatement(localFunc); } } } else { foreach (var stmt in block.Statements) { VisitStatement(stmt); } } } public override BoundNode? VisitLocalFunctionStatement(BoundLocalFunctionStatement node) { var localFunc = node.Symbol; var localFunctionState = GetOrCreateLocalFuncUsages(localFunc); // The starting state is the top state, but with captured // variables set according to Joining the state at all the // local function use sites var state = TopState(); var startingState = localFunctionState.StartingState; startingState.ForEach( (slot, variables) => { var symbol = variables[variables.RootSlot(slot)].Symbol; if (Symbol.IsCaptured(symbol, localFunc)) { state[slot] = startingState[slot]; } }, _variables); localFunctionState.Visited = true; AnalyzeLocalFunctionOrLambda( node, localFunc, state, delegateInvokeMethod: null, useDelegateInvokeParameterTypes: false, useDelegateInvokeReturnType: false); SetInvalidResult(); return null; } private Variables GetOrCreateNestedFunctionVariables(Variables container, MethodSymbol lambdaOrLocalFunction) { _nestedFunctionVariables ??= PooledDictionary<MethodSymbol, Variables>.GetInstance(); if (!_nestedFunctionVariables.TryGetValue(lambdaOrLocalFunction, out var variables)) { variables = container.CreateNestedMethodScope(lambdaOrLocalFunction); _nestedFunctionVariables.Add(lambdaOrLocalFunction, variables); } Debug.Assert((object?)variables.Container == container); return variables; } private void AnalyzeLocalFunctionOrLambda( IBoundLambdaOrFunction lambdaOrFunction, MethodSymbol lambdaOrFunctionSymbol, LocalState state, MethodSymbol? delegateInvokeMethod, bool useDelegateInvokeParameterTypes, bool useDelegateInvokeReturnType) { Debug.Assert(!useDelegateInvokeParameterTypes || delegateInvokeMethod is object); Debug.Assert(!useDelegateInvokeReturnType || delegateInvokeMethod is object); var oldSymbol = this.CurrentSymbol; this.CurrentSymbol = lambdaOrFunctionSymbol; var oldDelegateInvokeMethod = _delegateInvokeMethod; _delegateInvokeMethod = delegateInvokeMethod; var oldUseDelegateInvokeParameterTypes = _useDelegateInvokeParameterTypes; _useDelegateInvokeParameterTypes = useDelegateInvokeParameterTypes; var oldUseDelegateInvokeReturnType = _useDelegateInvokeReturnType; _useDelegateInvokeReturnType = useDelegateInvokeReturnType; var oldReturnTypes = _returnTypesOpt; _returnTypesOpt = null; var oldState = this.State; _variables = GetOrCreateNestedFunctionVariables(_variables, lambdaOrFunctionSymbol); this.State = state.CreateNestedMethodState(_variables); var previousSlot = _snapshotBuilderOpt?.EnterNewWalker(lambdaOrFunctionSymbol) ?? -1; try { var oldPending = SavePending(); EnterParameters(); var oldPending2 = SavePending(); // If this is an iterator, there's an implicit branch before the first statement // of the function where the enumerable is returned. if (lambdaOrFunctionSymbol.IsIterator) { PendingBranches.Add(new PendingBranch(null, this.State, null)); } VisitAlways(lambdaOrFunction.Body); RestorePending(oldPending2); // process any forward branches within the lambda body ImmutableArray<PendingBranch> pendingReturns = RemoveReturns(); RestorePending(oldPending); } finally { _snapshotBuilderOpt?.ExitWalker(this.SaveSharedState(), previousSlot); } _variables = _variables.Container!; this.State = oldState; _returnTypesOpt = oldReturnTypes; _useDelegateInvokeReturnType = oldUseDelegateInvokeReturnType; _useDelegateInvokeParameterTypes = oldUseDelegateInvokeParameterTypes; _delegateInvokeMethod = oldDelegateInvokeMethod; this.CurrentSymbol = oldSymbol; } protected override void VisitLocalFunctionUse( LocalFunctionSymbol symbol, LocalFunctionState localFunctionState, SyntaxNode syntax, bool isCall) { // Do not use this overload in NullableWalker. Use the overload below instead. throw ExceptionUtilities.Unreachable; } private void VisitLocalFunctionUse(LocalFunctionSymbol symbol) { Debug.Assert(!IsConditionalState); var localFunctionState = GetOrCreateLocalFuncUsages(symbol); var state = State.GetStateForVariables(localFunctionState.StartingState.Id); if (Join(ref localFunctionState.StartingState, ref state) && localFunctionState.Visited) { // If the starting state of the local function has changed and we've already visited // the local function, we need another pass stateChangedAfterUse = true; } } public override BoundNode? VisitDoStatement(BoundDoStatement node) { DeclareLocals(node.Locals); return base.VisitDoStatement(node); } public override BoundNode? VisitWhileStatement(BoundWhileStatement node) { DeclareLocals(node.Locals); return base.VisitWhileStatement(node); } public override BoundNode? VisitWithExpression(BoundWithExpression withExpr) { Debug.Assert(!IsConditionalState); var receiver = withExpr.Receiver; VisitRvalue(receiver); _ = CheckPossibleNullReceiver(receiver); var resultType = withExpr.CloneMethod?.ReturnTypeWithAnnotations ?? ResultType.ToTypeWithAnnotations(compilation); var resultState = ApplyUnconditionalAnnotations(resultType.ToTypeWithState(), GetRValueAnnotations(withExpr.CloneMethod)); var resultSlot = GetOrCreatePlaceholderSlot(withExpr); // carry over the null state of members of 'receiver' to the result of the with-expression. TrackNullableStateForAssignment(receiver, resultType, resultSlot, resultState, MakeSlot(receiver)); // use the declared nullability of Clone() for the top-level nullability of the result of the with-expression. SetResult(withExpr, resultState, resultType); VisitObjectCreationInitializer(containingSymbol: null, resultSlot, withExpr.InitializerExpression, FlowAnalysisAnnotations.None); // Note: this does not account for the scenario where `Clone()` returns maybe-null and the with-expression has no initializers. // Tracking in https://github.com/dotnet/roslyn/issues/44759 return null; } public override BoundNode? VisitForStatement(BoundForStatement node) { DeclareLocals(node.OuterLocals); DeclareLocals(node.InnerLocals); return base.VisitForStatement(node); } public override BoundNode? VisitForEachStatement(BoundForEachStatement node) { DeclareLocals(node.IterationVariables); return base.VisitForEachStatement(node); } public override BoundNode? VisitUsingStatement(BoundUsingStatement node) { DeclareLocals(node.Locals); Visit(node.AwaitOpt); return base.VisitUsingStatement(node); } public override BoundNode? VisitUsingLocalDeclarations(BoundUsingLocalDeclarations node) { Visit(node.AwaitOpt); return base.VisitUsingLocalDeclarations(node); } public override BoundNode? VisitFixedStatement(BoundFixedStatement node) { DeclareLocals(node.Locals); return base.VisitFixedStatement(node); } public override BoundNode? VisitConstructorMethodBody(BoundConstructorMethodBody node) { DeclareLocals(node.Locals); return base.VisitConstructorMethodBody(node); } private void DeclareLocal(LocalSymbol local) { if (local.DeclarationKind != LocalDeclarationKind.None) { int slot = GetOrCreateSlot(local); if (slot > 0) { this.State[slot] = GetDefaultState(ref this.State, slot); InheritDefaultState(GetDeclaredLocalResult(local).Type, slot); } } } private void DeclareLocals(ImmutableArray<LocalSymbol> locals) { foreach (var local in locals) { DeclareLocal(local); } } public override BoundNode? VisitLocalDeclaration(BoundLocalDeclaration node) { var local = node.LocalSymbol; int slot = GetOrCreateSlot(local); // We need visit the optional arguments so that we can return nullability information // about them, but we don't want to communicate any information about anything underneath. // Additionally, tests like Scope_DeclaratorArguments_06 can have conditional expressions // in the optional arguments that can leave us in a split state, so we want to make sure // we are not in a conditional state after. Debug.Assert(!IsConditionalState); var oldDisable = _disableDiagnostics; _disableDiagnostics = true; var currentState = State; VisitAndUnsplitAll(node.ArgumentsOpt); _disableDiagnostics = oldDisable; SetState(currentState); if (node.DeclaredTypeOpt != null) { VisitTypeExpression(node.DeclaredTypeOpt); } var initializer = node.InitializerOpt; if (initializer is null) { return null; } TypeWithAnnotations type = local.TypeWithAnnotations; TypeWithState valueType; bool inferredType = node.InferredType; if (local.IsRef) { valueType = VisitRefExpression(initializer, type); } else { valueType = VisitOptionalImplicitConversion(initializer, targetTypeOpt: inferredType ? default : type, useLegacyWarnings: true, trackMembers: true, AssignmentKind.Assignment); } if (inferredType) { if (valueType.HasNullType) { Debug.Assert(type.Type.IsErrorType()); valueType = type.ToTypeWithState(); } type = valueType.ToAnnotatedTypeWithAnnotations(compilation); _variables.SetType(local, type); if (node.DeclaredTypeOpt != null) { SetAnalyzedNullability(node.DeclaredTypeOpt, new VisitResult(type.ToTypeWithState(), type), true); } } TrackNullableStateForAssignment(initializer, type, slot, valueType, MakeSlot(initializer)); return null; } protected override BoundExpression? VisitExpressionWithoutStackGuard(BoundExpression node) { Debug.Assert(!IsConditionalState); SetInvalidResult(); _ = base.VisitExpressionWithoutStackGuard(node); TypeWithState resultType = ResultType; #if DEBUG // Verify Visit method set _result. Debug.Assert((object?)resultType.Type != _invalidType.Type); Debug.Assert(AreCloseEnough(resultType.Type, node.Type)); #endif if (ShouldMakeNotNullRvalue(node)) { var result = resultType.WithNotNullState(); SetResult(node, result, LvalueResultType); } return null; } #if DEBUG // For asserts only. private static bool AreCloseEnough(TypeSymbol? typeA, TypeSymbol? typeB) { // https://github.com/dotnet/roslyn/issues/34993: We should be able to tighten this to ensure that we're actually always returning the same type, // not error if one is null or ignoring certain types if ((object?)typeA == typeB) { return true; } if (typeA is null || typeB is null) { return typeA?.IsErrorType() != false && typeB?.IsErrorType() != false; } return canIgnoreAnyType(typeA) || canIgnoreAnyType(typeB) || typeA.Equals(typeB, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes | TypeCompareKind.IgnoreDynamicAndTupleNames); // Ignore TupleElementNames (see https://github.com/dotnet/roslyn/issues/23651). bool canIgnoreAnyType(TypeSymbol type) { return type.VisitType((t, unused1, unused2) => canIgnoreType(t), (object?)null) is object; } bool canIgnoreType(TypeSymbol type) { return type.IsErrorType() || type.IsDynamic() || type.HasUseSiteError || (type.IsAnonymousType && canIgnoreAnonymousType((NamedTypeSymbol)type)); } bool canIgnoreAnonymousType(NamedTypeSymbol type) { return AnonymousTypeManager.GetAnonymousTypePropertyTypesWithAnnotations(type).Any(t => canIgnoreAnyType(t.Type)); } } private static bool AreCloseEnough(Symbol original, Symbol updated) { // When https://github.com/dotnet/roslyn/issues/38195 is fixed, this workaround needs to be removed if (original is ConstructedMethodSymbol || updated is ConstructedMethodSymbol) { return AreCloseEnough(original.OriginalDefinition, updated.OriginalDefinition); } return (original, updated) switch { (LambdaSymbol l, NamedTypeSymbol n) _ when n.IsDelegateType() => AreLambdaAndNewDelegateSimilar(l, n), (FieldSymbol { ContainingType: { IsTupleType: true }, TupleElementIndex: var oi } originalField, FieldSymbol { ContainingType: { IsTupleType: true }, TupleElementIndex: var ui } updatedField) => originalField.Type.Equals(updatedField.Type, TypeCompareKind.AllNullableIgnoreOptions | TypeCompareKind.IgnoreTupleNames) && oi == ui, _ => original.Equals(updated, TypeCompareKind.AllNullableIgnoreOptions | TypeCompareKind.IgnoreTupleNames) }; } #endif private static bool AreLambdaAndNewDelegateSimilar(LambdaSymbol l, NamedTypeSymbol n) { var invokeMethod = n.DelegateInvokeMethod; return invokeMethod!.Parameters.SequenceEqual(l.Parameters, (p1, p2) => p1.Type.Equals(p2.Type, TypeCompareKind.AllNullableIgnoreOptions | TypeCompareKind.IgnoreTupleNames)) && invokeMethod.ReturnType.Equals(l.ReturnType, TypeCompareKind.AllNullableIgnoreOptions | TypeCompareKind.IgnoreTupleNames); } public override BoundNode? Visit(BoundNode? node) { return Visit(node, expressionIsRead: true); } private BoundNode VisitLValue(BoundNode node) { return Visit(node, expressionIsRead: false); } private BoundNode Visit(BoundNode? node, bool expressionIsRead) { bool originalExpressionIsRead = _expressionIsRead; _expressionIsRead = expressionIsRead; TakeIncrementalSnapshot(node); var result = base.Visit(node); _expressionIsRead = originalExpressionIsRead; return result; } protected override void VisitStatement(BoundStatement statement) { SetInvalidResult(); base.VisitStatement(statement); SetInvalidResult(); } public override BoundNode? VisitObjectCreationExpression(BoundObjectCreationExpression node) { Debug.Assert(!IsConditionalState); var arguments = node.Arguments; var argumentResults = VisitArguments(node, arguments, node.ArgumentRefKindsOpt, node.Constructor, node.ArgsToParamsOpt, node.DefaultArguments, node.Expanded, invokedAsExtensionMethod: false).results; VisitObjectOrDynamicObjectCreation(node, arguments, argumentResults, node.InitializerExpressionOpt); return null; } public override BoundNode? VisitUnconvertedObjectCreationExpression(BoundUnconvertedObjectCreationExpression node) { // This method is only involved in method inference with unbound lambdas. // The diagnostics on arguments are reported by VisitObjectCreationExpression. SetResultType(node, TypeWithState.Create(null, NullableFlowState.NotNull)); return null; } private void VisitObjectOrDynamicObjectCreation( BoundExpression node, ImmutableArray<BoundExpression> arguments, ImmutableArray<VisitArgumentResult> argumentResults, BoundExpression? initializerOpt) { Debug.Assert(node.Kind == BoundKind.ObjectCreationExpression || node.Kind == BoundKind.DynamicObjectCreationExpression || node.Kind == BoundKind.NewT); var argumentTypes = argumentResults.SelectAsArray(ar => ar.RValueType); int slot = -1; var type = node.Type; var resultState = NullableFlowState.NotNull; if (type is object) { slot = GetOrCreatePlaceholderSlot(node); if (slot > 0) { var boundObjectCreationExpression = node as BoundObjectCreationExpression; var constructor = boundObjectCreationExpression?.Constructor; bool isDefaultValueTypeConstructor = constructor?.IsDefaultValueTypeConstructor(requireZeroInit: true) == true; if (EmptyStructTypeCache.IsTrackableStructType(type)) { var containingType = constructor?.ContainingType; if (containingType?.IsTupleType == true && !isDefaultValueTypeConstructor) { // new System.ValueTuple<T1, ..., TN>(e1, ..., eN) TrackNullableStateOfTupleElements(slot, containingType, arguments, argumentTypes, boundObjectCreationExpression!.ArgsToParamsOpt, useRestField: true); } else { InheritNullableStateOfTrackableStruct( type, slot, valueSlot: -1, isDefaultValue: isDefaultValueTypeConstructor); } } else if (type.IsNullableType()) { if (isDefaultValueTypeConstructor) { // a nullable value type created with its default constructor is by definition null resultState = NullableFlowState.MaybeNull; } else if (constructor?.ParameterCount == 1) { // if we deal with one-parameter ctor that takes underlying, then Value state is inferred from the argument. var parameterType = constructor.ParameterTypesWithAnnotations[0]; if (AreNullableAndUnderlyingTypes(type, parameterType.Type, out TypeWithAnnotations underlyingType)) { var operand = arguments[0]; int valueSlot = MakeSlot(operand); if (valueSlot > 0) { TrackNullableStateOfNullableValue(slot, type, operand, underlyingType.ToTypeWithState(), valueSlot); } } } } this.State[slot] = resultState; } } if (initializerOpt != null) { VisitObjectCreationInitializer(containingSymbol: null, slot, initializerOpt, leftAnnotations: FlowAnalysisAnnotations.None); } SetResultType(node, TypeWithState.Create(type, resultState)); } private void VisitObjectCreationInitializer(Symbol? containingSymbol, int containingSlot, BoundExpression node, FlowAnalysisAnnotations leftAnnotations) { TakeIncrementalSnapshot(node); switch (node) { case BoundObjectInitializerExpression objectInitializer: checkImplicitReceiver(objectInitializer); foreach (var initializer in objectInitializer.Initializers) { switch (initializer.Kind) { case BoundKind.AssignmentOperator: VisitObjectElementInitializer(containingSlot, (BoundAssignmentOperator)initializer); break; default: VisitRvalue(initializer); break; } } SetNotNullResult(objectInitializer.Placeholder); break; case BoundCollectionInitializerExpression collectionInitializer: checkImplicitReceiver(collectionInitializer); foreach (var initializer in collectionInitializer.Initializers) { switch (initializer.Kind) { case BoundKind.CollectionElementInitializer: VisitCollectionElementInitializer((BoundCollectionElementInitializer)initializer); break; default: VisitRvalue(initializer); break; } } SetNotNullResult(collectionInitializer.Placeholder); break; default: Debug.Assert(containingSymbol is object); if (containingSymbol is object) { var type = ApplyLValueAnnotations(containingSymbol.GetTypeOrReturnType(), leftAnnotations); TypeWithState resultType = VisitOptionalImplicitConversion(node, type, useLegacyWarnings: false, trackMembers: true, AssignmentKind.Assignment); TrackNullableStateForAssignment(node, type, containingSlot, resultType, MakeSlot(node)); } break; } void checkImplicitReceiver(BoundObjectInitializerExpressionBase node) { if (containingSlot >= 0 && !node.Initializers.IsEmpty) { if (!node.Type.IsValueType && State[containingSlot].MayBeNull()) { if (containingSymbol is null) { ReportDiagnostic(ErrorCode.WRN_NullReferenceReceiver, node.Syntax); } else { ReportDiagnostic(ErrorCode.WRN_NullReferenceInitializer, node.Syntax, containingSymbol); } } } } } private void VisitObjectElementInitializer(int containingSlot, BoundAssignmentOperator node) { TakeIncrementalSnapshot(node); var left = node.Left; switch (left.Kind) { case BoundKind.ObjectInitializerMember: { var objectInitializer = (BoundObjectInitializerMember)left; TakeIncrementalSnapshot(left); var symbol = objectInitializer.MemberSymbol; if (!objectInitializer.Arguments.IsDefaultOrEmpty) { VisitArguments(objectInitializer, objectInitializer.Arguments, objectInitializer.ArgumentRefKindsOpt, (PropertySymbol?)symbol, objectInitializer.ArgsToParamsOpt, objectInitializer.DefaultArguments, objectInitializer.Expanded); } if (symbol is object) { int slot = (containingSlot < 0 || !IsSlotMember(containingSlot, symbol)) ? -1 : GetOrCreateSlot(symbol, containingSlot); VisitObjectCreationInitializer(symbol, slot, node.Right, GetLValueAnnotations(node.Left)); // https://github.com/dotnet/roslyn/issues/35040: Should likely be setting _resultType in VisitObjectCreationInitializer // and using that value instead of reconstructing here } var result = new VisitResult(objectInitializer.Type, NullableAnnotation.NotAnnotated, NullableFlowState.NotNull); SetAnalyzedNullability(objectInitializer, result); SetAnalyzedNullability(node, result); } break; default: Visit(node); break; } } private new void VisitCollectionElementInitializer(BoundCollectionElementInitializer node) { // Note: we analyze even omitted calls (var reinferredMethod, _, _) = VisitArguments(node, node.Arguments, refKindsOpt: default, node.AddMethod, node.ArgsToParamsOpt, node.DefaultArguments, node.Expanded, node.InvokedAsExtensionMethod); Debug.Assert(reinferredMethod is object); if (node.ImplicitReceiverOpt != null) { Debug.Assert(node.ImplicitReceiverOpt.Kind == BoundKind.ObjectOrCollectionValuePlaceholder); SetAnalyzedNullability(node.ImplicitReceiverOpt, new VisitResult(node.ImplicitReceiverOpt.Type, NullableAnnotation.NotAnnotated, NullableFlowState.NotNull)); } SetUnknownResultNullability(node); SetUpdatedSymbol(node, node.AddMethod, reinferredMethod); } private void SetNotNullResult(BoundExpression node) { SetResultType(node, TypeWithState.Create(node.Type, NullableFlowState.NotNull)); } /// <summary> /// Returns true if the type is a struct with no fields or properties. /// </summary> protected override bool IsEmptyStructType(TypeSymbol type) { if (type.TypeKind != TypeKind.Struct) { return false; } // EmptyStructTypeCache.IsEmptyStructType() returns false // if there are non-cyclic fields. if (!_emptyStructTypeCache.IsEmptyStructType(type)) { return false; } if (type.SpecialType != SpecialType.None) { return true; } var members = ((NamedTypeSymbol)type).GetMembersUnordered(); // EmptyStructTypeCache.IsEmptyStructType() returned true. If there are fields, // at least one of those fields must be cyclic, so treat the type as empty. if (members.Any(m => m.Kind == SymbolKind.Field)) { return true; } // If there are properties, the type is not empty. if (members.Any(m => m.Kind == SymbolKind.Property)) { return false; } return true; } private int GetOrCreatePlaceholderSlot(BoundExpression node) { Debug.Assert(node.Type is object); if (IsEmptyStructType(node.Type)) { return -1; } return GetOrCreatePlaceholderSlot(node, TypeWithAnnotations.Create(node.Type, NullableAnnotation.NotAnnotated)); } private int GetOrCreatePlaceholderSlot(object identifier, TypeWithAnnotations type) { _placeholderLocalsOpt ??= PooledDictionary<object, PlaceholderLocal>.GetInstance(); if (!_placeholderLocalsOpt.TryGetValue(identifier, out var placeholder)) { placeholder = new PlaceholderLocal(CurrentSymbol, identifier, type); _placeholderLocalsOpt.Add(identifier, placeholder); } Debug.Assert((object)placeholder != null); return GetOrCreateSlot(placeholder, forceSlotEvenIfEmpty: true); } public override BoundNode? VisitAnonymousObjectCreationExpression(BoundAnonymousObjectCreationExpression node) { Debug.Assert(!IsConditionalState); Debug.Assert(node.Type.IsAnonymousType); var anonymousType = (NamedTypeSymbol)node.Type; var arguments = node.Arguments; var argumentTypes = arguments.SelectAsArray((arg, self) => self.VisitRvalueWithState(arg), this); var argumentsWithAnnotations = argumentTypes.SelectAsArray(arg => arg.ToTypeWithAnnotations(compilation)); if (argumentsWithAnnotations.All(argType => argType.HasType)) { anonymousType = AnonymousTypeManager.ConstructAnonymousTypeSymbol(anonymousType, argumentsWithAnnotations); int receiverSlot = GetOrCreatePlaceholderSlot(node); int currentDeclarationIndex = 0; for (int i = 0; i < arguments.Length; i++) { var argument = arguments[i]; var argumentType = argumentTypes[i]; var property = AnonymousTypeManager.GetAnonymousTypeProperty(anonymousType, i); if (property.Type.SpecialType != SpecialType.System_Void) { // A void element results in an error type in the anonymous type but not in the property's container! // To avoid failing an assertion later, we skip them. var slot = GetOrCreateSlot(property, receiverSlot); TrackNullableStateForAssignment(argument, property.TypeWithAnnotations, slot, argumentType, MakeSlot(argument)); var currentDeclaration = getDeclaration(node, property, ref currentDeclarationIndex); if (currentDeclaration is object) { TakeIncrementalSnapshot(currentDeclaration); SetAnalyzedNullability(currentDeclaration, new VisitResult(argumentType, property.TypeWithAnnotations)); } } } } SetResultType(node, TypeWithState.Create(anonymousType, NullableFlowState.NotNull)); return null; static BoundAnonymousPropertyDeclaration? getDeclaration(BoundAnonymousObjectCreationExpression node, PropertySymbol currentProperty, ref int currentDeclarationIndex) { if (currentDeclarationIndex >= node.Declarations.Length) { return null; } var currentDeclaration = node.Declarations[currentDeclarationIndex]; if (currentDeclaration.Property.MemberIndexOpt == currentProperty.MemberIndexOpt) { currentDeclarationIndex++; return currentDeclaration; } return null; } } public override BoundNode? VisitArrayCreation(BoundArrayCreation node) { foreach (var expr in node.Bounds) { VisitRvalue(expr); } var initialization = node.InitializerOpt; if (initialization is null) { SetResultType(node, TypeWithState.Create(node.Type, NullableFlowState.NotNull)); return null; } TakeIncrementalSnapshot(initialization); var expressions = ArrayBuilder<BoundExpression>.GetInstance(initialization.Initializers.Length); GetArrayElements(initialization, expressions); int n = expressions.Count; // Consider recording in the BoundArrayCreation // whether the array was implicitly typed, rather than relying on syntax. bool isInferred = node.Syntax.Kind() == SyntaxKind.ImplicitArrayCreationExpression; var arrayType = (ArrayTypeSymbol)node.Type; var elementType = arrayType.ElementTypeWithAnnotations; if (!isInferred) { foreach (var expr in expressions) { _ = VisitOptionalImplicitConversion(expr, elementType, useLegacyWarnings: false, trackMembers: false, AssignmentKind.Assignment); } } else { var expressionsNoConversions = ArrayBuilder<BoundExpression>.GetInstance(n); var conversions = ArrayBuilder<Conversion>.GetInstance(n); var resultTypes = ArrayBuilder<TypeWithState>.GetInstance(n); var placeholderBuilder = ArrayBuilder<BoundExpression>.GetInstance(n); foreach (var expression in expressions) { // collect expressions, conversions and result types (BoundExpression expressionNoConversion, Conversion conversion) = RemoveConversion(expression, includeExplicitConversions: false); expressionsNoConversions.Add(expressionNoConversion); conversions.Add(conversion); SnapshotWalkerThroughConversionGroup(expression, expressionNoConversion); var resultType = VisitRvalueWithState(expressionNoConversion); resultTypes.Add(resultType); placeholderBuilder.Add(CreatePlaceholderIfNecessary(expressionNoConversion, resultType.ToTypeWithAnnotations(compilation))); } var placeholders = placeholderBuilder.ToImmutableAndFree(); TypeSymbol? bestType = null; if (!node.HasErrors) { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; bestType = BestTypeInferrer.InferBestType(placeholders, _conversions, ref discardedUseSiteInfo); } TypeWithAnnotations inferredType = (bestType is null) ? elementType.SetUnknownNullabilityForReferenceTypes() : TypeWithAnnotations.Create(bestType); if (bestType is object) { // Convert elements to best type to determine element top-level nullability and to report nested nullability warnings for (int i = 0; i < n; i++) { var expressionNoConversion = expressionsNoConversions[i]; var expression = GetConversionIfApplicable(expressions[i], expressionNoConversion); resultTypes[i] = VisitConversion(expression, expressionNoConversion, conversions[i], inferredType, resultTypes[i], checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Assignment, reportRemainingWarnings: true, reportTopLevelWarnings: false); } // Set top-level nullability on inferred element type var elementState = BestTypeInferrer.GetNullableState(resultTypes); inferredType = TypeWithState.Create(inferredType.Type, elementState).ToTypeWithAnnotations(compilation); for (int i = 0; i < n; i++) { // Report top-level warnings _ = VisitConversion(conversionOpt: null, conversionOperand: expressionsNoConversions[i], Conversion.Identity, targetTypeWithNullability: inferredType, operandType: resultTypes[i], checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Assignment, reportRemainingWarnings: false); } } else { // We need to ensure that we're tracking the inferred type with nullability of any conversions that // were stripped off. for (int i = 0; i < n; i++) { TrackAnalyzedNullabilityThroughConversionGroup(inferredType.ToTypeWithState(), expressions[i] as BoundConversion, expressionsNoConversions[i]); } } expressionsNoConversions.Free(); conversions.Free(); resultTypes.Free(); arrayType = arrayType.WithElementType(inferredType); } expressions.Free(); SetResultType(node, TypeWithState.Create(arrayType, NullableFlowState.NotNull)); return null; } /// <summary> /// Applies analysis similar to <see cref="VisitArrayCreation"/>. /// The expressions returned from a lambda are not converted though, so we'll have to classify fresh conversions. /// Note: even if some conversions fail, we'll proceed to infer top-level nullability. That is reasonable in common cases. /// </summary> internal static TypeWithAnnotations BestTypeForLambdaReturns( ArrayBuilder<(BoundExpression, TypeWithAnnotations)> returns, Binder binder, BoundNode node, Conversions conversions) { var walker = new NullableWalker(binder.Compilation, symbol: null, useConstructorExitWarnings: false, useDelegateInvokeParameterTypes: false, useDelegateInvokeReturnType: false, delegateInvokeMethodOpt: null, node, binder, conversions: conversions, variables: null, returnTypesOpt: null, analyzedNullabilityMapOpt: null, snapshotBuilderOpt: null); int n = returns.Count; var resultTypes = ArrayBuilder<TypeWithAnnotations>.GetInstance(n); var placeholdersBuilder = ArrayBuilder<BoundExpression>.GetInstance(n); for (int i = 0; i < n; i++) { var (returnExpr, resultType) = returns[i]; resultTypes.Add(resultType); placeholdersBuilder.Add(CreatePlaceholderIfNecessary(returnExpr, resultType)); } var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var placeholders = placeholdersBuilder.ToImmutableAndFree(); TypeSymbol? bestType = BestTypeInferrer.InferBestType(placeholders, walker._conversions, ref discardedUseSiteInfo); TypeWithAnnotations inferredType; if (bestType is { }) { // Note: so long as we have a best type, we can proceed. var bestTypeWithObliviousAnnotation = TypeWithAnnotations.Create(bestType); ConversionsBase conversionsWithoutNullability = walker._conversions.WithNullability(false); for (int i = 0; i < n; i++) { BoundExpression placeholder = placeholders[i]; Conversion conversion = conversionsWithoutNullability.ClassifyConversionFromExpression(placeholder, bestType, ref discardedUseSiteInfo); resultTypes[i] = walker.VisitConversion(conversionOpt: null, placeholder, conversion, bestTypeWithObliviousAnnotation, resultTypes[i].ToTypeWithState(), checkConversion: false, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Return, reportRemainingWarnings: false, reportTopLevelWarnings: false).ToTypeWithAnnotations(binder.Compilation); } // Set top-level nullability on inferred type inferredType = TypeWithAnnotations.Create(bestType, BestTypeInferrer.GetNullableAnnotation(resultTypes)); } else { inferredType = default; } resultTypes.Free(); walker.Free(); return inferredType; } private static void GetArrayElements(BoundArrayInitialization node, ArrayBuilder<BoundExpression> builder) { foreach (var child in node.Initializers) { if (child.Kind == BoundKind.ArrayInitialization) { GetArrayElements((BoundArrayInitialization)child, builder); } else { builder.Add(child); } } } public override BoundNode? VisitArrayAccess(BoundArrayAccess node) { Debug.Assert(!IsConditionalState); Visit(node.Expression); Debug.Assert(!IsConditionalState); Debug.Assert(!node.Expression.Type!.IsValueType); // https://github.com/dotnet/roslyn/issues/30598: Mark receiver as not null // after indices have been visited, and only if the receiver has not changed. _ = CheckPossibleNullReceiver(node.Expression); var type = ResultType.Type as ArrayTypeSymbol; foreach (var i in node.Indices) { VisitRvalue(i); } TypeWithAnnotations result; if (node.Indices.Length == 1 && TypeSymbol.Equals(node.Indices[0].Type, compilation.GetWellKnownType(WellKnownType.System_Range), TypeCompareKind.ConsiderEverything2)) { result = TypeWithAnnotations.Create(type); } else { result = type?.ElementTypeWithAnnotations ?? default; } SetLvalueResultType(node, result); return null; } private TypeWithState InferResultNullability(BinaryOperatorKind operatorKind, MethodSymbol? methodOpt, TypeSymbol resultType, TypeWithState leftType, TypeWithState rightType) { NullableFlowState resultState = NullableFlowState.NotNull; if (operatorKind.IsUserDefined()) { if (methodOpt?.ParameterCount == 2) { if (operatorKind.IsLifted() && !operatorKind.IsComparison()) { return GetLiftedReturnType(methodOpt.ReturnTypeWithAnnotations, leftType.State.Join(rightType.State)); } var resultTypeWithState = GetReturnTypeWithState(methodOpt); if ((leftType.IsNotNull && methodOpt.ReturnNotNullIfParameterNotNull.Contains(methodOpt.Parameters[0].Name)) || (rightType.IsNotNull && methodOpt.ReturnNotNullIfParameterNotNull.Contains(methodOpt.Parameters[1].Name))) { resultTypeWithState = resultTypeWithState.WithNotNullState(); } return resultTypeWithState; } } else if (!operatorKind.IsDynamic() && !resultType.IsValueType) { switch (operatorKind.Operator() | operatorKind.OperandTypes()) { case BinaryOperatorKind.DelegateCombination: resultState = leftType.State.Meet(rightType.State); break; case BinaryOperatorKind.DelegateRemoval: resultState = NullableFlowState.MaybeNull; // Delegate removal can produce null. break; default: resultState = NullableFlowState.NotNull; break; } } if (operatorKind.IsLifted() && !operatorKind.IsComparison()) { resultState = leftType.State.Join(rightType.State); } return TypeWithState.Create(resultType, resultState); } protected override void VisitBinaryOperatorChildren(ArrayBuilder<BoundBinaryOperator> stack) { var binary = stack.Pop(); var (leftOperand, leftConversion) = RemoveConversion(binary.Left, includeExplicitConversions: false); // Only the leftmost operator of a left-associative binary operator chain can learn from a conditional access on the left // For simplicity, we just special case it here. // For example, `a?.b(out x) == true` has a conditional access on the left of the operator, // but `expr == a?.b(out x) == true` has a conditional access on the right of the operator if (VisitPossibleConditionalAccess(leftOperand, out var conditionalStateWhenNotNull) && CanPropagateStateWhenNotNull(leftConversion) && binary.OperatorKind.Operator() is BinaryOperatorKind.Equal or BinaryOperatorKind.NotEqual) { Debug.Assert(!IsConditionalState); var leftType = ResultType; var (rightOperand, rightConversion) = RemoveConversion(binary.Right, includeExplicitConversions: false); // Consider the following two scenarios: // `a?.b(x = new object()) == c.d(x = null)` // `x` is maybe-null after expression // `a?.b(x = null) == c.d(x = new object())` // `x` is not-null after expression // In this scenario, we visit the RHS twice: // (1) Once using the single "stateWhenNotNull" after the LHS, in order to update the "stateWhenNotNull" with the effects of the RHS // (2) Once using the "worst case" state after the LHS for diagnostics and public API // After the two visits of the RHS, we may set a conditional state using the state after (1) as the StateWhenTrue and the state after (2) as the StateWhenFalse. // Depending on whether `==` or `!=` was used, and depending on the value of the RHS, we may then swap the StateWhenTrue with the StateWhenFalse. var oldDisableDiagnostics = _disableDiagnostics; _disableDiagnostics = true; var stateAfterLeft = this.State; SetState(getUnconditionalStateWhenNotNull(rightOperand, conditionalStateWhenNotNull)); VisitRvalue(rightOperand); var stateWhenNotNull = this.State; _disableDiagnostics = oldDisableDiagnostics; // Now visit the right side for public API and diagnostics using the worst-case state from the LHS. // Note that we do this visit last to try and make sure that the "visit for public API" overwrites walker state recorded during previous visits where possible. SetState(stateAfterLeft); var rightType = VisitRvalueWithState(rightOperand); ReinferBinaryOperatorAndSetResult(leftOperand, leftConversion, leftType, rightOperand, rightConversion, rightType, binary); if (isKnownNullOrNotNull(rightOperand, rightType)) { var isNullConstant = rightOperand.ConstantValue?.IsNull == true; SetConditionalState(isNullConstant == isEquals(binary) ? (State, stateWhenNotNull) : (stateWhenNotNull, State)); } if (stack.Count == 0) { return; } leftOperand = binary; leftConversion = Conversion.Identity; binary = stack.Pop(); } while (true) { if (!learnFromConditionalAccessOrBoolConstant()) { Unsplit(); // VisitRvalue does this UseRvalueOnly(leftOperand); // drop lvalue part AfterLeftChildHasBeenVisited(leftOperand, leftConversion, binary); } if (stack.Count == 0) { break; } leftOperand = binary; leftConversion = Conversion.Identity; binary = stack.Pop(); } static bool isEquals(BoundBinaryOperator binary) => binary.OperatorKind.Operator() == BinaryOperatorKind.Equal; static bool isKnownNullOrNotNull(BoundExpression expr, TypeWithState resultType) { return resultType.State.IsNotNull() || expr.ConstantValue is object; } LocalState getUnconditionalStateWhenNotNull(BoundExpression otherOperand, PossiblyConditionalState conditionalStateWhenNotNull) { LocalState stateWhenNotNull; if (!conditionalStateWhenNotNull.IsConditionalState) { stateWhenNotNull = conditionalStateWhenNotNull.State; } else if (isEquals(binary) && otherOperand.ConstantValue is { IsBoolean: true, BooleanValue: var boolValue }) { // can preserve conditional state from `.TryGetValue` in `dict?.TryGetValue(key, out value) == true`, // but not in `dict?.TryGetValue(key, out value) != false` stateWhenNotNull = boolValue ? conditionalStateWhenNotNull.StateWhenTrue : conditionalStateWhenNotNull.StateWhenFalse; } else { stateWhenNotNull = conditionalStateWhenNotNull.StateWhenTrue; Join(ref stateWhenNotNull, ref conditionalStateWhenNotNull.StateWhenFalse); } return stateWhenNotNull; } // Returns true if `binary.Right` was visited by the call. bool learnFromConditionalAccessOrBoolConstant() { if (binary.OperatorKind.Operator() is not (BinaryOperatorKind.Equal or BinaryOperatorKind.NotEqual)) { return false; } var leftResult = ResultType; var (rightOperand, rightConversion) = RemoveConversion(binary.Right, includeExplicitConversions: false); // `true == a?.b(out x)` if (isKnownNullOrNotNull(leftOperand, leftResult) && CanPropagateStateWhenNotNull(rightConversion) && TryVisitConditionalAccess(rightOperand, out var conditionalStateWhenNotNull)) { ReinferBinaryOperatorAndSetResult(leftOperand, leftConversion, leftResult, rightOperand, rightConversion, rightType: ResultType, binary); var stateWhenNotNull = getUnconditionalStateWhenNotNull(leftOperand, conditionalStateWhenNotNull); var isNullConstant = leftOperand.ConstantValue?.IsNull == true; SetConditionalState(isNullConstant == isEquals(binary) ? (State, stateWhenNotNull) : (stateWhenNotNull, State)); return true; } // can only learn from a bool constant operand here if it's using the built in `bool operator ==(bool left, bool right)` if (binary.OperatorKind.IsUserDefined()) { return false; } // `(x != null) == true` if (IsConditionalState && binary.Right.ConstantValue is { IsBoolean: true } rightConstant) { var (stateWhenTrue, stateWhenFalse) = (StateWhenTrue.Clone(), StateWhenFalse.Clone()); Unsplit(); Visit(binary.Right); UseRvalueOnly(binary.Right); // record result for the right SetConditionalState(isEquals(binary) == rightConstant.BooleanValue ? (stateWhenTrue, stateWhenFalse) : (stateWhenFalse, stateWhenTrue)); } // `true == (x != null)` else if (binary.Left.ConstantValue is { IsBoolean: true } leftConstant) { Unsplit(); Visit(binary.Right); UseRvalueOnly(binary.Right); if (IsConditionalState && isEquals(binary) != leftConstant.BooleanValue) { SetConditionalState(StateWhenFalse, StateWhenTrue); } } else { return false; } // record result for the binary Debug.Assert(binary.Type.SpecialType == SpecialType.System_Boolean); SetResult(binary, TypeWithState.ForType(binary.Type), TypeWithAnnotations.Create(binary.Type)); return true; } } private void ReinferBinaryOperatorAndSetResult( BoundExpression leftOperand, Conversion leftConversion, TypeWithState leftType, BoundExpression rightOperand, Conversion rightConversion, TypeWithState rightType, BoundBinaryOperator binary) { Debug.Assert(!IsConditionalState); // At this point, State.Reachable may be false for // invalid code such as `s + throw new Exception()`. var method = binary.Method; if (binary.OperatorKind.IsUserDefined() && method?.ParameterCount == 2) { // Update method based on inferred operand type. TypeSymbol methodContainer = method.ContainingType; bool isLifted = binary.OperatorKind.IsLifted(); TypeWithState leftUnderlyingType = GetNullableUnderlyingTypeIfNecessary(isLifted, leftType); TypeWithState rightUnderlyingType = GetNullableUnderlyingTypeIfNecessary(isLifted, rightType); TypeSymbol? asMemberOfType = getTypeIfContainingType(methodContainer, leftUnderlyingType.Type) ?? getTypeIfContainingType(methodContainer, rightUnderlyingType.Type); if (asMemberOfType is object) { method = (MethodSymbol)AsMemberOfType(asMemberOfType, method); } // Analyze operator call properly (honoring [Disallow|Allow|Maybe|NotNull] attribute annotations) https://github.com/dotnet/roslyn/issues/32671 var parameters = method.Parameters; visitOperandConversion(binary.Left, leftOperand, leftConversion, parameters[0], leftUnderlyingType); visitOperandConversion(binary.Right, rightOperand, rightConversion, parameters[1], rightUnderlyingType); SetUpdatedSymbol(binary, binary.Method!, method); void visitOperandConversion( BoundExpression expr, BoundExpression operand, Conversion conversion, ParameterSymbol parameter, TypeWithState operandType) { TypeWithAnnotations targetTypeWithNullability = parameter.TypeWithAnnotations; if (isLifted && targetTypeWithNullability.Type.IsNonNullableValueType()) { targetTypeWithNullability = TypeWithAnnotations.Create(MakeNullableOf(targetTypeWithNullability)); } _ = VisitConversion( expr as BoundConversion, operand, conversion, targetTypeWithNullability, operandType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Argument, parameter); } } else { // Assume this is a built-in operator in which case the parameter types are unannotated. visitOperandConversion(binary.Left, leftOperand, leftConversion, leftType); visitOperandConversion(binary.Right, rightOperand, rightConversion, rightType); void visitOperandConversion( BoundExpression expr, BoundExpression operand, Conversion conversion, TypeWithState operandType) { if (expr.Type is null) { Debug.Assert(operand == expr); } else { _ = VisitConversion( expr as BoundConversion, operand, conversion, TypeWithAnnotations.Create(expr.Type), operandType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Argument); } } } Debug.Assert(!IsConditionalState); // For nested binary operators, this can be the only time they're visited due to explicit stack used in AbstractFlowPass.VisitBinaryOperator, // so we need to set the flow-analyzed type here. var inferredResult = InferResultNullability(binary.OperatorKind, method, binary.Type, leftType, rightType); SetResult(binary, inferredResult, inferredResult.ToTypeWithAnnotations(compilation)); TypeSymbol? getTypeIfContainingType(TypeSymbol baseType, TypeSymbol? derivedType) { if (derivedType is null) { return null; } derivedType = derivedType.StrippedType(); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var conversion = _conversions.ClassifyBuiltInConversion(derivedType, baseType, ref discardedUseSiteInfo); if (conversion.Exists && !conversion.IsExplicit) { return derivedType; } return null; } } private void AfterLeftChildHasBeenVisited( BoundExpression leftOperand, Conversion leftConversion, BoundBinaryOperator binary) { Debug.Assert(!IsConditionalState); var leftType = ResultType; var (rightOperand, rightConversion) = RemoveConversion(binary.Right, includeExplicitConversions: false); VisitRvalue(rightOperand); var rightType = ResultType; ReinferBinaryOperatorAndSetResult(leftOperand, leftConversion, leftType, rightOperand, rightConversion, rightType, binary); BinaryOperatorKind op = binary.OperatorKind.Operator(); if (op == BinaryOperatorKind.Equal || op == BinaryOperatorKind.NotEqual) { // learn from null constant BoundExpression? operandComparedToNull = null; if (binary.Right.ConstantValue?.IsNull == true) { operandComparedToNull = binary.Left; } else if (binary.Left.ConstantValue?.IsNull == true) { operandComparedToNull = binary.Right; } if (operandComparedToNull != null) { // Set all nested conditional slots. For example in a?.b?.c we'll set a, b, and c. bool nonNullCase = op != BinaryOperatorKind.Equal; // true represents WhenTrue splitAndLearnFromNonNullTest(operandComparedToNull, whenTrue: nonNullCase); // `x == null` and `x != null` are pure null tests so update the null-state in the alternative branch too LearnFromNullTest(operandComparedToNull, ref nonNullCase ? ref StateWhenFalse : ref StateWhenTrue); return; } } // learn from comparison between non-null and maybe-null, possibly updating maybe-null to non-null BoundExpression? operandComparedToNonNull = null; if (leftType.IsNotNull && rightType.MayBeNull) { operandComparedToNonNull = binary.Right; } else if (rightType.IsNotNull && leftType.MayBeNull) { operandComparedToNonNull = binary.Left; } if (operandComparedToNonNull != null) { switch (op) { case BinaryOperatorKind.Equal: case BinaryOperatorKind.GreaterThan: case BinaryOperatorKind.LessThan: case BinaryOperatorKind.GreaterThanOrEqual: case BinaryOperatorKind.LessThanOrEqual: operandComparedToNonNull = SkipReferenceConversions(operandComparedToNonNull); splitAndLearnFromNonNullTest(operandComparedToNonNull, whenTrue: true); return; case BinaryOperatorKind.NotEqual: operandComparedToNonNull = SkipReferenceConversions(operandComparedToNonNull); splitAndLearnFromNonNullTest(operandComparedToNonNull, whenTrue: false); return; }; } void splitAndLearnFromNonNullTest(BoundExpression operandComparedToNonNull, bool whenTrue) { var slotBuilder = ArrayBuilder<int>.GetInstance(); GetSlotsToMarkAsNotNullable(operandComparedToNonNull, slotBuilder); if (slotBuilder.Count != 0) { Split(); ref LocalState stateToUpdate = ref whenTrue ? ref this.StateWhenTrue : ref this.StateWhenFalse; MarkSlotsAsNotNull(slotBuilder, ref stateToUpdate); } slotBuilder.Free(); } } protected override bool VisitInterpolatedStringHandlerParts(BoundInterpolatedStringBase node, bool usesBoolReturns, bool firstPartIsConditional, ref LocalState shortCircuitState) { var result = base.VisitInterpolatedStringHandlerParts(node, usesBoolReturns, firstPartIsConditional, ref shortCircuitState); SetNotNullResult(node); return result; } protected override void VisitInterpolatedStringBinaryOperatorNode(BoundBinaryOperator node) { SetNotNullResult(node); } /// <summary> /// If we learn that the operand is non-null, we can infer that certain /// sub-expressions were also non-null. /// Get all nested conditional slots for those sub-expressions. For example in a?.b?.c we'll set a, b, and c. /// Only returns slots for tracked expressions. /// </summary> /// <remarks>https://github.com/dotnet/roslyn/issues/53397 This method should potentially be removed.</remarks> private void GetSlotsToMarkAsNotNullable(BoundExpression operand, ArrayBuilder<int> slotBuilder) { Debug.Assert(operand != null); var previousConditionalAccessSlot = _lastConditionalAccessSlot; try { while (true) { // Due to the nature of binding, if there are conditional access they will be at the top of the bound tree, // potentially with a conversion on top of it. We go through any conditional accesses, adding slots for the // conditional receivers if they have them. If we ever get to a receiver that MakeSlot doesn't return a slot // for, nothing underneath is trackable and we bail at that point. Example: // // a?.GetB()?.C // a is a field, GetB is a method, and C is a property // // The top of the tree is the a?.GetB() conditional call. We'll ask for a slot for a, and we'll get one because // fields have slots. The AccessExpression of the BoundConditionalAccess is another BoundConditionalAccess, this time // with a receiver of the GetB() BoundCall. Attempting to get a slot for this receiver will fail, and we'll // return an array with just the slot for a. int slot; switch (operand.Kind) { case BoundKind.Conversion: // https://github.com/dotnet/roslyn/issues/33879 Detect when conversion has a nullable operand operand = ((BoundConversion)operand).Operand; continue; case BoundKind.AsOperator: operand = ((BoundAsOperator)operand).Operand; continue; case BoundKind.ConditionalAccess: var conditional = (BoundConditionalAccess)operand; GetSlotsToMarkAsNotNullable(conditional.Receiver, slotBuilder); slot = MakeSlot(conditional.Receiver); if (slot > 0) { // We need to continue the walk regardless of whether the receiver should be updated. var receiverType = conditional.Receiver.Type!; if (receiverType.IsNullableType()) slot = GetNullableOfTValueSlot(receiverType, slot, out _); } if (slot > 0) { // When MakeSlot is called on the nested AccessExpression, it will recurse through receivers // until it gets to the BoundConditionalReceiver associated with this node. In our override // of MakeSlot, we substitute this slot when we encounter a BoundConditionalReceiver, and reset the // _lastConditionalAccess field. _lastConditionalAccessSlot = slot; operand = conditional.AccessExpression; continue; } // If there's no slot for this receiver, there cannot be another slot for any of the remaining // access expressions. break; default: // Attempt to create a slot for the current thing. If there were any more conditional accesses, // they would have been on top, so this is the last thing we need to specially handle. // https://github.com/dotnet/roslyn/issues/33879 When we handle unconditional access survival (ie after // c.D has been invoked, c must be nonnull or we've thrown a NullRef), revisit whether // we need more special handling here slot = MakeSlot(operand); if (slot > 0 && PossiblyNullableType(operand.Type)) { slotBuilder.Add(slot); } break; } return; } } finally { _lastConditionalAccessSlot = previousConditionalAccessSlot; } } private static bool PossiblyNullableType([NotNullWhen(true)] TypeSymbol? operandType) => operandType?.CanContainNull() == true; private static void MarkSlotsAsNotNull(ArrayBuilder<int> slots, ref LocalState stateToUpdate) { foreach (int slot in slots) { stateToUpdate[slot] = NullableFlowState.NotNull; } } private void LearnFromNonNullTest(BoundExpression expression, ref LocalState state) { if (expression.Kind == BoundKind.AwaitableValuePlaceholder) { if (_awaitablePlaceholdersOpt != null && _awaitablePlaceholdersOpt.TryGetValue((BoundAwaitableValuePlaceholder)expression, out var value)) { expression = value.AwaitableExpression; } else { return; } } var slotBuilder = ArrayBuilder<int>.GetInstance(); GetSlotsToMarkAsNotNullable(expression, slotBuilder); MarkSlotsAsNotNull(slotBuilder, ref state); slotBuilder.Free(); } private void LearnFromNonNullTest(int slot, ref LocalState state) { state[slot] = NullableFlowState.NotNull; } private void LearnFromNullTest(BoundExpression expression, ref LocalState state) { // nothing to learn about a constant if (expression.ConstantValue != null) return; // We should not blindly strip conversions here. Tracked by https://github.com/dotnet/roslyn/issues/36164 var expressionWithoutConversion = RemoveConversion(expression, includeExplicitConversions: true).expression; var slot = MakeSlot(expressionWithoutConversion); // Since we know for sure the slot is null (we just tested it), we know that dependent slots are not // reachable and therefore can be treated as not null. However, we have not computed the proper // (inferred) type for the expression, so we cannot compute the correct symbols for the member slots here // (using the incorrect symbols would result in computing an incorrect default state for them). // Therefore we do not mark dependent slots not null. See https://github.com/dotnet/roslyn/issues/39624 LearnFromNullTest(slot, expressionWithoutConversion.Type, ref state, markDependentSlotsNotNull: false); } private void LearnFromNullTest(int slot, TypeSymbol? expressionType, ref LocalState state, bool markDependentSlotsNotNull) { if (slot > 0 && PossiblyNullableType(expressionType)) { if (state[slot] == NullableFlowState.NotNull) { // Note: We leave a MaybeDefault state as-is state[slot] = NullableFlowState.MaybeNull; } if (markDependentSlotsNotNull) { MarkDependentSlotsNotNull(slot, expressionType, ref state); } } } // If we know for sure that a slot contains a null value, then we know for sure that dependent slots // are "unreachable" so we might as well treat them as not null. That way when this state is merged // with another state, those dependent states won't pollute values from the other state. private void MarkDependentSlotsNotNull(int slot, TypeSymbol expressionType, ref LocalState state, int depth = 2) { if (depth <= 0) return; foreach (var member in getMembers(expressionType)) { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var containingType = this._symbol?.ContainingType; if ((member is PropertySymbol { IsIndexedProperty: false } || member.Kind == SymbolKind.Field) && member.RequiresInstanceReceiver() && (containingType is null || AccessCheck.IsSymbolAccessible(member, containingType, ref discardedUseSiteInfo))) { int childSlot = GetOrCreateSlot(member, slot, forceSlotEvenIfEmpty: true, createIfMissing: false); if (childSlot > 0) { state[childSlot] = NullableFlowState.NotNull; MarkDependentSlotsNotNull(childSlot, member.GetTypeOrReturnType().Type, ref state, depth - 1); } } } static IEnumerable<Symbol> getMembers(TypeSymbol type) { // First, return the direct members foreach (var member in type.GetMembers()) yield return member; // All types inherit members from their effective bases for (NamedTypeSymbol baseType = effectiveBase(type); !(baseType is null); baseType = baseType.BaseTypeNoUseSiteDiagnostics) foreach (var member in baseType.GetMembers()) yield return member; // Interfaces and type parameters inherit from their effective interfaces foreach (NamedTypeSymbol interfaceType in inheritedInterfaces(type)) foreach (var member in interfaceType.GetMembers()) yield return member; yield break; static NamedTypeSymbol effectiveBase(TypeSymbol type) => type switch { TypeParameterSymbol tp => tp.EffectiveBaseClassNoUseSiteDiagnostics, var t => t.BaseTypeNoUseSiteDiagnostics, }; static ImmutableArray<NamedTypeSymbol> inheritedInterfaces(TypeSymbol type) => type switch { TypeParameterSymbol tp => tp.AllEffectiveInterfacesNoUseSiteDiagnostics, { TypeKind: TypeKind.Interface } => type.AllInterfacesNoUseSiteDiagnostics, _ => ImmutableArray<NamedTypeSymbol>.Empty, }; } } private static BoundExpression SkipReferenceConversions(BoundExpression possiblyConversion) { while (possiblyConversion.Kind == BoundKind.Conversion) { var conversion = (BoundConversion)possiblyConversion; switch (conversion.ConversionKind) { case ConversionKind.ImplicitReference: case ConversionKind.ExplicitReference: possiblyConversion = conversion.Operand; break; default: return possiblyConversion; } } return possiblyConversion; } public override BoundNode? VisitNullCoalescingAssignmentOperator(BoundNullCoalescingAssignmentOperator node) { BoundExpression leftOperand = node.LeftOperand; BoundExpression rightOperand = node.RightOperand; int leftSlot = MakeSlot(leftOperand); TypeWithAnnotations targetType = VisitLvalueWithAnnotations(leftOperand); var leftState = this.State.Clone(); LearnFromNonNullTest(leftOperand, ref leftState); LearnFromNullTest(leftOperand, ref this.State); if (node.IsNullableValueTypeAssignment) { targetType = TypeWithAnnotations.Create(node.Type, NullableAnnotation.NotAnnotated); } TypeWithState rightResult = VisitOptionalImplicitConversion(rightOperand, targetType, useLegacyWarnings: UseLegacyWarnings(leftOperand, targetType), trackMembers: false, AssignmentKind.Assignment); TrackNullableStateForAssignment(rightOperand, targetType, leftSlot, rightResult, MakeSlot(rightOperand)); Join(ref this.State, ref leftState); TypeWithState resultType = TypeWithState.Create(targetType.Type, rightResult.State); SetResultType(node, resultType); return null; } public override BoundNode? VisitNullCoalescingOperator(BoundNullCoalescingOperator node) { Debug.Assert(!IsConditionalState); BoundExpression leftOperand = node.LeftOperand; BoundExpression rightOperand = node.RightOperand; if (IsConstantNull(leftOperand)) { VisitRvalue(leftOperand); Visit(rightOperand); var rightUnconditionalResult = ResultType; // Should be able to use rightResult for the result of the operator but // binding may have generated a different result type in the case of errors. SetResultType(node, TypeWithState.Create(node.Type, rightUnconditionalResult.State)); return null; } VisitPossibleConditionalAccess(leftOperand, out var whenNotNull); TypeWithState leftResult = ResultType; Unsplit(); LearnFromNullTest(leftOperand, ref this.State); bool leftIsConstant = leftOperand.ConstantValue != null; if (leftIsConstant) { SetUnreachable(); } Visit(rightOperand); TypeWithState rightResult = ResultType; Join(ref whenNotNull); var leftResultType = leftResult.Type; var rightResultType = rightResult.Type; var (resultType, leftState) = node.OperatorResultKind switch { BoundNullCoalescingOperatorResultKind.NoCommonType => (node.Type, NullableFlowState.NotNull), BoundNullCoalescingOperatorResultKind.LeftType => getLeftResultType(leftResultType!, rightResultType!), BoundNullCoalescingOperatorResultKind.LeftUnwrappedType => getLeftResultType(leftResultType!.StrippedType(), rightResultType!), BoundNullCoalescingOperatorResultKind.RightType => getResultStateWithRightType(leftResultType!, rightResultType!), BoundNullCoalescingOperatorResultKind.LeftUnwrappedRightType => getResultStateWithRightType(leftResultType!.StrippedType(), rightResultType!), BoundNullCoalescingOperatorResultKind.RightDynamicType => (rightResultType!, NullableFlowState.NotNull), _ => throw ExceptionUtilities.UnexpectedValue(node.OperatorResultKind), }; SetResultType(node, TypeWithState.Create(resultType, rightResult.State.Join(leftState))); return null; (TypeSymbol ResultType, NullableFlowState LeftState) getLeftResultType(TypeSymbol leftType, TypeSymbol rightType) { Debug.Assert(rightType is object); // If there was an identity conversion between the two operands (in short, if there // is no implicit conversion on the right operand), then check nullable conversions // in both directions since it's possible the right operand is the better result type. if ((node.RightOperand as BoundConversion)?.ExplicitCastInCode != false && GenerateConversionForConditionalOperator(node.LeftOperand, leftType, rightType, reportMismatch: false) is { Exists: true } conversion) { Debug.Assert(!conversion.IsUserDefined); return (rightType, NullableFlowState.NotNull); } conversion = GenerateConversionForConditionalOperator(node.RightOperand, rightType, leftType, reportMismatch: true); Debug.Assert(!conversion.IsUserDefined); return (leftType, NullableFlowState.NotNull); } (TypeSymbol ResultType, NullableFlowState LeftState) getResultStateWithRightType(TypeSymbol leftType, TypeSymbol rightType) { var conversion = GenerateConversionForConditionalOperator(node.LeftOperand, leftType, rightType, reportMismatch: true); if (conversion.IsUserDefined) { var conversionResult = VisitConversion( conversionOpt: null, node.LeftOperand, conversion, TypeWithAnnotations.Create(rightType), // When considering the conversion on the left node, it can only occur in the case where the underlying // execution returned non-null TypeWithState.Create(leftType, NullableFlowState.NotNull), checkConversion: false, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Assignment, reportTopLevelWarnings: false, reportRemainingWarnings: false); Debug.Assert(conversionResult.Type is not null); return (conversionResult.Type!, conversionResult.State); } return (rightType, NullableFlowState.NotNull); } } /// <summary> /// Visits a node only if it is a conditional access. /// Returns 'true' if and only if the node was visited. /// </summary> private bool TryVisitConditionalAccess(BoundExpression node, out PossiblyConditionalState stateWhenNotNull) { var (operand, conversion) = RemoveConversion(node, includeExplicitConversions: true); if (operand is not BoundConditionalAccess access || !CanPropagateStateWhenNotNull(conversion)) { stateWhenNotNull = default; return false; } Unsplit(); VisitConditionalAccess(access, out stateWhenNotNull); if (node is BoundConversion boundConversion) { var operandType = ResultType; TypeWithAnnotations explicitType = boundConversion.ConversionGroupOpt?.ExplicitType ?? default; bool fromExplicitCast = explicitType.HasType; TypeWithAnnotations targetType = fromExplicitCast ? explicitType : TypeWithAnnotations.Create(boundConversion.Type); Debug.Assert(targetType.HasType); var result = VisitConversion(boundConversion, access, conversion, targetType, operandType, checkConversion: true, fromExplicitCast, useLegacyWarnings: true, assignmentKind: AssignmentKind.Assignment); SetResultType(boundConversion, result); } Debug.Assert(!IsConditionalState); return true; } /// <summary> /// Unconditionally visits an expression and returns the "state when not null" for the expression. /// </summary> private bool VisitPossibleConditionalAccess(BoundExpression node, out PossiblyConditionalState stateWhenNotNull) { if (TryVisitConditionalAccess(node, out stateWhenNotNull)) { return true; } // in case we *didn't* have a conditional access, the only thing we learn in the "state when not null" // is that the top-level expression was non-null. Visit(node); stateWhenNotNull = PossiblyConditionalState.Create(this); (node, _) = RemoveConversion(node, includeExplicitConversions: true); var slot = MakeSlot(node); if (slot > -1) { if (IsConditionalState) { LearnFromNonNullTest(slot, ref stateWhenNotNull.StateWhenTrue); LearnFromNonNullTest(slot, ref stateWhenNotNull.StateWhenFalse); } else { LearnFromNonNullTest(slot, ref stateWhenNotNull.State); } } return false; } private void VisitConditionalAccess(BoundConditionalAccess node, out PossiblyConditionalState stateWhenNotNull) { Debug.Assert(!IsConditionalState); var receiver = node.Receiver; // handle scenarios like `(a?.b)?.c()` VisitPossibleConditionalAccess(receiver, out stateWhenNotNull); Unsplit(); _currentConditionalReceiverVisitResult = _visitResult; var previousConditionalAccessSlot = _lastConditionalAccessSlot; if (receiver.ConstantValue is { IsNull: false }) { // Consider a scenario like `"a"?.M0(x = 1)?.M0(y = 1)`. // We can "know" that `.M0(x = 1)` was evaluated unconditionally but not `M0(y = 1)`. // Therefore we do a VisitPossibleConditionalAccess here which unconditionally includes the "after receiver" state in State // and includes the "after subsequent conditional accesses" in stateWhenNotNull VisitPossibleConditionalAccess(node.AccessExpression, out stateWhenNotNull); } else { var savedState = this.State.Clone(); if (IsConstantNull(receiver)) { SetUnreachable(); _lastConditionalAccessSlot = -1; } else { // In the when-null branch, the receiver is known to be maybe-null. // In the other branch, the receiver is known to be non-null. LearnFromNullTest(receiver, ref savedState); makeAndAdjustReceiverSlot(receiver); SetPossiblyConditionalState(stateWhenNotNull); } // We want to preserve stateWhenNotNull from accesses in the same "chain": // a?.b(out x)?.c(out y); // expected to preserve stateWhenNotNull from both ?.b(out x) and ?.c(out y) // but not accesses in nested expressions: // a?.b(out x, c?.d(out y)); // expected to preserve stateWhenNotNull from a?.b(out x, ...) but not from c?.d(out y) BoundExpression expr = node.AccessExpression; while (expr is BoundConditionalAccess innerCondAccess) { // we assume that non-conditional accesses can never contain conditional accesses from the same "chain". // that is, we never have to dig through non-conditional accesses to find and handle conditional accesses. Debug.Assert(innerCondAccess.Receiver is not (BoundConditionalAccess or BoundConversion)); VisitRvalue(innerCondAccess.Receiver); _currentConditionalReceiverVisitResult = _visitResult; makeAndAdjustReceiverSlot(innerCondAccess.Receiver); // The savedState here represents the scenario where 0 or more of the access expressions could have been evaluated. // e.g. after visiting `a?.b(x = null)?.c(x = new object())`, the "state when not null" of `x` is NotNull, but the "state when maybe null" of `x` is MaybeNull. Join(ref savedState, ref State); expr = innerCondAccess.AccessExpression; } Debug.Assert(expr is BoundExpression); Visit(expr); expr = node.AccessExpression; while (expr is BoundConditionalAccess innerCondAccess) { // The resulting nullability of each nested conditional access is the same as the resulting nullability of the rightmost access. SetAnalyzedNullability(innerCondAccess, _visitResult); expr = innerCondAccess.AccessExpression; } Debug.Assert(expr is BoundExpression); var slot = MakeSlot(expr); if (slot > -1) { if (IsConditionalState) { LearnFromNonNullTest(slot, ref StateWhenTrue); LearnFromNonNullTest(slot, ref StateWhenFalse); } else { LearnFromNonNullTest(slot, ref State); } } stateWhenNotNull = PossiblyConditionalState.Create(this); Unsplit(); Join(ref this.State, ref savedState); } var accessTypeWithAnnotations = LvalueResultType; TypeSymbol accessType = accessTypeWithAnnotations.Type; var oldType = node.Type; var resultType = oldType.IsVoidType() || oldType.IsErrorType() ? oldType : oldType.IsNullableType() && !accessType.IsNullableType() ? MakeNullableOf(accessTypeWithAnnotations) : accessType; // Per LDM 2019-02-13 decision, the result of a conditional access "may be null" even if // both the receiver and right-hand-side are believed not to be null. SetResultType(node, TypeWithState.Create(resultType, NullableFlowState.MaybeDefault)); _currentConditionalReceiverVisitResult = default; _lastConditionalAccessSlot = previousConditionalAccessSlot; void makeAndAdjustReceiverSlot(BoundExpression receiver) { var slot = MakeSlot(receiver); if (slot > -1) LearnFromNonNullTest(slot, ref State); // given `a?.b()`, when `a` is a nullable value type, // the conditional receiver for `?.b()` must be linked to `a.Value`, not to `a`. if (slot > 0 && receiver.Type?.IsNullableType() == true) slot = GetNullableOfTValueSlot(receiver.Type, slot, out _); _lastConditionalAccessSlot = slot; } } public override BoundNode? VisitConditionalAccess(BoundConditionalAccess node) { VisitConditionalAccess(node, out _); return null; } protected override BoundNode? VisitConditionalOperatorCore( BoundExpression node, bool isRef, BoundExpression condition, BoundExpression originalConsequence, BoundExpression originalAlternative) { VisitCondition(condition); var consequenceState = this.StateWhenTrue; var alternativeState = this.StateWhenFalse; TypeWithState consequenceRValue; TypeWithState alternativeRValue; if (isRef) { TypeWithAnnotations consequenceLValue; TypeWithAnnotations alternativeLValue; (consequenceLValue, consequenceRValue) = visitConditionalRefOperand(consequenceState, originalConsequence); consequenceState = this.State; (alternativeLValue, alternativeRValue) = visitConditionalRefOperand(alternativeState, originalAlternative); Join(ref this.State, ref consequenceState); TypeSymbol? refResultType = node.Type?.SetUnknownNullabilityForReferenceTypes(); if (IsNullabilityMismatch(consequenceLValue, alternativeLValue)) { // l-value types must match ReportNullabilityMismatchInAssignment(node.Syntax, consequenceLValue, alternativeLValue); } else if (!node.HasErrors) { refResultType = consequenceRValue.Type!.MergeEquivalentTypes(alternativeRValue.Type, VarianceKind.None); } var lValueAnnotation = consequenceLValue.NullableAnnotation.EnsureCompatible(alternativeLValue.NullableAnnotation); var rValueState = consequenceRValue.State.Join(alternativeRValue.State); SetResult(node, TypeWithState.Create(refResultType, rValueState), TypeWithAnnotations.Create(refResultType, lValueAnnotation)); return null; } (var consequence, var consequenceConversion, consequenceRValue) = visitConditionalOperand(consequenceState, originalConsequence); var consequenceConditionalState = PossiblyConditionalState.Create(this); consequenceState = CloneAndUnsplit(ref consequenceConditionalState); var consequenceEndReachable = consequenceState.Reachable; (var alternative, var alternativeConversion, alternativeRValue) = visitConditionalOperand(alternativeState, originalAlternative); var alternativeConditionalState = PossiblyConditionalState.Create(this); alternativeState = CloneAndUnsplit(ref alternativeConditionalState); var alternativeEndReachable = alternativeState.Reachable; SetPossiblyConditionalState(in consequenceConditionalState); Join(ref alternativeConditionalState); TypeSymbol? resultType; bool wasTargetTyped = node is BoundConditionalOperator { WasTargetTyped: true }; if (node.HasErrors || wasTargetTyped) { resultType = null; } else { // Determine nested nullability using BestTypeInferrer. // If a branch is unreachable, we could use the nested nullability of the other // branch, but that requires using the nullability of the branch as it applies to the // target type. For instance, the result of the conditional in the following should // be `IEnumerable<object>` not `object[]`: // object[] a = ...; // IEnumerable<object?> b = ...; // var c = true ? a : b; BoundExpression consequencePlaceholder = CreatePlaceholderIfNecessary(consequence, consequenceRValue.ToTypeWithAnnotations(compilation)); BoundExpression alternativePlaceholder = CreatePlaceholderIfNecessary(alternative, alternativeRValue.ToTypeWithAnnotations(compilation)); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; resultType = BestTypeInferrer.InferBestTypeForConditionalOperator(consequencePlaceholder, alternativePlaceholder, _conversions, out _, ref discardedUseSiteInfo); } resultType ??= node.Type?.SetUnknownNullabilityForReferenceTypes(); NullableFlowState resultState; if (!wasTargetTyped) { if (resultType is null) { // This can happen when we're inferring the return type of a lambda. For this case, we don't need to do any work, // the unconverted conditional operator can't contribute info. The conversion that should be on top of this // can add or remove nullability, and nested nodes aren't being publicly exposed by the semantic model. Debug.Assert(node is BoundUnconvertedConditionalOperator); Debug.Assert(_returnTypesOpt is not null); resultState = default; } else { var resultTypeWithAnnotations = TypeWithAnnotations.Create(resultType); TypeWithState convertedConsequenceResult = ConvertConditionalOperandOrSwitchExpressionArmResult( originalConsequence, consequence, consequenceConversion, resultTypeWithAnnotations, consequenceRValue, consequenceState, consequenceEndReachable); TypeWithState convertedAlternativeResult = ConvertConditionalOperandOrSwitchExpressionArmResult( originalAlternative, alternative, alternativeConversion, resultTypeWithAnnotations, alternativeRValue, alternativeState, alternativeEndReachable); resultState = convertedConsequenceResult.State.Join(convertedAlternativeResult.State); } } else { resultState = consequenceRValue.State.Join(alternativeRValue.State); ConditionalInfoForConversion.Add(node, ImmutableArray.Create( (consequenceState, consequenceRValue, consequenceEndReachable), (alternativeState, alternativeRValue, alternativeEndReachable))); } SetResultType(node, TypeWithState.Create(resultType, resultState)); return null; (BoundExpression, Conversion, TypeWithState) visitConditionalOperand(LocalState state, BoundExpression operand) { Conversion conversion; SetState(state); Debug.Assert(!isRef); BoundExpression operandNoConversion; (operandNoConversion, conversion) = RemoveConversion(operand, includeExplicitConversions: false); SnapshotWalkerThroughConversionGroup(operand, operandNoConversion); Visit(operandNoConversion); return (operandNoConversion, conversion, ResultType); } (TypeWithAnnotations LValueType, TypeWithState RValueType) visitConditionalRefOperand(LocalState state, BoundExpression operand) { SetState(state); Debug.Assert(isRef); TypeWithAnnotations lValueType = VisitLvalueWithAnnotations(operand); return (lValueType, ResultType); } } private TypeWithState ConvertConditionalOperandOrSwitchExpressionArmResult( BoundExpression node, BoundExpression operand, Conversion conversion, TypeWithAnnotations targetType, TypeWithState operandType, LocalState state, bool isReachable) { var savedState = this.State; this.State = state; bool previousDisabledDiagnostics = _disableDiagnostics; // If the node is not reachable, then we're only visiting to get // nullability information for the public API, and not to produce diagnostics. // Disable diagnostics, and return default for the resulting state // to indicate that warnings were suppressed. if (!isReachable) { _disableDiagnostics = true; } var resultType = VisitConversion( GetConversionIfApplicable(node, operand), operand, conversion, targetType, operandType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Assignment, reportTopLevelWarnings: false); if (!isReachable) { resultType = default; _disableDiagnostics = previousDisabledDiagnostics; } this.State = savedState; return resultType; } private bool IsReachable() => this.IsConditionalState ? (this.StateWhenTrue.Reachable || this.StateWhenFalse.Reachable) : this.State.Reachable; /// <summary> /// Placeholders are bound expressions with type and state. /// But for typeless expressions (such as `null` or `(null, null)` we hold onto the original bound expression, /// as it will be useful for conversions from expression. /// </summary> private static BoundExpression CreatePlaceholderIfNecessary(BoundExpression expr, TypeWithAnnotations type) { return !type.HasType ? expr : new BoundExpressionWithNullability(expr.Syntax, expr, type.NullableAnnotation, type.Type); } public override BoundNode? VisitConditionalReceiver(BoundConditionalReceiver node) { var rvalueType = _currentConditionalReceiverVisitResult.RValueType.Type; if (rvalueType?.IsNullableType() == true) { rvalueType = rvalueType.GetNullableUnderlyingType(); } SetResultType(node, TypeWithState.Create(rvalueType, NullableFlowState.NotNull)); return null; } public override BoundNode? VisitCall(BoundCall node) { // Note: we analyze even omitted calls TypeWithState receiverType = VisitCallReceiver(node); ReinferMethodAndVisitArguments(node, receiverType); return null; } private void ReinferMethodAndVisitArguments(BoundCall node, TypeWithState receiverType) { var method = node.Method; ImmutableArray<RefKind> refKindsOpt = node.ArgumentRefKindsOpt; if (!receiverType.HasNullType) { // Update method based on inferred receiver type. method = (MethodSymbol)AsMemberOfType(receiverType.Type, method); } ImmutableArray<VisitArgumentResult> results; bool returnNotNull; (method, results, returnNotNull) = VisitArguments(node, node.Arguments, refKindsOpt, method!.Parameters, node.ArgsToParamsOpt, node.DefaultArguments, node.Expanded, node.InvokedAsExtensionMethod, method); ApplyMemberPostConditions(node.ReceiverOpt, method); LearnFromEqualsMethod(method, node, receiverType, results); var returnState = GetReturnTypeWithState(method); if (returnNotNull) { returnState = returnState.WithNotNullState(); } SetResult(node, returnState, method.ReturnTypeWithAnnotations); SetUpdatedSymbol(node, node.Method, method); } private void LearnFromEqualsMethod(MethodSymbol method, BoundCall node, TypeWithState receiverType, ImmutableArray<VisitArgumentResult> results) { // easy out var parameterCount = method.ParameterCount; var arguments = node.Arguments; if (node.HasErrors || (parameterCount != 1 && parameterCount != 2) || parameterCount != arguments.Length || method.MethodKind != MethodKind.Ordinary || method.ReturnType.SpecialType != SpecialType.System_Boolean || (method.Name != SpecialMembers.GetDescriptor(SpecialMember.System_Object__Equals).Name && method.Name != SpecialMembers.GetDescriptor(SpecialMember.System_Object__ReferenceEquals).Name && !anyOverriddenMethodHasExplicitImplementation(method))) { return; } var isStaticEqualsMethod = method.Equals(compilation.GetSpecialTypeMember(SpecialMember.System_Object__EqualsObjectObject)) || method.Equals(compilation.GetSpecialTypeMember(SpecialMember.System_Object__ReferenceEquals)); if (isStaticEqualsMethod || isWellKnownEqualityMethodOrImplementation(compilation, method, receiverType.Type, WellKnownMember.System_Collections_Generic_IEqualityComparer_T__Equals)) { Debug.Assert(arguments.Length == 2); learnFromEqualsMethodArguments(arguments[0], results[0].RValueType, arguments[1], results[1].RValueType); return; } var isObjectEqualsMethodOrOverride = method.GetLeastOverriddenMethod(accessingTypeOpt: null) .Equals(compilation.GetSpecialTypeMember(SpecialMember.System_Object__Equals)); if (node.ReceiverOpt is BoundExpression receiver && (isObjectEqualsMethodOrOverride || isWellKnownEqualityMethodOrImplementation(compilation, method, receiverType.Type, WellKnownMember.System_IEquatable_T__Equals))) { Debug.Assert(arguments.Length == 1); learnFromEqualsMethodArguments(receiver, receiverType, arguments[0], results[0].RValueType); return; } static bool anyOverriddenMethodHasExplicitImplementation(MethodSymbol method) { for (var overriddenMethod = method; overriddenMethod is object; overriddenMethod = overriddenMethod.OverriddenMethod) { if (overriddenMethod.IsExplicitInterfaceImplementation) { return true; } } return false; } static bool isWellKnownEqualityMethodOrImplementation(CSharpCompilation compilation, MethodSymbol method, TypeSymbol? receiverType, WellKnownMember wellKnownMember) { var wellKnownMethod = (MethodSymbol?)compilation.GetWellKnownTypeMember(wellKnownMember); if (wellKnownMethod is null || receiverType is null) { return false; } var wellKnownType = wellKnownMethod.ContainingType; var parameterType = method.Parameters[0].TypeWithAnnotations; var constructedType = wellKnownType.Construct(ImmutableArray.Create(parameterType)); var constructedMethod = wellKnownMethod.AsMember(constructedType); // FindImplementationForInterfaceMember doesn't check if this method is itself the interface method we're looking for if (constructedMethod.Equals(method)) { return true; } // check whether 'method', when called on this receiver, is an implementation of 'constructedMethod'. for (var baseType = receiverType; baseType is object && method is object; baseType = baseType.BaseTypeNoUseSiteDiagnostics) { var implementationMethod = baseType.FindImplementationForInterfaceMember(constructedMethod); if (implementationMethod is null) { // we know no base type will implement this interface member either return false; } if (implementationMethod.ContainingType.IsInterface) { // this method cannot be called directly from source because an interface can only explicitly implement a method from its base interface. return false; } // could be calling an override of a method that implements the interface method for (var overriddenMethod = method; overriddenMethod is object; overriddenMethod = overriddenMethod.OverriddenMethod) { if (overriddenMethod.Equals(implementationMethod)) { return true; } } // the Equals method being called isn't the method that implements the interface method in this type. // it could be a method that implements the interface on a base type, so check again with the base type of 'implementationMethod.ContainingType' // e.g. in this hierarchy: // class A -> B -> C -> D // method virtual B.Equals -> override D.Equals // // we would potentially check: // 1. D.Equals when called on D, then B.Equals when called on D // 2. B.Equals when called on C // 3. B.Equals when called on B // 4. give up when checking A, since B.Equals is not overriding anything in A // we know that implementationMethod.ContainingType is the same type or a base type of 'baseType', // and that the implementation method will be the same between 'baseType' and 'implementationMethod.ContainingType'. // we step through the intermediate bases in order to skip unnecessary override methods. while (!baseType.Equals(implementationMethod.ContainingType) && method is object) { if (baseType.Equals(method.ContainingType)) { // since we're about to move on to the base of 'method.ContainingType', // we know the implementation could only be an overridden method of 'method'. method = method.OverriddenMethod; } baseType = baseType.BaseTypeNoUseSiteDiagnostics; // the implementation method must be contained in this 'baseType' or one of its bases. Debug.Assert(baseType is object); } // now 'baseType == implementationMethod.ContainingType', so if 'method' is // contained in that same type we should advance 'method' one more time. if (method is object && baseType.Equals(method.ContainingType)) { method = method.OverriddenMethod; } } return false; } void learnFromEqualsMethodArguments(BoundExpression left, TypeWithState leftType, BoundExpression right, TypeWithState rightType) { // comparing anything to a null literal gives maybe-null when true and not-null when false // comparing a maybe-null to a not-null gives us not-null when true, nothing learned when false if (left.ConstantValue?.IsNull == true) { Split(); LearnFromNullTest(right, ref StateWhenTrue); LearnFromNonNullTest(right, ref StateWhenFalse); } else if (right.ConstantValue?.IsNull == true) { Split(); LearnFromNullTest(left, ref StateWhenTrue); LearnFromNonNullTest(left, ref StateWhenFalse); } else if (leftType.MayBeNull && rightType.IsNotNull) { Split(); LearnFromNonNullTest(left, ref StateWhenTrue); } else if (rightType.MayBeNull && leftType.IsNotNull) { Split(); LearnFromNonNullTest(right, ref StateWhenTrue); } } } private bool IsCompareExchangeMethod(MethodSymbol? method) { if (method is null) { return false; } return method.Equals(compilation.GetWellKnownTypeMember(WellKnownMember.System_Threading_Interlocked__CompareExchange), SymbolEqualityComparer.ConsiderEverything.CompareKind) || method.OriginalDefinition.Equals(compilation.GetWellKnownTypeMember(WellKnownMember.System_Threading_Interlocked__CompareExchange_T), SymbolEqualityComparer.ConsiderEverything.CompareKind); } private readonly struct CompareExchangeInfo { public readonly ImmutableArray<BoundExpression> Arguments; public readonly ImmutableArray<VisitArgumentResult> Results; public readonly ImmutableArray<int> ArgsToParamsOpt; public CompareExchangeInfo(ImmutableArray<BoundExpression> arguments, ImmutableArray<VisitArgumentResult> results, ImmutableArray<int> argsToParamsOpt) { Arguments = arguments; Results = results; ArgsToParamsOpt = argsToParamsOpt; } public bool IsDefault => Arguments.IsDefault || Results.IsDefault; } private NullableFlowState LearnFromCompareExchangeMethod(in CompareExchangeInfo compareExchangeInfo) { Debug.Assert(!compareExchangeInfo.IsDefault); // In general a call to CompareExchange of the form: // // Interlocked.CompareExchange(ref location, value, comparand); // // will be analyzed similarly to the following: // // if (location == comparand) // { // location = value; // } if (compareExchangeInfo.Arguments.Length != 3) { // This can occur if CompareExchange has optional arguments. // Since none of the main runtimes have optional arguments, // we bail to avoid an exception but don't bother actually calculating the FlowState. return NullableFlowState.NotNull; } var argsToParamsOpt = compareExchangeInfo.ArgsToParamsOpt; Debug.Assert(argsToParamsOpt is { IsDefault: true } or { Length: 3 }); var (comparandIndex, valueIndex, locationIndex) = argsToParamsOpt.IsDefault ? (2, 1, 0) : (argsToParamsOpt.IndexOf(2), argsToParamsOpt.IndexOf(1), argsToParamsOpt.IndexOf(0)); var comparand = compareExchangeInfo.Arguments[comparandIndex]; var valueFlowState = compareExchangeInfo.Results[valueIndex].RValueType.State; if (comparand.ConstantValue?.IsNull == true) { // If location contained a null, then the write `location = value` definitely occurred } else { var locationFlowState = compareExchangeInfo.Results[locationIndex].RValueType.State; // A write may have occurred valueFlowState = valueFlowState.Join(locationFlowState); } return valueFlowState; } private TypeWithState VisitCallReceiver(BoundCall node) { var receiverOpt = node.ReceiverOpt; TypeWithState receiverType = default; if (receiverOpt != null) { receiverType = VisitRvalueWithState(receiverOpt); // methods which are members of Nullable<T> (ex: ToString, GetHashCode) can be invoked on null receiver. // However, inherited methods (ex: GetType) are invoked on a boxed value (since base types are reference types) // and therefore in those cases nullable receivers should be checked for nullness. bool checkNullableValueType = false; var type = receiverType.Type; var method = node.Method; if (method.RequiresInstanceReceiver && type?.IsNullableType() == true && method.ContainingType.IsReferenceType) { checkNullableValueType = true; } else if (method.OriginalDefinition == compilation.GetSpecialTypeMember(SpecialMember.System_Nullable_T_get_Value)) { // call to get_Value may not occur directly in source, but may be inserted as a result of premature lowering. // One example where we do it is foreach with nullables. // The reason is Dev10 compatibility (see: UnwrapCollectionExpressionIfNullable in ForEachLoopBinder.cs) // Regardless of the reasons, we know that the method does not tolerate nulls. checkNullableValueType = true; } // https://github.com/dotnet/roslyn/issues/30598: Mark receiver as not null // after arguments have been visited, and only if the receiver has not changed. _ = CheckPossibleNullReceiver(receiverOpt, checkNullableValueType); } return receiverType; } private TypeWithState GetReturnTypeWithState(MethodSymbol method) { return TypeWithState.Create(method.ReturnTypeWithAnnotations, GetRValueAnnotations(method)); } private FlowAnalysisAnnotations GetRValueAnnotations(Symbol? symbol) { // Annotations are ignored when binding an attribute to avoid cycles. (Members used // in attributes are error scenarios, so missing warnings should not be important.) if (IsAnalyzingAttribute) { return FlowAnalysisAnnotations.None; } var annotations = symbol.GetFlowAnalysisAnnotations(); return annotations & (FlowAnalysisAnnotations.MaybeNull | FlowAnalysisAnnotations.NotNull); } private FlowAnalysisAnnotations GetParameterAnnotations(ParameterSymbol parameter) { // Annotations are ignored when binding an attribute to avoid cycles. (Members used // in attributes are error scenarios, so missing warnings should not be important.) return IsAnalyzingAttribute ? FlowAnalysisAnnotations.None : parameter.FlowAnalysisAnnotations; } /// <summary> /// Fix a TypeWithAnnotations based on Allow/DisallowNull annotations prior to a conversion or assignment. /// Note this does not work for nullable value types, so an additional check with <see cref="CheckDisallowedNullAssignment"/> may be required. /// </summary> private static TypeWithAnnotations ApplyLValueAnnotations(TypeWithAnnotations declaredType, FlowAnalysisAnnotations flowAnalysisAnnotations) { if ((flowAnalysisAnnotations & FlowAnalysisAnnotations.DisallowNull) == FlowAnalysisAnnotations.DisallowNull) { return declaredType.AsNotAnnotated(); } else if ((flowAnalysisAnnotations & FlowAnalysisAnnotations.AllowNull) == FlowAnalysisAnnotations.AllowNull) { return declaredType.AsAnnotated(); } return declaredType; } /// <summary> /// Update the null-state based on MaybeNull/NotNull /// </summary> private static TypeWithState ApplyUnconditionalAnnotations(TypeWithState typeWithState, FlowAnalysisAnnotations annotations) { if ((annotations & FlowAnalysisAnnotations.NotNull) == FlowAnalysisAnnotations.NotNull) { return TypeWithState.Create(typeWithState.Type, NullableFlowState.NotNull); } if ((annotations & FlowAnalysisAnnotations.MaybeNull) == FlowAnalysisAnnotations.MaybeNull) { return TypeWithState.Create(typeWithState.Type, NullableFlowState.MaybeDefault); } return typeWithState; } private static TypeWithAnnotations ApplyUnconditionalAnnotations(TypeWithAnnotations declaredType, FlowAnalysisAnnotations annotations) { if ((annotations & FlowAnalysisAnnotations.MaybeNull) == FlowAnalysisAnnotations.MaybeNull) { return declaredType.AsAnnotated(); } if ((annotations & FlowAnalysisAnnotations.NotNull) == FlowAnalysisAnnotations.NotNull) { return declaredType.AsNotAnnotated(); } return declaredType; } // https://github.com/dotnet/roslyn/issues/29863 Record in the node whether type // arguments were implicit, to allow for cases where the syntax is not an // invocation (such as a synthesized call from a query interpretation). private static bool HasImplicitTypeArguments(BoundNode node) { if (node is BoundCollectionElementInitializer { AddMethod: { TypeArgumentsWithAnnotations: { IsEmpty: false } } }) { return true; } if (node is BoundForEachStatement { EnumeratorInfoOpt: { GetEnumeratorInfo: { Method: { TypeArgumentsWithAnnotations: { IsEmpty: false } } } } }) { return true; } var syntax = node.Syntax; if (syntax.Kind() != SyntaxKind.InvocationExpression) { // Unexpected syntax kind. return false; } return HasImplicitTypeArguments(((InvocationExpressionSyntax)syntax).Expression); } private static bool HasImplicitTypeArguments(SyntaxNode syntax) { var nameSyntax = Binder.GetNameSyntax(syntax, out _); if (nameSyntax == null) { // Unexpected syntax kind. return false; } nameSyntax = nameSyntax.GetUnqualifiedName(); return nameSyntax.Kind() != SyntaxKind.GenericName; } protected override void VisitArguments(ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> refKindsOpt, MethodSymbol method) { // Callers should be using VisitArguments overload below. throw ExceptionUtilities.Unreachable; } private (MethodSymbol? method, ImmutableArray<VisitArgumentResult> results, bool returnNotNull) VisitArguments( BoundExpression node, ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> refKindsOpt, MethodSymbol? method, ImmutableArray<int> argsToParamsOpt, BitVector defaultArguments, bool expanded, bool invokedAsExtensionMethod) { return VisitArguments(node, arguments, refKindsOpt, method is null ? default : method.Parameters, argsToParamsOpt, defaultArguments, expanded, invokedAsExtensionMethod, method); } private ImmutableArray<VisitArgumentResult> VisitArguments( BoundExpression node, ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> refKindsOpt, PropertySymbol? property, ImmutableArray<int> argsToParamsOpt, BitVector defaultArguments, bool expanded) { return VisitArguments(node, arguments, refKindsOpt, property is null ? default : property.Parameters, argsToParamsOpt, defaultArguments, expanded, invokedAsExtensionMethod: false).results; } /// <summary> /// If you pass in a method symbol, its type arguments will be re-inferred and the re-inferred method will be returned. /// </summary> private (MethodSymbol? method, ImmutableArray<VisitArgumentResult> results, bool returnNotNull) VisitArguments( BoundNode node, ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> refKindsOpt, ImmutableArray<ParameterSymbol> parametersOpt, ImmutableArray<int> argsToParamsOpt, BitVector defaultArguments, bool expanded, bool invokedAsExtensionMethod, MethodSymbol? method = null) { Debug.Assert(!arguments.IsDefault); bool shouldReturnNotNull = false; (ImmutableArray<BoundExpression> argumentsNoConversions, ImmutableArray<Conversion> conversions) = RemoveArgumentConversions(arguments, refKindsOpt); // Visit the arguments and collect results ImmutableArray<VisitArgumentResult> results = VisitArgumentsEvaluate(node.Syntax, argumentsNoConversions, refKindsOpt, parametersOpt, argsToParamsOpt, defaultArguments, expanded); // Re-infer method type parameters if (method?.IsGenericMethod == true) { if (HasImplicitTypeArguments(node)) { method = InferMethodTypeArguments(method, GetArgumentsForMethodTypeInference(results, argumentsNoConversions), refKindsOpt, argsToParamsOpt, expanded); parametersOpt = method.Parameters; } if (ConstraintsHelper.RequiresChecking(method)) { var syntax = node.Syntax; CheckMethodConstraints( syntax switch { InvocationExpressionSyntax { Expression: var expression } => expression, ForEachStatementSyntax { Expression: var expression } => expression, _ => syntax }, method); } } bool parameterHasNotNullIfNotNull = !IsAnalyzingAttribute && !parametersOpt.IsDefault && parametersOpt.Any(p => !p.NotNullIfParameterNotNull.IsEmpty); var notNullParametersBuilder = parameterHasNotNullIfNotNull ? ArrayBuilder<ParameterSymbol>.GetInstance() : null; if (!parametersOpt.IsDefault) { // Visit conversions, inbound assignments including pre-conditions ImmutableHashSet<string>? returnNotNullIfParameterNotNull = IsAnalyzingAttribute ? null : method?.ReturnNotNullIfParameterNotNull; for (int i = 0; i < results.Length; i++) { var argumentNoConversion = argumentsNoConversions[i]; var argument = i < arguments.Length ? arguments[i] : argumentNoConversion; if (argument is not BoundConversion && argumentNoConversion is BoundLambda lambda) { Debug.Assert(node.HasErrors); Debug.Assert((object)argument == argumentNoConversion); // 'VisitConversion' only visits a lambda when the lambda has an AnonymousFunction conversion. // This lambda doesn't have a conversion, so we need to visit it here. VisitLambda(lambda, delegateTypeOpt: null, results[i].StateForLambda); continue; } (ParameterSymbol? parameter, TypeWithAnnotations parameterType, FlowAnalysisAnnotations parameterAnnotations, bool isExpandedParamsArgument) = GetCorrespondingParameter(i, parametersOpt, argsToParamsOpt, expanded); if (parameter is null) { // If this assert fails, we are missing necessary info to visit the // conversion of a target typed conditional or switch. Debug.Assert(argumentNoConversion is not (BoundConditionalOperator { WasTargetTyped: true } or BoundConvertedSwitchExpression { WasTargetTyped: true }) && _conditionalInfoForConversionOpt?.ContainsKey(argumentNoConversion) is null or false); // If this assert fails, it means we failed to visit a lambda for error recovery above. Debug.Assert(argumentNoConversion is not BoundLambda); continue; } // We disable diagnostics when: // 1. the containing call has errors (to reduce cascading diagnostics) // 2. on implicit default arguments (since that's really only an issue with the declaration) var previousDisableDiagnostics = _disableDiagnostics; _disableDiagnostics |= node.HasErrors || defaultArguments[i]; VisitArgumentConversionAndInboundAssignmentsAndPreConditions( GetConversionIfApplicable(argument, argumentNoConversion), argumentNoConversion, conversions.IsDefault || i >= conversions.Length ? Conversion.Identity : conversions[i], GetRefKind(refKindsOpt, i), parameter, parameterType, parameterAnnotations, results[i], invokedAsExtensionMethod && i == 0); _disableDiagnostics = previousDisableDiagnostics; if (results[i].RValueType.IsNotNull || isExpandedParamsArgument) { notNullParametersBuilder?.Add(parameter); if (returnNotNullIfParameterNotNull?.Contains(parameter.Name) == true) { shouldReturnNotNull = true; } } } } if (node is BoundCall { Method: { OriginalDefinition: LocalFunctionSymbol localFunction } }) { VisitLocalFunctionUse(localFunction); } if (!node.HasErrors && !parametersOpt.IsDefault) { // For CompareExchange method we need more context to determine the state of outbound assignment CompareExchangeInfo compareExchangeInfo = IsCompareExchangeMethod(method) ? new CompareExchangeInfo(arguments, results, argsToParamsOpt) : default; // Visit outbound assignments and post-conditions // Note: the state may get split in this step for (int i = 0; i < arguments.Length; i++) { (ParameterSymbol? parameter, TypeWithAnnotations parameterType, FlowAnalysisAnnotations parameterAnnotations, _) = GetCorrespondingParameter(i, parametersOpt, argsToParamsOpt, expanded); if (parameter is null) { continue; } VisitArgumentOutboundAssignmentsAndPostConditions( arguments[i], GetRefKind(refKindsOpt, i), parameter, parameterType, parameterAnnotations, results[i], notNullParametersBuilder, (!compareExchangeInfo.IsDefault && parameter.Ordinal == 0) ? compareExchangeInfo : default); } } else { for (int i = 0; i < arguments.Length; i++) { // We can hit this case when dynamic methods are involved, or when there are errors. In either case we have no information, // so just assume that the conversions have the same nullability as the underlying result var argument = arguments[i]; var result = results[i]; var argumentNoConversion = argumentsNoConversions[i]; TrackAnalyzedNullabilityThroughConversionGroup(TypeWithState.Create(argument.Type, result.RValueType.State), argument as BoundConversion, argumentNoConversion); } } if (!IsAnalyzingAttribute && method is object && (method.FlowAnalysisAnnotations & FlowAnalysisAnnotations.DoesNotReturn) == FlowAnalysisAnnotations.DoesNotReturn) { SetUnreachable(); } notNullParametersBuilder?.Free(); return (method, results, shouldReturnNotNull); } private void ApplyMemberPostConditions(BoundExpression? receiverOpt, MethodSymbol? method) { if (method is null) { return; } int receiverSlot = method.IsStatic ? 0 : receiverOpt is null ? -1 : MakeSlot(receiverOpt); if (receiverSlot < 0) { return; } ApplyMemberPostConditions(receiverSlot, method); } private void ApplyMemberPostConditions(int receiverSlot, MethodSymbol method) { Debug.Assert(receiverSlot >= 0); do { var type = method.ContainingType; var notNullMembers = method.NotNullMembers; var notNullWhenTrueMembers = method.NotNullWhenTrueMembers; var notNullWhenFalseMembers = method.NotNullWhenFalseMembers; if (IsConditionalState) { applyMemberPostConditions(receiverSlot, type, notNullMembers, ref StateWhenTrue); applyMemberPostConditions(receiverSlot, type, notNullMembers, ref StateWhenFalse); } else { applyMemberPostConditions(receiverSlot, type, notNullMembers, ref State); } if (!notNullWhenTrueMembers.IsEmpty || !notNullWhenFalseMembers.IsEmpty) { Split(); applyMemberPostConditions(receiverSlot, type, notNullWhenTrueMembers, ref StateWhenTrue); applyMemberPostConditions(receiverSlot, type, notNullWhenFalseMembers, ref StateWhenFalse); } method = method.OverriddenMethod; } while (method != null); void applyMemberPostConditions(int receiverSlot, TypeSymbol type, ImmutableArray<string> members, ref LocalState state) { if (members.IsEmpty) { return; } foreach (var memberName in members) { markMembersAsNotNull(receiverSlot, type, memberName, ref state); } } void markMembersAsNotNull(int receiverSlot, TypeSymbol type, string memberName, ref LocalState state) { foreach (Symbol member in type.GetMembers(memberName)) { if (member.IsStatic) { receiverSlot = 0; } switch (member.Kind) { case SymbolKind.Field: case SymbolKind.Property: if (GetOrCreateSlot(member, receiverSlot) is int memberSlot && memberSlot > 0) { state[memberSlot] = NullableFlowState.NotNull; } break; case SymbolKind.Event: case SymbolKind.Method: break; } } } } private ImmutableArray<VisitArgumentResult> VisitArgumentsEvaluate( SyntaxNode syntax, ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> refKindsOpt, ImmutableArray<ParameterSymbol> parametersOpt, ImmutableArray<int> argsToParamsOpt, BitVector defaultArguments, bool expanded) { Debug.Assert(!IsConditionalState); int n = arguments.Length; if (n == 0 && parametersOpt.IsDefaultOrEmpty) { return ImmutableArray<VisitArgumentResult>.Empty; } var visitedParameters = PooledHashSet<ParameterSymbol?>.GetInstance(); var resultsBuilder = ArrayBuilder<VisitArgumentResult>.GetInstance(n); var previousDisableDiagnostics = _disableDiagnostics; for (int i = 0; i < n; i++) { var (parameter, _, parameterAnnotations, _) = GetCorrespondingParameter(i, parametersOpt, argsToParamsOpt, expanded); // we disable nullable warnings on default arguments _disableDiagnostics = defaultArguments[i] || previousDisableDiagnostics; resultsBuilder.Add(VisitArgumentEvaluate(arguments[i], GetRefKind(refKindsOpt, i), parameterAnnotations)); visitedParameters.Add(parameter); } _disableDiagnostics = previousDisableDiagnostics; SetInvalidResult(); visitedParameters.Free(); return resultsBuilder.ToImmutableAndFree(); } private VisitArgumentResult VisitArgumentEvaluate(BoundExpression argument, RefKind refKind, FlowAnalysisAnnotations annotations) { Debug.Assert(!IsConditionalState); var savedState = (argument.Kind == BoundKind.Lambda) ? this.State.Clone() : default(Optional<LocalState>); // Note: DoesNotReturnIf is ineffective on ref/out parameters switch (refKind) { case RefKind.Ref: Visit(argument); Unsplit(); break; case RefKind.None: case RefKind.In: switch (annotations & (FlowAnalysisAnnotations.DoesNotReturnIfTrue | FlowAnalysisAnnotations.DoesNotReturnIfFalse)) { case FlowAnalysisAnnotations.DoesNotReturnIfTrue: Visit(argument); if (IsConditionalState) { SetState(StateWhenFalse); } break; case FlowAnalysisAnnotations.DoesNotReturnIfFalse: Visit(argument); if (IsConditionalState) { SetState(StateWhenTrue); } break; default: VisitRvalue(argument); break; } break; case RefKind.Out: // As far as we can tell, there is no scenario relevant to nullability analysis // where splitting an L-value (for instance with a ref conditional) would affect the result. Visit(argument); // We'll want to use the l-value type, rather than the result type, for method re-inference UseLvalueOnly(argument); break; } Debug.Assert(!IsConditionalState); return new VisitArgumentResult(_visitResult, savedState); } /// <summary> /// Verifies that an argument's nullability is compatible with its parameter's on the way in. /// </summary> private void VisitArgumentConversionAndInboundAssignmentsAndPreConditions( BoundConversion? conversionOpt, BoundExpression argumentNoConversion, Conversion conversion, RefKind refKind, ParameterSymbol parameter, TypeWithAnnotations parameterType, FlowAnalysisAnnotations parameterAnnotations, VisitArgumentResult result, bool extensionMethodThisArgument) { Debug.Assert(!this.IsConditionalState); // Note: we allow for some variance in `in` and `out` cases. Unlike in binding, we're not // limited by CLR constraints. var resultType = result.RValueType; switch (refKind) { case RefKind.None: case RefKind.In: { // Note: for lambda arguments, they will be converted in the context/state we saved for that argument if (conversion is { Kind: ConversionKind.ImplicitUserDefined }) { var argumentResultType = resultType.Type; conversion = GenerateConversion(_conversions, argumentNoConversion, argumentResultType, parameterType.Type, fromExplicitCast: false, extensionMethodThisArgument: false); if (!conversion.Exists && !argumentNoConversion.IsSuppressed) { Debug.Assert(argumentResultType is not null); ReportNullabilityMismatchInArgument(argumentNoConversion.Syntax, argumentResultType, parameter, parameterType.Type, forOutput: false); } } var stateAfterConversion = VisitConversion( conversionOpt: conversionOpt, conversionOperand: argumentNoConversion, conversion: conversion, targetTypeWithNullability: ApplyLValueAnnotations(parameterType, parameterAnnotations), operandType: resultType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, assignmentKind: AssignmentKind.Argument, parameterOpt: parameter, extensionMethodThisArgument: extensionMethodThisArgument, stateForLambda: result.StateForLambda); // If the parameter has annotations, we perform an additional check for nullable value types if (CheckDisallowedNullAssignment(stateAfterConversion, parameterAnnotations, argumentNoConversion.Syntax.Location)) { LearnFromNonNullTest(argumentNoConversion, ref State); } SetResultType(argumentNoConversion, stateAfterConversion, updateAnalyzedNullability: false); } break; case RefKind.Ref: if (!argumentNoConversion.IsSuppressed) { var lvalueResultType = result.LValueType; if (IsNullabilityMismatch(lvalueResultType.Type, parameterType.Type)) { // declared types must match, ignoring top-level nullability ReportNullabilityMismatchInRefArgument(argumentNoConversion, argumentType: lvalueResultType.Type, parameter, parameterType.Type); } else { // types match, but state would let a null in ReportNullableAssignmentIfNecessary(argumentNoConversion, ApplyLValueAnnotations(parameterType, parameterAnnotations), resultType, useLegacyWarnings: false); // If the parameter has annotations, we perform an additional check for nullable value types CheckDisallowedNullAssignment(resultType, parameterAnnotations, argumentNoConversion.Syntax.Location); } } break; case RefKind.Out: break; default: throw ExceptionUtilities.UnexpectedValue(refKind); } Debug.Assert(!this.IsConditionalState); } /// <summary>Returns <see langword="true"/> if this is an assignment forbidden by DisallowNullAttribute, otherwise <see langword="false"/>.</summary> private bool CheckDisallowedNullAssignment(TypeWithState state, FlowAnalysisAnnotations annotations, Location location, BoundExpression? boundValueOpt = null) { if (boundValueOpt is { WasCompilerGenerated: true }) { // We need to skip `return backingField;` in auto-prop getters return false; } // We do this extra check for types whose non-nullable version cannot be represented if (IsDisallowedNullAssignment(state, annotations)) { ReportDiagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, location); return true; } return false; } private static bool IsDisallowedNullAssignment(TypeWithState valueState, FlowAnalysisAnnotations targetAnnotations) { return ((targetAnnotations & FlowAnalysisAnnotations.DisallowNull) != 0) && hasNoNonNullableCounterpart(valueState.Type) && valueState.MayBeNull; static bool hasNoNonNullableCounterpart(TypeSymbol? type) { if (type is null) { return false; } // Some types that could receive a maybe-null value have a NotNull counterpart: // [NotNull]string? -> string // [NotNull]string -> string // [NotNull]TClass -> TClass // [NotNull]TClass? -> TClass // // While others don't: // [NotNull]int? -> X // [NotNull]TNullable -> X // [NotNull]TStruct? -> X // [NotNull]TOpen -> X return (type.Kind == SymbolKind.TypeParameter && !type.IsReferenceType) || type.IsNullableTypeOrTypeParameter(); } } /// <summary> /// Verifies that outbound assignments (from parameter to argument) are safe and /// tracks those assignments (or learns from post-condition attributes) /// </summary> private void VisitArgumentOutboundAssignmentsAndPostConditions( BoundExpression argument, RefKind refKind, ParameterSymbol parameter, TypeWithAnnotations parameterType, FlowAnalysisAnnotations parameterAnnotations, VisitArgumentResult result, ArrayBuilder<ParameterSymbol>? notNullParametersOpt, CompareExchangeInfo compareExchangeInfoOpt) { // Note: the state may be conditional if a previous argument involved a conditional post-condition // The WhenTrue/False states correspond to the invocation returning true/false switch (refKind) { case RefKind.None: case RefKind.In: { // learn from post-conditions [Maybe/NotNull, Maybe/NotNullWhen] without using an assignment learnFromPostConditions(argument, parameterType, parameterAnnotations); } break; case RefKind.Ref: { // assign from a fictional value from the parameter to the argument. parameterAnnotations = notNullBasedOnParameters(parameterAnnotations, notNullParametersOpt, parameter); var parameterWithState = TypeWithState.Create(parameterType, parameterAnnotations); if (!compareExchangeInfoOpt.IsDefault) { var adjustedState = LearnFromCompareExchangeMethod(in compareExchangeInfoOpt); parameterWithState = TypeWithState.Create(parameterType.Type, adjustedState); } var parameterValue = new BoundParameter(argument.Syntax, parameter); var lValueType = result.LValueType; trackNullableStateForAssignment(parameterValue, lValueType, MakeSlot(argument), parameterWithState, argument.IsSuppressed, parameterAnnotations); // check whether parameter would unsafely let a null out in the worse case if (!argument.IsSuppressed) { var leftAnnotations = GetLValueAnnotations(argument); ReportNullableAssignmentIfNecessary( parameterValue, targetType: ApplyLValueAnnotations(lValueType, leftAnnotations), valueType: applyPostConditionsUnconditionally(parameterWithState, parameterAnnotations), UseLegacyWarnings(argument, result.LValueType)); } } break; case RefKind.Out: { // compute the fictional parameter state parameterAnnotations = notNullBasedOnParameters(parameterAnnotations, notNullParametersOpt, parameter); var parameterWithState = TypeWithState.Create(parameterType, parameterAnnotations); // Adjust parameter state if MaybeNull or MaybeNullWhen are present (for `var` type and for assignment warnings) var worstCaseParameterWithState = applyPostConditionsUnconditionally(parameterWithState, parameterAnnotations); var declaredType = result.LValueType; var leftAnnotations = GetLValueAnnotations(argument); var lValueType = ApplyLValueAnnotations(declaredType, leftAnnotations); if (argument is BoundLocal local && local.DeclarationKind == BoundLocalDeclarationKind.WithInferredType) { var varType = worstCaseParameterWithState.ToAnnotatedTypeWithAnnotations(compilation); _variables.SetType(local.LocalSymbol, varType); lValueType = varType; } else if (argument is BoundDiscardExpression discard) { SetAnalyzedNullability(discard, new VisitResult(parameterWithState, parameterWithState.ToTypeWithAnnotations(compilation)), isLvalue: true); } // track state by assigning from a fictional value from the parameter to the argument. var parameterValue = new BoundParameter(argument.Syntax, parameter); // If the argument type has annotations, we perform an additional check for nullable value types CheckDisallowedNullAssignment(parameterWithState, leftAnnotations, argument.Syntax.Location); AdjustSetValue(argument, ref parameterWithState); trackNullableStateForAssignment(parameterValue, lValueType, MakeSlot(argument), parameterWithState, argument.IsSuppressed, parameterAnnotations); // report warnings if parameter would unsafely let a null out in the worst case if (!argument.IsSuppressed) { ReportNullableAssignmentIfNecessary(parameterValue, lValueType, worstCaseParameterWithState, UseLegacyWarnings(argument, result.LValueType)); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; if (!_conversions.HasIdentityOrImplicitReferenceConversion(parameterType.Type, lValueType.Type, ref discardedUseSiteInfo)) { ReportNullabilityMismatchInArgument(argument.Syntax, lValueType.Type, parameter, parameterType.Type, forOutput: true); } } } break; default: throw ExceptionUtilities.UnexpectedValue(refKind); } FlowAnalysisAnnotations notNullBasedOnParameters(FlowAnalysisAnnotations parameterAnnotations, ArrayBuilder<ParameterSymbol>? notNullParametersOpt, ParameterSymbol parameter) { if (!IsAnalyzingAttribute && notNullParametersOpt is object) { var notNullIfParameterNotNull = parameter.NotNullIfParameterNotNull; if (!notNullIfParameterNotNull.IsEmpty) { foreach (var notNullParameter in notNullParametersOpt) { if (notNullIfParameterNotNull.Contains(notNullParameter.Name)) { return FlowAnalysisAnnotations.NotNull; } } } } return parameterAnnotations; } void trackNullableStateForAssignment(BoundExpression parameterValue, TypeWithAnnotations lValueType, int targetSlot, TypeWithState parameterWithState, bool isSuppressed, FlowAnalysisAnnotations parameterAnnotations) { if (!IsConditionalState && !hasConditionalPostCondition(parameterAnnotations)) { TrackNullableStateForAssignment(parameterValue, lValueType, targetSlot, parameterWithState.WithSuppression(isSuppressed)); } else { Split(); var originalWhenFalse = StateWhenFalse.Clone(); SetState(StateWhenTrue); // Note: the suppression applies over the post-condition attributes TrackNullableStateForAssignment(parameterValue, lValueType, targetSlot, applyPostConditionsWhenTrue(parameterWithState, parameterAnnotations).WithSuppression(isSuppressed)); Debug.Assert(!IsConditionalState); var newWhenTrue = State.Clone(); SetState(originalWhenFalse); TrackNullableStateForAssignment(parameterValue, lValueType, targetSlot, applyPostConditionsWhenFalse(parameterWithState, parameterAnnotations).WithSuppression(isSuppressed)); Debug.Assert(!IsConditionalState); SetConditionalState(newWhenTrue, whenFalse: State); } } static bool hasConditionalPostCondition(FlowAnalysisAnnotations annotations) { return (((annotations & FlowAnalysisAnnotations.MaybeNullWhenTrue) != 0) ^ ((annotations & FlowAnalysisAnnotations.MaybeNullWhenFalse) != 0)) || (((annotations & FlowAnalysisAnnotations.NotNullWhenTrue) != 0) ^ ((annotations & FlowAnalysisAnnotations.NotNullWhenFalse) != 0)); } static TypeWithState applyPostConditionsUnconditionally(TypeWithState typeWithState, FlowAnalysisAnnotations annotations) { if ((annotations & FlowAnalysisAnnotations.MaybeNull) != 0) { // MaybeNull and MaybeNullWhen return TypeWithState.Create(typeWithState.Type, NullableFlowState.MaybeDefault); } if ((annotations & FlowAnalysisAnnotations.NotNull) == FlowAnalysisAnnotations.NotNull) { // NotNull return TypeWithState.Create(typeWithState.Type, NullableFlowState.NotNull); } return typeWithState; } static TypeWithState applyPostConditionsWhenTrue(TypeWithState typeWithState, FlowAnalysisAnnotations annotations) { bool notNullWhenTrue = (annotations & FlowAnalysisAnnotations.NotNullWhenTrue) != 0; bool maybeNullWhenTrue = (annotations & FlowAnalysisAnnotations.MaybeNullWhenTrue) != 0; bool maybeNullWhenFalse = (annotations & FlowAnalysisAnnotations.MaybeNullWhenFalse) != 0; if (maybeNullWhenTrue && !(maybeNullWhenFalse && notNullWhenTrue)) { // [MaybeNull, NotNullWhen(true)] means [MaybeNullWhen(false)] return TypeWithState.Create(typeWithState.Type, NullableFlowState.MaybeDefault); } else if (notNullWhenTrue) { return TypeWithState.Create(typeWithState.Type, NullableFlowState.NotNull); } return typeWithState; } static TypeWithState applyPostConditionsWhenFalse(TypeWithState typeWithState, FlowAnalysisAnnotations annotations) { bool notNullWhenFalse = (annotations & FlowAnalysisAnnotations.NotNullWhenFalse) != 0; bool maybeNullWhenTrue = (annotations & FlowAnalysisAnnotations.MaybeNullWhenTrue) != 0; bool maybeNullWhenFalse = (annotations & FlowAnalysisAnnotations.MaybeNullWhenFalse) != 0; if (maybeNullWhenFalse && !(maybeNullWhenTrue && notNullWhenFalse)) { // [MaybeNull, NotNullWhen(false)] means [MaybeNullWhen(true)] return TypeWithState.Create(typeWithState.Type, NullableFlowState.MaybeDefault); } else if (notNullWhenFalse) { return TypeWithState.Create(typeWithState.Type, NullableFlowState.NotNull); } return typeWithState; } void learnFromPostConditions(BoundExpression argument, TypeWithAnnotations parameterType, FlowAnalysisAnnotations parameterAnnotations) { // Note: NotNull = NotNullWhen(true) + NotNullWhen(false) bool notNullWhenTrue = (parameterAnnotations & FlowAnalysisAnnotations.NotNullWhenTrue) != 0; bool notNullWhenFalse = (parameterAnnotations & FlowAnalysisAnnotations.NotNullWhenFalse) != 0; // Note: MaybeNull = MaybeNullWhen(true) + MaybeNullWhen(false) bool maybeNullWhenTrue = (parameterAnnotations & FlowAnalysisAnnotations.MaybeNullWhenTrue) != 0; bool maybeNullWhenFalse = (parameterAnnotations & FlowAnalysisAnnotations.MaybeNullWhenFalse) != 0; if (maybeNullWhenTrue && maybeNullWhenFalse && !IsConditionalState && !(notNullWhenTrue && notNullWhenFalse)) { LearnFromNullTest(argument, ref State); } else if (notNullWhenTrue && notNullWhenFalse && !IsConditionalState && !(maybeNullWhenTrue || maybeNullWhenFalse)) { LearnFromNonNullTest(argument, ref State); } else if (notNullWhenTrue || notNullWhenFalse || maybeNullWhenTrue || maybeNullWhenFalse) { Split(); if (notNullWhenTrue) { LearnFromNonNullTest(argument, ref StateWhenTrue); } if (notNullWhenFalse) { LearnFromNonNullTest(argument, ref StateWhenFalse); } if (maybeNullWhenTrue) { LearnFromNullTest(argument, ref StateWhenTrue); } if (maybeNullWhenFalse) { LearnFromNullTest(argument, ref StateWhenFalse); } } } } private (ImmutableArray<BoundExpression> arguments, ImmutableArray<Conversion> conversions) RemoveArgumentConversions( ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> refKindsOpt) { int n = arguments.Length; var conversions = default(ImmutableArray<Conversion>); if (n > 0) { var argumentsBuilder = ArrayBuilder<BoundExpression>.GetInstance(n); var conversionsBuilder = ArrayBuilder<Conversion>.GetInstance(n); bool includedConversion = false; for (int i = 0; i < n; i++) { RefKind refKind = GetRefKind(refKindsOpt, i); var argument = arguments[i]; var conversion = Conversion.Identity; if (refKind == RefKind.None) { var before = argument; (argument, conversion) = RemoveConversion(argument, includeExplicitConversions: false); if (argument != before) { SnapshotWalkerThroughConversionGroup(before, argument); includedConversion = true; } } argumentsBuilder.Add(argument); conversionsBuilder.Add(conversion); } if (includedConversion) { arguments = argumentsBuilder.ToImmutable(); conversions = conversionsBuilder.ToImmutable(); } argumentsBuilder.Free(); conversionsBuilder.Free(); } return (arguments, conversions); } private static VariableState GetVariableState(Variables variables, LocalState localState) { Debug.Assert(variables.Id == localState.Id); return new VariableState(variables.CreateSnapshot(), localState.CreateSnapshot()); } private (ParameterSymbol? Parameter, TypeWithAnnotations Type, FlowAnalysisAnnotations Annotations, bool isExpandedParamsArgument) GetCorrespondingParameter( int argumentOrdinal, ImmutableArray<ParameterSymbol> parametersOpt, ImmutableArray<int> argsToParamsOpt, bool expanded) { if (parametersOpt.IsDefault) { return default; } var parameter = Binder.GetCorrespondingParameter(argumentOrdinal, parametersOpt, argsToParamsOpt, expanded); if (parameter is null) { Debug.Assert(!expanded); return default; } var type = parameter.TypeWithAnnotations; if (expanded && parameter.Ordinal == parametersOpt.Length - 1 && type.IsSZArray()) { type = ((ArrayTypeSymbol)type.Type).ElementTypeWithAnnotations; return (parameter, type, FlowAnalysisAnnotations.None, isExpandedParamsArgument: true); } return (parameter, type, GetParameterAnnotations(parameter), isExpandedParamsArgument: false); } private MethodSymbol InferMethodTypeArguments( MethodSymbol method, ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> argumentRefKindsOpt, ImmutableArray<int> argsToParamsOpt, bool expanded) { Debug.Assert(method.IsGenericMethod); // https://github.com/dotnet/roslyn/issues/27961 OverloadResolution.IsMemberApplicableInNormalForm and // IsMemberApplicableInExpandedForm use the least overridden method. We need to do the same here. var definition = method.ConstructedFrom; var refKinds = ArrayBuilder<RefKind>.GetInstance(); if (argumentRefKindsOpt != null) { refKinds.AddRange(argumentRefKindsOpt); } // https://github.com/dotnet/roslyn/issues/27961 Do we really need OverloadResolution.GetEffectiveParameterTypes? // Aren't we doing roughly the same calculations in GetCorrespondingParameter? OverloadResolution.GetEffectiveParameterTypes( definition, arguments.Length, argsToParamsOpt, refKinds, isMethodGroupConversion: false, // https://github.com/dotnet/roslyn/issues/27961 `allowRefOmittedArguments` should be // false for constructors and several other cases (see Binder use). Should we // capture the original value in the BoundCall? allowRefOmittedArguments: true, binder: _binder, expanded: expanded, parameterTypes: out ImmutableArray<TypeWithAnnotations> parameterTypes, parameterRefKinds: out ImmutableArray<RefKind> parameterRefKinds); refKinds.Free(); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var result = MethodTypeInferrer.Infer( _binder, _conversions, definition.TypeParameters, definition.ContainingType, parameterTypes, parameterRefKinds, arguments, ref discardedUseSiteInfo, new MethodInferenceExtensions(this)); if (!result.Success) { return method; } return definition.Construct(result.InferredTypeArguments); } private sealed class MethodInferenceExtensions : MethodTypeInferrer.Extensions { private readonly NullableWalker _walker; internal MethodInferenceExtensions(NullableWalker walker) { _walker = walker; } internal override TypeWithAnnotations GetTypeWithAnnotations(BoundExpression expr) { return TypeWithAnnotations.Create(expr.GetTypeOrFunctionType(), GetNullableAnnotation(expr)); } /// <summary> /// Return top-level nullability for the expression. This method should be called on a limited /// set of expressions only. It should not be called on expressions tracked by flow analysis /// other than <see cref="BoundKind.ExpressionWithNullability"/> which is an expression /// specifically created in NullableWalker to represent the flow analysis state. /// </summary> private static NullableAnnotation GetNullableAnnotation(BoundExpression expr) { switch (expr.Kind) { case BoundKind.DefaultLiteral: case BoundKind.DefaultExpression: case BoundKind.Literal: return expr.ConstantValue == ConstantValue.NotAvailable || !expr.ConstantValue.IsNull || expr.IsSuppressed ? NullableAnnotation.NotAnnotated : NullableAnnotation.Annotated; case BoundKind.ExpressionWithNullability: return ((BoundExpressionWithNullability)expr).NullableAnnotation; case BoundKind.MethodGroup: case BoundKind.UnboundLambda: case BoundKind.UnconvertedObjectCreationExpression: case BoundKind.ConvertedTupleLiteral: return NullableAnnotation.NotAnnotated; default: Debug.Assert(false); // unexpected value return NullableAnnotation.Oblivious; } } internal override TypeWithAnnotations GetMethodGroupResultType(BoundMethodGroup group, MethodSymbol method) { if (_walker.TryGetMethodGroupReceiverNullability(group.ReceiverOpt, out TypeWithState receiverType)) { if (!method.IsStatic) { method = (MethodSymbol)AsMemberOfType(receiverType.Type, method); } } return method.ReturnTypeWithAnnotations; } } private ImmutableArray<BoundExpression> GetArgumentsForMethodTypeInference(ImmutableArray<VisitArgumentResult> argumentResults, ImmutableArray<BoundExpression> arguments) { // https://github.com/dotnet/roslyn/issues/27961 MethodTypeInferrer.Infer relies // on the BoundExpressions for tuple element types and method groups. // By using a generic BoundValuePlaceholder, we're losing inference in those cases. // https://github.com/dotnet/roslyn/issues/27961 Inference should be based on // unconverted arguments. Consider cases such as `default`, lambdas, tuples. int n = argumentResults.Length; var builder = ArrayBuilder<BoundExpression>.GetInstance(n); for (int i = 0; i < n; i++) { var visitArgumentResult = argumentResults[i]; var lambdaState = visitArgumentResult.StateForLambda; // Note: for `out` arguments, the argument result contains the declaration type (see `VisitArgumentEvaluate`) var argumentResult = visitArgumentResult.RValueType.ToTypeWithAnnotations(compilation); builder.Add(getArgumentForMethodTypeInference(arguments[i], argumentResult, lambdaState)); } return builder.ToImmutableAndFree(); BoundExpression getArgumentForMethodTypeInference(BoundExpression argument, TypeWithAnnotations argumentType, Optional<LocalState> lambdaState) { if (argument.Kind == BoundKind.Lambda) { Debug.Assert(lambdaState.HasValue); // MethodTypeInferrer must infer nullability for lambdas based on the nullability // from flow analysis rather than the declared nullability. To allow that, we need // to re-bind lambdas in MethodTypeInferrer. return getUnboundLambda((BoundLambda)argument, GetVariableState(_variables, lambdaState.Value)); } if (!argumentType.HasType) { return argument; } if (argument is BoundLocal { DeclarationKind: BoundLocalDeclarationKind.WithInferredType } or BoundConditionalOperator { WasTargetTyped: true } or BoundConvertedSwitchExpression { WasTargetTyped: true }) { // target-typed contexts don't contribute to nullability return new BoundExpressionWithNullability(argument.Syntax, argument, NullableAnnotation.Oblivious, type: null); } return new BoundExpressionWithNullability(argument.Syntax, argument, argumentType.NullableAnnotation, argumentType.Type); } static UnboundLambda getUnboundLambda(BoundLambda expr, VariableState variableState) { return expr.UnboundLambda.WithNullableState(variableState); } } private void CheckMethodConstraints(SyntaxNode syntax, MethodSymbol method) { if (_disableDiagnostics) { return; } var diagnosticsBuilder = ArrayBuilder<TypeParameterDiagnosticInfo>.GetInstance(); var nullabilityBuilder = ArrayBuilder<TypeParameterDiagnosticInfo>.GetInstance(); ArrayBuilder<TypeParameterDiagnosticInfo>? useSiteDiagnosticsBuilder = null; ConstraintsHelper.CheckMethodConstraints( method, new ConstraintsHelper.CheckConstraintsArgs(compilation, _conversions, includeNullability: true, NoLocation.Singleton, diagnostics: null, template: CompoundUseSiteInfo<AssemblySymbol>.Discarded), diagnosticsBuilder, nullabilityBuilder, ref useSiteDiagnosticsBuilder); foreach (var pair in nullabilityBuilder) { if (pair.UseSiteInfo.DiagnosticInfo is object) { Diagnostics.Add(pair.UseSiteInfo.DiagnosticInfo, syntax.Location); } } useSiteDiagnosticsBuilder?.Free(); nullabilityBuilder.Free(); diagnosticsBuilder.Free(); } /// <summary> /// Returns the expression without the top-most conversion plus the conversion. /// If the expression is not a conversion, returns the original expression plus /// the Identity conversion. If `includeExplicitConversions` is true, implicit and /// explicit conversions are considered. If `includeExplicitConversions` is false /// only implicit conversions are considered and if the expression is an explicit /// conversion, the expression is returned as is, with the Identity conversion. /// (Currently, the only visit method that passes `includeExplicitConversions: true` /// is VisitConversion. All other callers are handling implicit conversions only.) /// </summary> private static (BoundExpression expression, Conversion conversion) RemoveConversion(BoundExpression expr, bool includeExplicitConversions) { ConversionGroup? group = null; while (true) { if (expr.Kind != BoundKind.Conversion) { break; } var conversion = (BoundConversion)expr; if (group != conversion.ConversionGroupOpt && group != null) { // E.g.: (C)(B)a break; } group = conversion.ConversionGroupOpt; Debug.Assert(group != null || !conversion.ExplicitCastInCode); // Explicit conversions should include a group. if (!includeExplicitConversions && group?.IsExplicitConversion == true) { return (expr, Conversion.Identity); } expr = conversion.Operand; if (group == null) { // Ungrouped conversion should not be followed by another ungrouped // conversion. Otherwise, the conversions should have been grouped. // https://github.com/dotnet/roslyn/issues/34919 This assertion does not always hold true for // enum initializers //Debug.Assert(expr.Kind != BoundKind.Conversion || // ((BoundConversion)expr).ConversionGroupOpt != null || // ((BoundConversion)expr).ConversionKind == ConversionKind.NoConversion); return (expr, conversion.Conversion); } } return (expr, group?.Conversion ?? Conversion.Identity); } // See Binder.BindNullCoalescingOperator for initial binding. private Conversion GenerateConversionForConditionalOperator(BoundExpression sourceExpression, TypeSymbol? sourceType, TypeSymbol destinationType, bool reportMismatch) { var conversion = GenerateConversion(_conversions, sourceExpression, sourceType, destinationType, fromExplicitCast: false, extensionMethodThisArgument: false); bool canConvertNestedNullability = conversion.Exists; if (!canConvertNestedNullability && reportMismatch && !sourceExpression.IsSuppressed) { ReportNullabilityMismatchInAssignment(sourceExpression.Syntax, GetTypeAsDiagnosticArgument(sourceType), destinationType); } return conversion; } private static Conversion GenerateConversion(Conversions conversions, BoundExpression? sourceExpression, TypeSymbol? sourceType, TypeSymbol destinationType, bool fromExplicitCast, bool extensionMethodThisArgument) { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; bool useExpression = sourceType is null || UseExpressionForConversion(sourceExpression); if (extensionMethodThisArgument) { return conversions.ClassifyImplicitExtensionMethodThisArgConversion( useExpression ? sourceExpression : null, sourceType, destinationType, ref discardedUseSiteInfo); } return useExpression ? (fromExplicitCast ? conversions.ClassifyConversionFromExpression(sourceExpression, destinationType, ref discardedUseSiteInfo, forCast: true) : conversions.ClassifyImplicitConversionFromExpression(sourceExpression!, destinationType, ref discardedUseSiteInfo)) : (fromExplicitCast ? conversions.ClassifyConversionFromType(sourceType, destinationType, ref discardedUseSiteInfo, forCast: true) : conversions.ClassifyImplicitConversionFromType(sourceType!, destinationType, ref discardedUseSiteInfo)); } /// <summary> /// Returns true if the expression should be used as the source when calculating /// a conversion from this expression, rather than using the type (with nullability) /// calculated by visiting this expression. Typically, that means expressions that /// do not have an explicit type but there are several other cases as well. /// (See expressions handled in ClassifyImplicitBuiltInConversionFromExpression.) /// </summary> private static bool UseExpressionForConversion([NotNullWhen(true)] BoundExpression? value) { if (value is null) { return false; } if (value.Type is null || value.Type.IsDynamic() || value.ConstantValue != null) { return true; } switch (value.Kind) { case BoundKind.InterpolatedString: return true; default: return false; } } /// <summary> /// Adjust declared type based on inferred nullability at the point of reference. /// </summary> private TypeWithState GetAdjustedResult(TypeWithState type, int slot) { if (this.State.HasValue(slot)) { NullableFlowState state = this.State[slot]; return TypeWithState.Create(type.Type, state); } return type; } /// <summary> /// Gets the corresponding member for a symbol from initial binding to match an updated receiver type in NullableWalker. /// For instance, this will map from List&lt;string~&gt;.Add(string~) to List&lt;string?&gt;.Add(string?) in the following example: /// <example> /// string s = null; /// var list = new[] { s }.ToList(); /// list.Add(null); /// </example> /// </summary> private static Symbol AsMemberOfType(TypeSymbol? type, Symbol symbol) { Debug.Assert((object)symbol != null); var containingType = type as NamedTypeSymbol; if (containingType is null || containingType.IsErrorType() || symbol is ErrorMethodSymbol) { return symbol; } if (symbol.Kind == SymbolKind.Method) { if (((MethodSymbol)symbol).MethodKind == MethodKind.LocalFunction) { // https://github.com/dotnet/roslyn/issues/27233 Handle type substitution for local functions. return symbol; } } if (symbol is TupleElementFieldSymbol or TupleErrorFieldSymbol) { return symbol.SymbolAsMember(containingType); } var symbolContainer = symbol.ContainingType; if (symbolContainer.IsAnonymousType) { int? memberIndex = symbol.Kind == SymbolKind.Property ? symbol.MemberIndexOpt : null; if (!memberIndex.HasValue) { return symbol; } return AnonymousTypeManager.GetAnonymousTypeProperty(containingType, memberIndex.GetValueOrDefault()); } if (!symbolContainer.IsGenericType) { Debug.Assert(symbol.ContainingType.IsDefinition); return symbol; } if (!containingType.IsGenericType) { return symbol; } if (symbolContainer.IsInterface) { if (tryAsMemberOfSingleType(containingType, out var result)) { return result; } foreach (var @interface in containingType.AllInterfacesNoUseSiteDiagnostics) { if (tryAsMemberOfSingleType(@interface, out result)) { return result; } } } else { while (true) { if (tryAsMemberOfSingleType(containingType, out var result)) { return result; } containingType = containingType.BaseTypeNoUseSiteDiagnostics; if ((object)containingType == null) { break; } } } Debug.Assert(false); // If this assert fails, add an appropriate test. return symbol; bool tryAsMemberOfSingleType(NamedTypeSymbol singleType, [NotNullWhen(true)] out Symbol? result) { if (!singleType.Equals(symbolContainer, TypeCompareKind.AllIgnoreOptions)) { result = null; return false; } var symbolDef = symbol.OriginalDefinition; result = symbolDef.SymbolAsMember(singleType); if (result is MethodSymbol resultMethod && resultMethod.IsGenericMethod) { result = resultMethod.Construct(((MethodSymbol)symbol).TypeArgumentsWithAnnotations); } return true; } } public override BoundNode? VisitConversion(BoundConversion node) { // https://github.com/dotnet/roslyn/issues/35732: Assert VisitConversion is only used for explicit conversions. //Debug.Assert(node.ExplicitCastInCode); //Debug.Assert(node.ConversionGroupOpt != null); //Debug.Assert(node.ConversionGroupOpt.ExplicitType.HasType); TypeWithAnnotations explicitType = node.ConversionGroupOpt?.ExplicitType ?? default; bool fromExplicitCast = explicitType.HasType; TypeWithAnnotations targetType = fromExplicitCast ? explicitType : TypeWithAnnotations.Create(node.Type); Debug.Assert(targetType.HasType); (BoundExpression operand, Conversion conversion) = RemoveConversion(node, includeExplicitConversions: true); SnapshotWalkerThroughConversionGroup(node, operand); TypeWithState operandType = VisitRvalueWithState(operand); SetResultType(node, VisitConversion( node, operand, conversion, targetType, operandType, checkConversion: true, fromExplicitCast: fromExplicitCast, useLegacyWarnings: fromExplicitCast, AssignmentKind.Assignment, reportTopLevelWarnings: fromExplicitCast, reportRemainingWarnings: true, trackMembers: true)); return null; } /// <summary> /// Visit an expression. If an explicit target type is provided, the expression is converted /// to that type. This method should be called whenever an expression may contain /// an implicit conversion, even if that conversion was omitted from the bound tree, /// so the conversion can be re-classified with nullability. /// </summary> private TypeWithState VisitOptionalImplicitConversion(BoundExpression expr, TypeWithAnnotations targetTypeOpt, bool useLegacyWarnings, bool trackMembers, AssignmentKind assignmentKind) { if (!targetTypeOpt.HasType) { return VisitRvalueWithState(expr); } (BoundExpression operand, Conversion conversion) = RemoveConversion(expr, includeExplicitConversions: false); SnapshotWalkerThroughConversionGroup(expr, operand); var operandType = VisitRvalueWithState(operand); // If an explicit conversion was used in place of an implicit conversion, the explicit // conversion was created by initial binding after reporting "error CS0266: // Cannot implicitly convert type '...' to '...'. An explicit conversion exists ...". // Since an error was reported, we don't need to report nested warnings as well. bool reportNestedWarnings = !conversion.IsExplicit; var resultType = VisitConversion( GetConversionIfApplicable(expr, operand), operand, conversion, targetTypeOpt, operandType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: useLegacyWarnings, assignmentKind, reportTopLevelWarnings: true, reportRemainingWarnings: reportNestedWarnings, trackMembers: trackMembers); return resultType; } private static bool AreNullableAndUnderlyingTypes([NotNullWhen(true)] TypeSymbol? nullableTypeOpt, [NotNullWhen(true)] TypeSymbol? underlyingTypeOpt, out TypeWithAnnotations underlyingTypeWithAnnotations) { if (nullableTypeOpt?.IsNullableType() == true && underlyingTypeOpt?.IsNullableType() == false) { var typeArg = nullableTypeOpt.GetNullableUnderlyingTypeWithAnnotations(); if (typeArg.Type.Equals(underlyingTypeOpt, TypeCompareKind.AllIgnoreOptions)) { underlyingTypeWithAnnotations = typeArg; return true; } } underlyingTypeWithAnnotations = default; return false; } public override BoundNode? VisitTupleLiteral(BoundTupleLiteral node) { VisitTupleExpression(node); return null; } public override BoundNode? VisitConvertedTupleLiteral(BoundConvertedTupleLiteral node) { Debug.Assert(!IsConditionalState); var savedState = this.State.Clone(); // Visit the source tuple so that the semantic model can correctly report nullability for it // Disable diagnostics, as we don't want to duplicate any that are produced by visiting the converted literal below VisitWithoutDiagnostics(node.SourceTuple); this.SetState(savedState); VisitTupleExpression(node); return null; } private void VisitTupleExpression(BoundTupleExpression node) { var arguments = node.Arguments; ImmutableArray<TypeWithState> elementTypes = arguments.SelectAsArray((a, w) => w.VisitRvalueWithState(a), this); ImmutableArray<TypeWithAnnotations> elementTypesWithAnnotations = elementTypes.SelectAsArray(a => a.ToTypeWithAnnotations(compilation)); var tupleOpt = (NamedTypeSymbol?)node.Type; if (tupleOpt is null) { SetResultType(node, TypeWithState.Create(null, NullableFlowState.NotNull)); } else { int slot = GetOrCreatePlaceholderSlot(node); if (slot > 0) { this.State[slot] = NullableFlowState.NotNull; TrackNullableStateOfTupleElements(slot, tupleOpt, arguments, elementTypes, argsToParamsOpt: default, useRestField: false); } tupleOpt = tupleOpt.WithElementTypes(elementTypesWithAnnotations); if (!_disableDiagnostics) { var locations = tupleOpt.TupleElements.SelectAsArray((element, location) => element.Locations.FirstOrDefault() ?? location, node.Syntax.Location); tupleOpt.CheckConstraints(new ConstraintsHelper.CheckConstraintsArgs(compilation, _conversions, includeNullability: true, node.Syntax.Location, diagnostics: null), typeSyntax: node.Syntax, locations, nullabilityDiagnosticsOpt: new BindingDiagnosticBag(Diagnostics)); } SetResultType(node, TypeWithState.Create(tupleOpt, NullableFlowState.NotNull)); } } /// <summary> /// Set the nullability of tuple elements for tuples at the point of construction. /// If <paramref name="useRestField"/> is true, the tuple was constructed with an explicit /// 'new ValueTuple' call, in which case the 8-th element, if any, represents the 'Rest' field. /// </summary> private void TrackNullableStateOfTupleElements( int slot, NamedTypeSymbol tupleType, ImmutableArray<BoundExpression> values, ImmutableArray<TypeWithState> types, ImmutableArray<int> argsToParamsOpt, bool useRestField) { Debug.Assert(tupleType.IsTupleType); Debug.Assert(values.Length == types.Length); Debug.Assert(values.Length == (useRestField ? Math.Min(tupleType.TupleElements.Length, NamedTypeSymbol.ValueTupleRestPosition) : tupleType.TupleElements.Length)); if (slot > 0) { var tupleElements = tupleType.TupleElements; int n = values.Length; if (useRestField) { n = Math.Min(n, NamedTypeSymbol.ValueTupleRestPosition - 1); } for (int i = 0; i < n; i++) { var argOrdinal = GetArgumentOrdinalFromParameterOrdinal(i); trackState(values[argOrdinal], tupleElements[i], types[argOrdinal]); } if (useRestField && values.Length == NamedTypeSymbol.ValueTupleRestPosition && tupleType.GetMembers(NamedTypeSymbol.ValueTupleRestFieldName).FirstOrDefault() is FieldSymbol restField) { var argOrdinal = GetArgumentOrdinalFromParameterOrdinal(NamedTypeSymbol.ValueTupleRestPosition - 1); trackState(values[argOrdinal], restField, types[argOrdinal]); } } void trackState(BoundExpression value, FieldSymbol field, TypeWithState valueType) { int targetSlot = GetOrCreateSlot(field, slot); TrackNullableStateForAssignment(value, field.TypeWithAnnotations, targetSlot, valueType, MakeSlot(value)); } int GetArgumentOrdinalFromParameterOrdinal(int parameterOrdinal) { var index = argsToParamsOpt.IsDefault ? parameterOrdinal : argsToParamsOpt.IndexOf(parameterOrdinal); Debug.Assert(index != -1); return index; } } private void TrackNullableStateOfNullableValue(int containingSlot, TypeSymbol containingType, BoundExpression? value, TypeWithState valueType, int valueSlot) { Debug.Assert(containingType.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T); Debug.Assert(containingSlot > 0); Debug.Assert(valueSlot > 0); int targetSlot = GetNullableOfTValueSlot(containingType, containingSlot, out Symbol? symbol); if (targetSlot > 0) { TrackNullableStateForAssignment(value, symbol!.GetTypeOrReturnType(), targetSlot, valueType, valueSlot); } } private void TrackNullableStateOfTupleConversion( BoundConversion? conversionOpt, BoundExpression convertedNode, Conversion conversion, TypeSymbol targetType, TypeSymbol operandType, int slot, int valueSlot, AssignmentKind assignmentKind, ParameterSymbol? parameterOpt, bool reportWarnings) { Debug.Assert(conversion.Kind == ConversionKind.ImplicitTuple || conversion.Kind == ConversionKind.ExplicitTuple); Debug.Assert(slot > 0); Debug.Assert(valueSlot > 0); var valueTuple = operandType as NamedTypeSymbol; if (valueTuple is null || !valueTuple.IsTupleType) { return; } var conversions = conversion.UnderlyingConversions; var targetElements = ((NamedTypeSymbol)targetType).TupleElements; var valueElements = valueTuple.TupleElements; int n = valueElements.Length; for (int i = 0; i < n; i++) { trackConvertedValue(targetElements[i], conversions[i], valueElements[i]); } void trackConvertedValue(FieldSymbol targetField, Conversion conversion, FieldSymbol valueField) { switch (conversion.Kind) { case ConversionKind.Identity: case ConversionKind.NullLiteral: case ConversionKind.DefaultLiteral: case ConversionKind.ImplicitReference: case ConversionKind.ExplicitReference: case ConversionKind.Boxing: case ConversionKind.Unboxing: InheritNullableStateOfMember(slot, valueSlot, valueField, isDefaultValue: false, skipSlot: slot); break; case ConversionKind.ImplicitTupleLiteral: case ConversionKind.ExplicitTupleLiteral: case ConversionKind.ImplicitTuple: case ConversionKind.ExplicitTuple: { int targetFieldSlot = GetOrCreateSlot(targetField, slot); if (targetFieldSlot > 0) { this.State[targetFieldSlot] = NullableFlowState.NotNull; int valueFieldSlot = GetOrCreateSlot(valueField, valueSlot); if (valueFieldSlot > 0) { TrackNullableStateOfTupleConversion(conversionOpt, convertedNode, conversion, targetField.Type, valueField.Type, targetFieldSlot, valueFieldSlot, assignmentKind, parameterOpt, reportWarnings); } } } break; case ConversionKind.ImplicitNullable: case ConversionKind.ExplicitNullable: // Conversion of T to Nullable<T> is equivalent to new Nullable<T>(t). if (AreNullableAndUnderlyingTypes(targetField.Type, valueField.Type, out _)) { int targetFieldSlot = GetOrCreateSlot(targetField, slot); if (targetFieldSlot > 0) { this.State[targetFieldSlot] = NullableFlowState.NotNull; int valueFieldSlot = GetOrCreateSlot(valueField, valueSlot); if (valueFieldSlot > 0) { TrackNullableStateOfNullableValue(targetFieldSlot, targetField.Type, null, valueField.TypeWithAnnotations.ToTypeWithState(), valueFieldSlot); } } } break; case ConversionKind.ImplicitUserDefined: case ConversionKind.ExplicitUserDefined: { var convertedType = VisitUserDefinedConversion( conversionOpt, convertedNode, conversion, targetField.TypeWithAnnotations, valueField.TypeWithAnnotations.ToTypeWithState(), useLegacyWarnings: false, assignmentKind, parameterOpt, reportTopLevelWarnings: reportWarnings, reportRemainingWarnings: reportWarnings, diagnosticLocation: (conversionOpt ?? convertedNode).Syntax.GetLocation()); int targetFieldSlot = GetOrCreateSlot(targetField, slot); if (targetFieldSlot > 0) { this.State[targetFieldSlot] = convertedType.State; } } break; default: break; } } } public override BoundNode? VisitTupleBinaryOperator(BoundTupleBinaryOperator node) { base.VisitTupleBinaryOperator(node); SetNotNullResult(node); return null; } private void ReportNullabilityMismatchWithTargetDelegate(Location location, TypeSymbol targetType, MethodSymbol targetInvokeMethod, MethodSymbol sourceInvokeMethod, bool invokedAsExtensionMethod) { SourceMemberContainerTypeSymbol.CheckValidNullableMethodOverride( compilation, targetInvokeMethod, sourceInvokeMethod, new BindingDiagnosticBag(Diagnostics), reportBadDelegateReturn, reportBadDelegateParameter, extraArgument: (targetType, location), invokedAsExtensionMethod: invokedAsExtensionMethod); void reportBadDelegateReturn(BindingDiagnosticBag bag, MethodSymbol targetInvokeMethod, MethodSymbol sourceInvokeMethod, bool topLevel, (TypeSymbol targetType, Location location) arg) { ReportDiagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, arg.location, new FormattedSymbol(sourceInvokeMethod, SymbolDisplayFormat.MinimallyQualifiedFormat), arg.targetType); } void reportBadDelegateParameter(BindingDiagnosticBag bag, MethodSymbol sourceInvokeMethod, MethodSymbol targetInvokeMethod, ParameterSymbol parameter, bool topLevel, (TypeSymbol targetType, Location location) arg) { ReportDiagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, arg.location, GetParameterAsDiagnosticArgument(parameter), GetContainingSymbolAsDiagnosticArgument(parameter), arg.targetType); } } private void ReportNullabilityMismatchWithTargetDelegate(Location location, NamedTypeSymbol delegateType, UnboundLambda unboundLambda) { if (!unboundLambda.HasExplicitlyTypedParameterList) { return; } var invoke = delegateType?.DelegateInvokeMethod; if (invoke is null) { return; } Debug.Assert(delegateType is object); if (unboundLambda.HasExplicitReturnType(out _, out var returnType) && IsNullabilityMismatch(invoke.ReturnTypeWithAnnotations, returnType, requireIdentity: true)) { ReportDiagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, location, unboundLambda.MessageID.Localize(), delegateType); } int count = Math.Min(invoke.ParameterCount, unboundLambda.ParameterCount); for (int i = 0; i < count; i++) { var invokeParameter = invoke.Parameters[i]; // Parameter nullability is expected to match exactly. This corresponds to the behavior of initial binding. // Action<string> x = (object o) => { }; // error CS1661: Cannot convert lambda expression to delegate type 'Action<string>' because the parameter types do not match the delegate parameter types // Action<object> y = (object? o) => { }; // warning CS8622: Nullability of reference types in type of parameter 'o' of 'lambda expression' doesn't match the target delegate 'Action<object>'. // https://github.com/dotnet/roslyn/issues/35564: Consider relaxing and allow implicit conversions of nullability. // (Compare with method group conversions which pass `requireIdentity: false`.) if (IsNullabilityMismatch(invokeParameter.TypeWithAnnotations, unboundLambda.ParameterTypeWithAnnotations(i), requireIdentity: true)) { // Should the warning be reported using location of specific lambda parameter? ReportDiagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, location, unboundLambda.ParameterName(i), unboundLambda.MessageID.Localize(), delegateType); } } } private bool IsNullabilityMismatch(TypeWithAnnotations source, TypeWithAnnotations destination, bool requireIdentity) { if (!HasTopLevelNullabilityConversion(source, destination, requireIdentity)) { return true; } if (requireIdentity) { return IsNullabilityMismatch(source, destination); } var sourceType = source.Type; var destinationType = destination.Type; var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; return !_conversions.ClassifyImplicitConversionFromType(sourceType, destinationType, ref discardedUseSiteInfo).Exists; } private bool HasTopLevelNullabilityConversion(TypeWithAnnotations source, TypeWithAnnotations destination, bool requireIdentity) { return requireIdentity ? _conversions.HasTopLevelNullabilityIdentityConversion(source, destination) : _conversions.HasTopLevelNullabilityImplicitConversion(source, destination); } /// <summary> /// Gets the conversion node for passing to <see cref="VisitConversion(BoundConversion, BoundExpression, Conversion, TypeWithAnnotations, TypeWithState, bool, bool, bool, AssignmentKind, ParameterSymbol, bool, bool, bool, Optional{LocalState}, bool, Location)"/>, /// if one should be passed. /// </summary> private static BoundConversion? GetConversionIfApplicable(BoundExpression? conversionOpt, BoundExpression convertedNode) { Debug.Assert(conversionOpt is null || convertedNode == conversionOpt // Note that convertedNode itself can be a BoundConversion, so we do this check explicitly // because the below calls to RemoveConversion could potentially strip that conversion. || convertedNode == RemoveConversion(conversionOpt, includeExplicitConversions: false).expression || convertedNode == RemoveConversion(conversionOpt, includeExplicitConversions: true).expression); return conversionOpt == convertedNode ? null : (BoundConversion?)conversionOpt; } /// <summary> /// Apply the conversion to the type of the operand and return the resulting type. /// If the operand does not have an explicit type, the operand expression is used. /// </summary> /// <param name="checkConversion"> /// If <see langword="true"/>, the incoming conversion is assumed to be from binding /// and will be re-calculated, this time considering nullability. /// Note that the conversion calculation considers nested nullability only. /// The caller is responsible for checking the top-level nullability of /// the type returned by this method. /// </param> /// <param name="trackMembers"> /// If <see langword="true"/>, the nullability of any members of the operand /// will be copied to the converted result when possible. /// </param> /// <param name="useLegacyWarnings"> /// If <see langword="true"/>, indicates that the "non-safety" diagnostic <see cref="ErrorCode.WRN_ConvertingNullableToNonNullable"/> /// should be given for an invalid conversion. /// </param> private TypeWithState VisitConversion( BoundConversion? conversionOpt, BoundExpression conversionOperand, Conversion conversion, TypeWithAnnotations targetTypeWithNullability, TypeWithState operandType, bool checkConversion, bool fromExplicitCast, bool useLegacyWarnings, AssignmentKind assignmentKind, ParameterSymbol? parameterOpt = null, bool reportTopLevelWarnings = true, bool reportRemainingWarnings = true, bool extensionMethodThisArgument = false, Optional<LocalState> stateForLambda = default, bool trackMembers = false, Location? diagnosticLocationOpt = null) { Debug.Assert(!trackMembers || !IsConditionalState); Debug.Assert(conversionOperand != null); NullableFlowState resultState = NullableFlowState.NotNull; bool canConvertNestedNullability = true; bool isSuppressed = false; diagnosticLocationOpt ??= (conversionOpt ?? conversionOperand).Syntax.GetLocation(); if (conversionOperand.IsSuppressed == true) { reportTopLevelWarnings = false; reportRemainingWarnings = false; isSuppressed = true; } #nullable disable TypeSymbol targetType = targetTypeWithNullability.Type; switch (conversion.Kind) { case ConversionKind.MethodGroup: { var group = conversionOperand as BoundMethodGroup; var (invokeSignature, parameters) = getDelegateOrFunctionPointerInfo(targetType); var method = conversion.Method; if (group != null) { if (method?.OriginalDefinition is LocalFunctionSymbol localFunc) { VisitLocalFunctionUse(localFunc); } method = CheckMethodGroupReceiverNullability(group, parameters, method, conversion.IsExtensionMethod); } if (reportRemainingWarnings && invokeSignature != null) { ReportNullabilityMismatchWithTargetDelegate(diagnosticLocationOpt, targetType, invokeSignature, method, conversion.IsExtensionMethod); } } resultState = NullableFlowState.NotNull; break; static (MethodSymbol invokeSignature, ImmutableArray<ParameterSymbol>) getDelegateOrFunctionPointerInfo(TypeSymbol targetType) => targetType switch { NamedTypeSymbol { TypeKind: TypeKind.Delegate, DelegateInvokeMethod: { Parameters: { } parameters } signature } => (signature, parameters), FunctionPointerTypeSymbol { Signature: { Parameters: { } parameters } signature } => (signature, parameters), _ => (null, ImmutableArray<ParameterSymbol>.Empty), }; case ConversionKind.AnonymousFunction: if (conversionOperand is BoundLambda lambda) { var delegateType = targetType.GetDelegateType(); VisitLambda(lambda, delegateType, stateForLambda); if (reportRemainingWarnings) { ReportNullabilityMismatchWithTargetDelegate(diagnosticLocationOpt, delegateType, lambda.UnboundLambda); } TrackAnalyzedNullabilityThroughConversionGroup(targetTypeWithNullability.ToTypeWithState(), conversionOpt, conversionOperand); return TypeWithState.Create(targetType, NullableFlowState.NotNull); } break; case ConversionKind.FunctionType: resultState = NullableFlowState.NotNull; break; case ConversionKind.InterpolatedString: resultState = NullableFlowState.NotNull; break; case ConversionKind.InterpolatedStringHandler: // https://github.com/dotnet/roslyn/issues/54583 Handle resultState = NullableFlowState.NotNull; break; case ConversionKind.ObjectCreation: case ConversionKind.SwitchExpression: case ConversionKind.ConditionalExpression: resultState = visitNestedTargetTypedConstructs(); TrackAnalyzedNullabilityThroughConversionGroup(targetTypeWithNullability.ToTypeWithState(), conversionOpt, conversionOperand); break; case ConversionKind.ExplicitUserDefined: case ConversionKind.ImplicitUserDefined: return VisitUserDefinedConversion(conversionOpt, conversionOperand, conversion, targetTypeWithNullability, operandType, useLegacyWarnings, assignmentKind, parameterOpt, reportTopLevelWarnings, reportRemainingWarnings, diagnosticLocationOpt); case ConversionKind.ExplicitDynamic: case ConversionKind.ImplicitDynamic: resultState = getConversionResultState(operandType); break; case ConversionKind.Boxing: resultState = getBoxingConversionResultState(targetTypeWithNullability, operandType); break; case ConversionKind.Unboxing: if (targetType.IsNonNullableValueType()) { if (!operandType.IsNotNull && reportRemainingWarnings) { ReportDiagnostic(ErrorCode.WRN_UnboxPossibleNull, diagnosticLocationOpt); } LearnFromNonNullTest(conversionOperand, ref State); } else { resultState = getUnboxingConversionResultState(operandType); } break; case ConversionKind.ImplicitThrow: resultState = NullableFlowState.NotNull; break; case ConversionKind.NoConversion: resultState = getConversionResultState(operandType); break; case ConversionKind.NullLiteral: case ConversionKind.DefaultLiteral: checkConversion = false; goto case ConversionKind.Identity; case ConversionKind.Identity: // If the operand is an explicit conversion, and this identity conversion // is converting to the same type including nullability, skip the conversion // to avoid reporting redundant warnings. Also check useLegacyWarnings // since that value was used when reporting warnings for the explicit cast. // Don't skip the node when it's a user-defined conversion, as identity conversions // on top of user-defined conversions means that we're coming in from VisitUserDefinedConversion // and that any warnings caught by this recursive call of VisitConversion won't be redundant. if (useLegacyWarnings && conversionOperand is BoundConversion operandConversion && !operandConversion.ConversionKind.IsUserDefinedConversion()) { var explicitType = operandConversion.ConversionGroupOpt?.ExplicitType; if (explicitType?.Equals(targetTypeWithNullability, TypeCompareKind.ConsiderEverything) == true) { TrackAnalyzedNullabilityThroughConversionGroup( calculateResultType(targetTypeWithNullability, fromExplicitCast, operandType.State, isSuppressed, targetType), conversionOpt, conversionOperand); return operandType; } } if (operandType.Type?.IsTupleType == true || conversionOperand.Kind == BoundKind.TupleLiteral) { goto case ConversionKind.ImplicitTuple; } goto case ConversionKind.ImplicitReference; case ConversionKind.ImplicitReference: case ConversionKind.ExplicitReference: // Inherit state from the operand. if (checkConversion) { conversion = GenerateConversion(_conversions, conversionOperand, operandType.Type, targetType, fromExplicitCast, extensionMethodThisArgument); canConvertNestedNullability = conversion.Exists; } resultState = conversion.IsReference ? getReferenceConversionResultState(targetTypeWithNullability, operandType) : operandType.State; break; case ConversionKind.ImplicitNullable: if (trackMembers) { Debug.Assert(conversionOperand != null); if (AreNullableAndUnderlyingTypes(targetType, operandType.Type, out TypeWithAnnotations underlyingType)) { // Conversion of T to Nullable<T> is equivalent to new Nullable<T>(t). int valueSlot = MakeSlot(conversionOperand); if (valueSlot > 0) { int containingSlot = GetOrCreatePlaceholderSlot(conversionOpt); Debug.Assert(containingSlot > 0); TrackNullableStateOfNullableValue(containingSlot, targetType, conversionOperand, underlyingType.ToTypeWithState(), valueSlot); } } } if (checkConversion) { conversion = GenerateConversion(_conversions, conversionOperand, operandType.Type, targetType, fromExplicitCast, extensionMethodThisArgument); canConvertNestedNullability = conversion.Exists; } resultState = operandType.State; break; case ConversionKind.ExplicitNullable: if (operandType.Type?.IsNullableType() == true && !targetType.IsNullableType()) { // Explicit conversion of Nullable<T> to T is equivalent to Nullable<T>.Value. if (reportTopLevelWarnings && operandType.MayBeNull) { ReportDiagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, diagnosticLocationOpt); } // Mark the value as not nullable, regardless of whether it was known to be nullable, // because the implied call to `.Value` will only succeed if not null. if (conversionOperand != null) { LearnFromNonNullTest(conversionOperand, ref State); } } goto case ConversionKind.ImplicitNullable; case ConversionKind.ImplicitTuple: case ConversionKind.ImplicitTupleLiteral: case ConversionKind.ExplicitTupleLiteral: case ConversionKind.ExplicitTuple: if (trackMembers) { Debug.Assert(conversionOperand != null); switch (conversion.Kind) { case ConversionKind.ImplicitTuple: case ConversionKind.ExplicitTuple: int valueSlot = MakeSlot(conversionOperand); if (valueSlot > 0) { int slot = GetOrCreatePlaceholderSlot(conversionOpt); if (slot > 0) { TrackNullableStateOfTupleConversion(conversionOpt, conversionOperand, conversion, targetType, operandType.Type, slot, valueSlot, assignmentKind, parameterOpt, reportWarnings: reportRemainingWarnings); } } break; } } if (checkConversion && !targetType.IsErrorType()) { // https://github.com/dotnet/roslyn/issues/29699: Report warnings for user-defined conversions on tuple elements. conversion = GenerateConversion(_conversions, conversionOperand, operandType.Type, targetType, fromExplicitCast, extensionMethodThisArgument); canConvertNestedNullability = conversion.Exists; } resultState = NullableFlowState.NotNull; break; case ConversionKind.Deconstruction: // Can reach here, with an error type, when the // Deconstruct method is missing or inaccessible. break; case ConversionKind.ExplicitEnumeration: // Can reach here, with an error type. break; default: Debug.Assert(targetType.IsValueType || targetType.IsErrorType()); break; } TypeWithState resultType = calculateResultType(targetTypeWithNullability, fromExplicitCast, resultState, isSuppressed, targetType); if (operandType.Type?.IsErrorType() != true && !targetType.IsErrorType()) { // Need to report all warnings that apply since the warnings can be suppressed individually. if (reportTopLevelWarnings) { ReportNullableAssignmentIfNecessary(conversionOperand, targetTypeWithNullability, resultType, useLegacyWarnings, assignmentKind, parameterOpt, diagnosticLocationOpt); } if (reportRemainingWarnings && !canConvertNestedNullability) { if (assignmentKind == AssignmentKind.Argument) { ReportNullabilityMismatchInArgument(diagnosticLocationOpt, operandType.Type, parameterOpt, targetType, forOutput: false); } else { ReportNullabilityMismatchInAssignment(diagnosticLocationOpt, GetTypeAsDiagnosticArgument(operandType.Type), targetType); } } } TrackAnalyzedNullabilityThroughConversionGroup(resultType, conversionOpt, conversionOperand); return resultType; #nullable enable static TypeWithState calculateResultType(TypeWithAnnotations targetTypeWithNullability, bool fromExplicitCast, NullableFlowState resultState, bool isSuppressed, TypeSymbol targetType) { if (isSuppressed) { resultState = NullableFlowState.NotNull; } else if (fromExplicitCast && targetTypeWithNullability.NullableAnnotation.IsAnnotated() && !targetType.IsNullableType()) { // An explicit cast to a nullable reference type introduces nullability resultState = targetType?.IsTypeParameterDisallowingAnnotationInCSharp8() == true ? NullableFlowState.MaybeDefault : NullableFlowState.MaybeNull; } var resultType = TypeWithState.Create(targetType, resultState); return resultType; } static NullableFlowState getReferenceConversionResultState(TypeWithAnnotations targetType, TypeWithState operandType) { var state = operandType.State; switch (state) { case NullableFlowState.MaybeNull: if (targetType.Type?.IsTypeParameterDisallowingAnnotationInCSharp8() == true) { var type = operandType.Type; if (type is null || !type.IsTypeParameterDisallowingAnnotationInCSharp8()) { return NullableFlowState.MaybeDefault; } else if (targetType.NullableAnnotation.IsNotAnnotated() && type is TypeParameterSymbol typeParameter1 && dependsOnTypeParameter(typeParameter1, (TypeParameterSymbol)targetType.Type, NullableAnnotation.NotAnnotated, out var annotation)) { return (annotation == NullableAnnotation.Annotated) ? NullableFlowState.MaybeDefault : NullableFlowState.MaybeNull; } } break; case NullableFlowState.MaybeDefault: if (targetType.Type?.IsTypeParameterDisallowingAnnotationInCSharp8() == false) { return NullableFlowState.MaybeNull; } break; } return state; } // Converting to a less-derived type (object, interface, type parameter). // If the operand is MaybeNull, the result should be // MaybeNull (if the target type allows) or MaybeDefault otherwise. static NullableFlowState getBoxingConversionResultState(TypeWithAnnotations targetType, TypeWithState operandType) { var state = operandType.State; if (state == NullableFlowState.MaybeNull) { var type = operandType.Type; if (type is null || !type.IsTypeParameterDisallowingAnnotationInCSharp8()) { return NullableFlowState.MaybeDefault; } else if (targetType.NullableAnnotation.IsNotAnnotated() && type is TypeParameterSymbol typeParameter1 && targetType.Type is TypeParameterSymbol typeParameter2) { bool dependsOn = dependsOnTypeParameter(typeParameter1, typeParameter2, NullableAnnotation.NotAnnotated, out var annotation); Debug.Assert(dependsOn); // If this case fails, add a corresponding test. if (dependsOn) { return (annotation == NullableAnnotation.Annotated) ? NullableFlowState.MaybeDefault : NullableFlowState.MaybeNull; } } } return state; } // Converting to a more-derived type (struct, class, type parameter). // If the operand is MaybeNull or MaybeDefault, the result should be // MaybeDefault. static NullableFlowState getUnboxingConversionResultState(TypeWithState operandType) { var state = operandType.State; if (state == NullableFlowState.MaybeNull) { return NullableFlowState.MaybeDefault; } return state; } static NullableFlowState getConversionResultState(TypeWithState operandType) { var state = operandType.State; if (state == NullableFlowState.MaybeNull) { return NullableFlowState.MaybeDefault; } return state; } // If type parameter 1 depends on type parameter 2 (that is, if type parameter 2 appears // in the constraint types of type parameter 1), returns the effective annotation on // type parameter 2 in the constraints of type parameter 1. static bool dependsOnTypeParameter(TypeParameterSymbol typeParameter1, TypeParameterSymbol typeParameter2, NullableAnnotation typeParameter1Annotation, out NullableAnnotation annotation) { if (typeParameter1.Equals(typeParameter2, TypeCompareKind.AllIgnoreOptions)) { annotation = typeParameter1Annotation; return true; } bool dependsOn = false; var combinedAnnotation = NullableAnnotation.Annotated; foreach (var constraintType in typeParameter1.ConstraintTypesNoUseSiteDiagnostics) { if (constraintType.Type is TypeParameterSymbol constraintTypeParameter && dependsOnTypeParameter(constraintTypeParameter, typeParameter2, constraintType.NullableAnnotation, out var constraintAnnotation)) { dependsOn = true; combinedAnnotation = combinedAnnotation.Meet(constraintAnnotation); } } if (dependsOn) { annotation = combinedAnnotation.Join(typeParameter1Annotation); return true; } annotation = default; return false; } NullableFlowState visitNestedTargetTypedConstructs() { switch (conversionOperand) { case BoundConditionalOperator { WasTargetTyped: true } conditional: { Debug.Assert(ConditionalInfoForConversion.ContainsKey(conditional)); var info = ConditionalInfoForConversion[conditional]; Debug.Assert(info.Length == 2); var consequence = conditional.Consequence; (BoundExpression consequenceOperand, Conversion consequenceConversion) = RemoveConversion(consequence, includeExplicitConversions: false); var consequenceRValue = ConvertConditionalOperandOrSwitchExpressionArmResult(consequence, consequenceOperand, consequenceConversion, targetTypeWithNullability, info[0].ResultType, info[0].State, info[0].EndReachable); var alternative = conditional.Alternative; (BoundExpression alternativeOperand, Conversion alternativeConversion) = RemoveConversion(alternative, includeExplicitConversions: false); var alternativeRValue = ConvertConditionalOperandOrSwitchExpressionArmResult(alternative, alternativeOperand, alternativeConversion, targetTypeWithNullability, info[1].ResultType, info[1].State, info[1].EndReachable); ConditionalInfoForConversion.Remove(conditional); return consequenceRValue.State.Join(alternativeRValue.State); } case BoundConvertedSwitchExpression { WasTargetTyped: true } @switch: { Debug.Assert(ConditionalInfoForConversion.ContainsKey(@switch)); var info = ConditionalInfoForConversion[@switch]; Debug.Assert(info.Length == @switch.SwitchArms.Length); var resultTypes = ArrayBuilder<TypeWithState>.GetInstance(info.Length); for (int i = 0; i < info.Length; i++) { var (state, armResultType, isReachable) = info[i]; var arm = @switch.SwitchArms[i].Value; var (operand, conversion) = RemoveConversion(arm, includeExplicitConversions: false); resultTypes.Add(ConvertConditionalOperandOrSwitchExpressionArmResult(arm, operand, conversion, targetTypeWithNullability, armResultType, state, isReachable)); } var resultState = BestTypeInferrer.GetNullableState(resultTypes); resultTypes.Free(); ConditionalInfoForConversion.Remove(@switch); return resultState; } case BoundObjectCreationExpression { WasTargetTyped: true }: case BoundUnconvertedObjectCreationExpression: return NullableFlowState.NotNull; case BoundUnconvertedConditionalOperator: case BoundUnconvertedSwitchExpression: return operandType.State; default: throw ExceptionUtilities.UnexpectedValue(conversionOperand.Kind); } } } private TypeWithState VisitUserDefinedConversion( BoundConversion? conversionOpt, BoundExpression conversionOperand, Conversion conversion, TypeWithAnnotations targetTypeWithNullability, TypeWithState operandType, bool useLegacyWarnings, AssignmentKind assignmentKind, ParameterSymbol? parameterOpt, bool reportTopLevelWarnings, bool reportRemainingWarnings, Location diagnosticLocation) { Debug.Assert(!IsConditionalState); Debug.Assert(conversionOperand != null); Debug.Assert(targetTypeWithNullability.HasType); Debug.Assert(diagnosticLocation != null); Debug.Assert(conversion.Kind == ConversionKind.ExplicitUserDefined || conversion.Kind == ConversionKind.ImplicitUserDefined); TypeSymbol targetType = targetTypeWithNullability.Type; // cf. Binder.CreateUserDefinedConversion if (!conversion.IsValid) { var resultType = TypeWithState.Create(targetType, NullableFlowState.NotNull); TrackAnalyzedNullabilityThroughConversionGroup(resultType, conversionOpt, conversionOperand); return resultType; } // operand -> conversion "from" type // May be distinct from method parameter type for Nullable<T>. operandType = VisitConversion( conversionOpt, conversionOperand, conversion.UserDefinedFromConversion, TypeWithAnnotations.Create(conversion.BestUserDefinedConversionAnalysis!.FromType), operandType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings, assignmentKind, parameterOpt, reportTopLevelWarnings, reportRemainingWarnings, diagnosticLocationOpt: diagnosticLocation); // Update method based on operandType: see https://github.com/dotnet/roslyn/issues/29605. // (see NullableReferenceTypesTests.ImplicitConversions_07). var method = conversion.Method; Debug.Assert(method is object); Debug.Assert(method.ParameterCount == 1); Debug.Assert(operandType.Type is object); var parameter = method.Parameters[0]; var parameterAnnotations = GetParameterAnnotations(parameter); var parameterType = ApplyLValueAnnotations(parameter.TypeWithAnnotations, parameterAnnotations); TypeWithState underlyingOperandType = default; bool isLiftedConversion = false; if (operandType.Type.IsNullableType() && !parameterType.IsNullableType()) { var underlyingOperandTypeWithAnnotations = operandType.Type.GetNullableUnderlyingTypeWithAnnotations(); underlyingOperandType = underlyingOperandTypeWithAnnotations.ToTypeWithState(); isLiftedConversion = parameterType.Equals(underlyingOperandTypeWithAnnotations, TypeCompareKind.AllIgnoreOptions); } // conversion "from" type -> method parameter type NullableFlowState operandState = operandType.State; Location operandLocation = conversionOperand.Syntax.GetLocation(); _ = ClassifyAndVisitConversion( conversionOperand, parameterType, isLiftedConversion ? underlyingOperandType : operandType, useLegacyWarnings, AssignmentKind.Argument, parameterOpt: parameter, reportWarnings: reportRemainingWarnings, fromExplicitCast: false, diagnosticLocation: operandLocation); // in the case of a lifted conversion, we assume that the call to the operator occurs only if the argument is not-null if (!isLiftedConversion && CheckDisallowedNullAssignment(operandType, parameterAnnotations, conversionOperand.Syntax.Location)) { LearnFromNonNullTest(conversionOperand, ref State); } // method parameter type -> method return type var methodReturnType = method.ReturnTypeWithAnnotations; operandType = GetLiftedReturnTypeIfNecessary(isLiftedConversion, methodReturnType, operandState); if (!isLiftedConversion || operandState.IsNotNull()) { var returnNotNull = operandState.IsNotNull() && method.ReturnNotNullIfParameterNotNull.Contains(parameter.Name); if (returnNotNull) { operandType = operandType.WithNotNullState(); } else { operandType = ApplyUnconditionalAnnotations(operandType, GetRValueAnnotations(method)); } } // method return type -> conversion "to" type // May be distinct from method return type for Nullable<T>. operandType = ClassifyAndVisitConversion( conversionOperand, TypeWithAnnotations.Create(conversion.BestUserDefinedConversionAnalysis!.ToType), operandType, useLegacyWarnings, assignmentKind, parameterOpt, reportWarnings: reportRemainingWarnings, fromExplicitCast: false, diagnosticLocation: operandLocation); // conversion "to" type -> final type // We should only pass fromExplicitCast here. Given the following example: // // class A { public static explicit operator C(A a) => throw null!; } // class C // { // void M() => var c = (C?)new A(); // } // // This final conversion from the method return type "C" to the cast type "C?" is // where we will need to ensure that this is counted as an explicit cast, so that // the resulting operandType is nullable if that was introduced via cast. operandType = ClassifyAndVisitConversion( conversionOpt ?? conversionOperand, targetTypeWithNullability, operandType, useLegacyWarnings, assignmentKind, parameterOpt, reportWarnings: reportRemainingWarnings, fromExplicitCast: conversionOpt?.ExplicitCastInCode ?? false, diagnosticLocation); TrackAnalyzedNullabilityThroughConversionGroup(operandType, conversionOpt, conversionOperand); return operandType; } private void SnapshotWalkerThroughConversionGroup(BoundExpression conversionExpression, BoundExpression convertedNode) { if (_snapshotBuilderOpt is null) { return; } var conversionOpt = conversionExpression as BoundConversion; var conversionGroup = conversionOpt?.ConversionGroupOpt; while (conversionOpt != null && conversionOpt != convertedNode && conversionOpt.Syntax.SpanStart != convertedNode.Syntax.SpanStart) { Debug.Assert(conversionOpt.ConversionGroupOpt == conversionGroup); TakeIncrementalSnapshot(conversionOpt); conversionOpt = conversionOpt.Operand as BoundConversion; } } private void TrackAnalyzedNullabilityThroughConversionGroup(TypeWithState resultType, BoundConversion? conversionOpt, BoundExpression convertedNode) { var visitResult = new VisitResult(resultType, resultType.ToTypeWithAnnotations(compilation)); var conversionGroup = conversionOpt?.ConversionGroupOpt; while (conversionOpt != null && conversionOpt != convertedNode) { Debug.Assert(conversionOpt.ConversionGroupOpt == conversionGroup); visitResult = withType(visitResult, conversionOpt.Type); SetAnalyzedNullability(conversionOpt, visitResult); conversionOpt = conversionOpt.Operand as BoundConversion; } static VisitResult withType(VisitResult visitResult, TypeSymbol newType) => new VisitResult(TypeWithState.Create(newType, visitResult.RValueType.State), TypeWithAnnotations.Create(newType, visitResult.LValueType.NullableAnnotation)); } /// <summary> /// Return the return type for a lifted operator, given the nullability state of its operands. /// </summary> private TypeWithState GetLiftedReturnType(TypeWithAnnotations returnType, NullableFlowState operandState) { bool typeNeedsLifting = returnType.Type.IsNonNullableValueType(); TypeSymbol type = typeNeedsLifting ? MakeNullableOf(returnType) : returnType.Type; NullableFlowState state = returnType.ToTypeWithState().State.Join(operandState); return TypeWithState.Create(type, state); } private static TypeWithState GetNullableUnderlyingTypeIfNecessary(bool isLifted, TypeWithState typeWithState) { if (isLifted) { var type = typeWithState.Type; if (type?.IsNullableType() == true) { return type.GetNullableUnderlyingTypeWithAnnotations().ToTypeWithState(); } } return typeWithState; } private TypeWithState GetLiftedReturnTypeIfNecessary(bool isLifted, TypeWithAnnotations returnType, NullableFlowState operandState) { return isLifted ? GetLiftedReturnType(returnType, operandState) : returnType.ToTypeWithState(); } private TypeSymbol MakeNullableOf(TypeWithAnnotations underlying) { return compilation.GetSpecialType(SpecialType.System_Nullable_T).Construct(ImmutableArray.Create(underlying)); } private TypeWithState ClassifyAndVisitConversion( BoundExpression node, TypeWithAnnotations targetType, TypeWithState operandType, bool useLegacyWarnings, AssignmentKind assignmentKind, ParameterSymbol? parameterOpt, bool reportWarnings, bool fromExplicitCast, Location diagnosticLocation) { Debug.Assert(operandType.Type is object); Debug.Assert(diagnosticLocation != null); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var conversion = _conversions.ClassifyStandardConversion(null, operandType.Type, targetType.Type, ref discardedUseSiteInfo); if (reportWarnings && !conversion.Exists) { if (assignmentKind == AssignmentKind.Argument) { ReportNullabilityMismatchInArgument(diagnosticLocation, operandType.Type, parameterOpt, targetType.Type, forOutput: false); } else { ReportNullabilityMismatchInAssignment(diagnosticLocation, operandType.Type, targetType.Type); } } return VisitConversion( conversionOpt: null, conversionOperand: node, conversion, targetType, operandType, checkConversion: false, fromExplicitCast, useLegacyWarnings: useLegacyWarnings, assignmentKind, parameterOpt, reportTopLevelWarnings: reportWarnings, reportRemainingWarnings: !fromExplicitCast && reportWarnings, diagnosticLocationOpt: diagnosticLocation); } public override BoundNode? VisitDelegateCreationExpression(BoundDelegateCreationExpression node) { Debug.Assert(node.Type.IsDelegateType()); if (node.MethodOpt?.OriginalDefinition is LocalFunctionSymbol localFunc) { VisitLocalFunctionUse(localFunc); } var delegateType = (NamedTypeSymbol)node.Type; switch (node.Argument) { case BoundMethodGroup group: { VisitMethodGroup(group); var method = node.MethodOpt; if (method is object && delegateType.DelegateInvokeMethod is { } delegateInvokeMethod) { method = CheckMethodGroupReceiverNullability(group, delegateInvokeMethod.Parameters, method, node.IsExtensionMethod); if (!group.IsSuppressed) { ReportNullabilityMismatchWithTargetDelegate(group.Syntax.Location, delegateType, delegateInvokeMethod, method, node.IsExtensionMethod); } } SetAnalyzedNullability(group, default); } break; case BoundLambda lambda: { VisitLambda(lambda, delegateType); SetNotNullResult(lambda); if (!lambda.IsSuppressed) { ReportNullabilityMismatchWithTargetDelegate(lambda.Symbol.DiagnosticLocation, delegateType, lambda.UnboundLambda); } } break; case BoundExpression arg when arg.Type is { TypeKind: TypeKind.Delegate } argType: { var argTypeWithAnnotations = TypeWithAnnotations.Create(argType, NullableAnnotation.NotAnnotated); var argState = VisitRvalueWithState(arg); ReportNullableAssignmentIfNecessary(arg, argTypeWithAnnotations, argState, useLegacyWarnings: false); if (!arg.IsSuppressed && delegateType.DelegateInvokeMethod is { } delegateInvokeMethod && argType.DelegateInvokeMethod() is { } argInvokeMethod) { ReportNullabilityMismatchWithTargetDelegate(arg.Syntax.Location, delegateType, delegateInvokeMethod, argInvokeMethod, invokedAsExtensionMethod: false); } // Delegate creation will throw an exception if the argument is null LearnFromNonNullTest(arg, ref State); } break; default: VisitRvalue(node.Argument); break; } SetNotNullResult(node); return null; } public override BoundNode? VisitMethodGroup(BoundMethodGroup node) { Debug.Assert(!IsConditionalState); var receiverOpt = node.ReceiverOpt; if (receiverOpt != null) { VisitRvalue(receiverOpt); // Receiver nullability is checked when applying the method group conversion, // when we have a specific method, to avoid reporting null receiver warnings // for extension method delegates. Here, store the receiver state for that check. SetMethodGroupReceiverNullability(receiverOpt, ResultType); } SetNotNullResult(node); return null; } private bool TryGetMethodGroupReceiverNullability([NotNullWhen(true)] BoundExpression? receiverOpt, out TypeWithState type) { if (receiverOpt != null && _methodGroupReceiverMapOpt != null && _methodGroupReceiverMapOpt.TryGetValue(receiverOpt, out type)) { return true; } else { type = default; return false; } } private void SetMethodGroupReceiverNullability(BoundExpression receiver, TypeWithState type) { _methodGroupReceiverMapOpt ??= PooledDictionary<BoundExpression, TypeWithState>.GetInstance(); _methodGroupReceiverMapOpt[receiver] = type; } private MethodSymbol CheckMethodGroupReceiverNullability(BoundMethodGroup group, ImmutableArray<ParameterSymbol> parameters, MethodSymbol method, bool invokedAsExtensionMethod) { var receiverOpt = group.ReceiverOpt; if (TryGetMethodGroupReceiverNullability(receiverOpt, out TypeWithState receiverType)) { var syntax = group.Syntax; if (!invokedAsExtensionMethod) { method = (MethodSymbol)AsMemberOfType(receiverType.Type, method); } if (method.IsGenericMethod && HasImplicitTypeArguments(group.Syntax)) { var arguments = ArrayBuilder<BoundExpression>.GetInstance(); if (invokedAsExtensionMethod) { arguments.Add(CreatePlaceholderIfNecessary(receiverOpt, receiverType.ToTypeWithAnnotations(compilation))); } // Create placeholders for the arguments. (See Conversions.GetDelegateArguments() // which is used for that purpose in initial binding.) foreach (var parameter in parameters) { var parameterType = parameter.TypeWithAnnotations; arguments.Add(new BoundExpressionWithNullability(syntax, new BoundParameter(syntax, parameter), parameterType.NullableAnnotation, parameterType.Type)); } Debug.Assert(_binder is object); method = InferMethodTypeArguments(method, arguments.ToImmutableAndFree(), argumentRefKindsOpt: default, argsToParamsOpt: default, expanded: false); } if (invokedAsExtensionMethod) { CheckExtensionMethodThisNullability(receiverOpt, Conversion.Identity, method.Parameters[0], receiverType); } else { CheckPossibleNullReceiver(receiverOpt, receiverType, checkNullableValueType: false); } if (ConstraintsHelper.RequiresChecking(method)) { CheckMethodConstraints(syntax, method); } } return method; } public override BoundNode? VisitLambda(BoundLambda node) { // Note: actual lambda analysis happens after this call (primarily in VisitConversion). // Here we just indicate that a lambda expression produces a non-null value. SetNotNullResult(node); return null; } private void VisitLambda(BoundLambda node, NamedTypeSymbol? delegateTypeOpt, Optional<LocalState> initialState = default) { Debug.Assert(delegateTypeOpt?.IsDelegateType() != false); var delegateInvokeMethod = delegateTypeOpt?.DelegateInvokeMethod; UseDelegateInvokeParameterAndReturnTypes(node, delegateInvokeMethod, out bool useDelegateInvokeParameterTypes, out bool useDelegateInvokeReturnType); if (useDelegateInvokeParameterTypes && _snapshotBuilderOpt is object) { SetUpdatedSymbol(node, node.Symbol, delegateTypeOpt!); } AnalyzeLocalFunctionOrLambda( node, node.Symbol, initialState.HasValue ? initialState.Value : State.Clone(), delegateInvokeMethod, useDelegateInvokeParameterTypes, useDelegateInvokeReturnType); } private static void UseDelegateInvokeParameterAndReturnTypes(BoundLambda lambda, MethodSymbol? delegateInvokeMethod, out bool useDelegateInvokeParameterTypes, out bool useDelegateInvokeReturnType) { if (delegateInvokeMethod is null) { useDelegateInvokeParameterTypes = false; useDelegateInvokeReturnType = false; } else { var unboundLambda = lambda.UnboundLambda; useDelegateInvokeParameterTypes = !unboundLambda.HasExplicitlyTypedParameterList; useDelegateInvokeReturnType = !unboundLambda.HasExplicitReturnType(out _, out _); } } public override BoundNode? VisitUnboundLambda(UnboundLambda node) { // The presence of this node suggests an error was detected in an earlier phase. // Analyze the body to report any additional warnings. var lambda = node.BindForErrorRecovery(); VisitLambda(lambda, delegateTypeOpt: null); SetNotNullResult(node); return null; } public override BoundNode? VisitThisReference(BoundThisReference node) { VisitThisOrBaseReference(node); return null; } private void VisitThisOrBaseReference(BoundExpression node) { var rvalueResult = TypeWithState.Create(node.Type, NullableFlowState.NotNull); var lvalueResult = TypeWithAnnotations.Create(node.Type, NullableAnnotation.NotAnnotated); SetResult(node, rvalueResult, lvalueResult); } public override BoundNode? VisitParameter(BoundParameter node) { var parameter = node.ParameterSymbol; int slot = GetOrCreateSlot(parameter); var parameterType = GetDeclaredParameterResult(parameter); var typeWithState = GetParameterState(parameterType, parameter.FlowAnalysisAnnotations); SetResult(node, GetAdjustedResult(typeWithState, slot), parameterType); return null; } public override BoundNode? VisitAssignmentOperator(BoundAssignmentOperator node) { Debug.Assert(!IsConditionalState); var left = node.Left; switch (left) { // when binding initializers, we treat assignments to auto-properties or field-like events as direct assignments to the underlying field. // in order to track member state based on these initializers, we need to see the assignment in terms of the associated member case BoundFieldAccess { ExpressionSymbol: FieldSymbol { AssociatedSymbol: PropertySymbol autoProperty } } fieldAccess: left = new BoundPropertyAccess(fieldAccess.Syntax, fieldAccess.ReceiverOpt, autoProperty, LookupResultKind.Viable, autoProperty.Type, fieldAccess.HasErrors); break; case BoundFieldAccess { ExpressionSymbol: FieldSymbol { AssociatedSymbol: EventSymbol @event } } fieldAccess: left = new BoundEventAccess(fieldAccess.Syntax, fieldAccess.ReceiverOpt, @event, isUsableAsField: true, LookupResultKind.Viable, @event.Type, fieldAccess.HasErrors); break; } var right = node.Right; VisitLValue(left); // we may enter a conditional state for error scenarios on the LHS. Unsplit(); FlowAnalysisAnnotations leftAnnotations = GetLValueAnnotations(left); TypeWithAnnotations declaredType = LvalueResultType; TypeWithAnnotations leftLValueType = ApplyLValueAnnotations(declaredType, leftAnnotations); if (left.Kind == BoundKind.EventAccess && ((BoundEventAccess)left).EventSymbol.IsWindowsRuntimeEvent) { // Event assignment is a call to an Add method. (Note that assignment // of non-field-like events uses BoundEventAssignmentOperator // rather than BoundAssignmentOperator.) VisitRvalue(right); SetNotNullResult(node); } else { TypeWithState rightState; if (!node.IsRef) { var discarded = left is BoundDiscardExpression; rightState = VisitOptionalImplicitConversion(right, targetTypeOpt: discarded ? default : leftLValueType, UseLegacyWarnings(left, leftLValueType), trackMembers: true, AssignmentKind.Assignment); } else { rightState = VisitRefExpression(right, leftLValueType); } // If the LHS has annotations, we perform an additional check for nullable value types CheckDisallowedNullAssignment(rightState, leftAnnotations, right.Syntax.Location); AdjustSetValue(left, ref rightState); TrackNullableStateForAssignment(right, leftLValueType, MakeSlot(left), rightState, MakeSlot(right)); if (left is BoundDiscardExpression) { var lvalueType = rightState.ToTypeWithAnnotations(compilation); SetResult(left, rightState, lvalueType, isLvalue: true); SetResult(node, rightState, lvalueType); } else { SetResult(node, TypeWithState.Create(leftLValueType.Type, rightState.State), leftLValueType); } } return null; } private bool IsPropertyOutputMoreStrictThanInput(PropertySymbol property) { var type = property.TypeWithAnnotations; var annotations = IsAnalyzingAttribute ? FlowAnalysisAnnotations.None : property.GetFlowAnalysisAnnotations(); var lValueType = ApplyLValueAnnotations(type, annotations); if (lValueType.NullableAnnotation.IsOblivious() || !lValueType.CanBeAssignedNull) { return false; } var rValueType = ApplyUnconditionalAnnotations(type.ToTypeWithState(), annotations); return rValueType.IsNotNull; } /// <summary> /// When the allowed output of a property/indexer is not-null but the allowed input is maybe-null, we store a not-null value instead. /// This way, assignment of a legal input value results in a legal output value. /// This adjustment doesn't apply to oblivious properties/indexers. /// </summary> private void AdjustSetValue(BoundExpression left, ref TypeWithState rightState) { var property = left switch { BoundPropertyAccess propAccess => propAccess.PropertySymbol, BoundIndexerAccess indexerAccess => indexerAccess.Indexer, _ => null }; if (property is not null && IsPropertyOutputMoreStrictThanInput(property)) { rightState = rightState.WithNotNullState(); } } private FlowAnalysisAnnotations GetLValueAnnotations(BoundExpression expr) { // Annotations are ignored when binding an attribute to avoid cycles. (Members used // in attributes are error scenarios, so missing warnings should not be important.) if (IsAnalyzingAttribute) { return FlowAnalysisAnnotations.None; } var annotations = expr switch { BoundPropertyAccess property => property.PropertySymbol.GetFlowAnalysisAnnotations(), BoundIndexerAccess indexer => indexer.Indexer.GetFlowAnalysisAnnotations(), BoundFieldAccess field => getFieldAnnotations(field.FieldSymbol), BoundObjectInitializerMember { MemberSymbol: PropertySymbol prop } => prop.GetFlowAnalysisAnnotations(), BoundObjectInitializerMember { MemberSymbol: FieldSymbol field } => getFieldAnnotations(field), BoundParameter { ParameterSymbol: ParameterSymbol parameter } => ToInwardAnnotations(GetParameterAnnotations(parameter) & ~FlowAnalysisAnnotations.NotNull), // NotNull is enforced upon method exit _ => FlowAnalysisAnnotations.None }; return annotations & (FlowAnalysisAnnotations.DisallowNull | FlowAnalysisAnnotations.AllowNull); static FlowAnalysisAnnotations getFieldAnnotations(FieldSymbol field) { return field.AssociatedSymbol is PropertySymbol property ? property.GetFlowAnalysisAnnotations() : field.FlowAnalysisAnnotations; } } private static FlowAnalysisAnnotations ToInwardAnnotations(FlowAnalysisAnnotations outwardAnnotations) { var annotations = FlowAnalysisAnnotations.None; if ((outwardAnnotations & FlowAnalysisAnnotations.MaybeNull) != 0) { // MaybeNull and MaybeNullWhen count as MaybeNull annotations |= FlowAnalysisAnnotations.AllowNull; } if ((outwardAnnotations & FlowAnalysisAnnotations.NotNull) == FlowAnalysisAnnotations.NotNull) { // NotNullWhenTrue and NotNullWhenFalse don't count on their own. Only NotNull (ie. both flags) matters. annotations |= FlowAnalysisAnnotations.DisallowNull; } return annotations; } private static bool UseLegacyWarnings(BoundExpression expr, TypeWithAnnotations exprType) { switch (expr.Kind) { case BoundKind.Local: return expr.GetRefKind() == RefKind.None; case BoundKind.Parameter: RefKind kind = ((BoundParameter)expr).ParameterSymbol.RefKind; return kind == RefKind.None; default: return false; } } public override BoundNode? VisitDeconstructionAssignmentOperator(BoundDeconstructionAssignmentOperator node) { return VisitDeconstructionAssignmentOperator(node, rightResultOpt: null); } private BoundNode? VisitDeconstructionAssignmentOperator(BoundDeconstructionAssignmentOperator node, TypeWithState? rightResultOpt) { var previousDisableNullabilityAnalysis = _disableNullabilityAnalysis; _disableNullabilityAnalysis = true; var left = node.Left; var right = node.Right; var variables = GetDeconstructionAssignmentVariables(left); if (node.HasErrors) { // In the case of errors, simply visit the right as an r-value to update // any nullability state even though deconstruction is skipped. VisitRvalue(right.Operand); } else { VisitDeconstructionArguments(variables, right.Conversion, right.Operand, rightResultOpt); } variables.FreeAll(v => v.NestedVariables); // https://github.com/dotnet/roslyn/issues/33011: Result type should be inferred and the constraints should // be re-verified. Even though the standard tuple type has no constraints we support that scenario. Constraints_78 // has a test for this case that should start failing when this is fixed. SetNotNullResult(node); _disableNullabilityAnalysis = previousDisableNullabilityAnalysis; return null; } private void VisitDeconstructionArguments(ArrayBuilder<DeconstructionVariable> variables, Conversion conversion, BoundExpression right, TypeWithState? rightResultOpt = null) { Debug.Assert(conversion.Kind == ConversionKind.Deconstruction); if (!conversion.DeconstructionInfo.IsDefault) { VisitDeconstructMethodArguments(variables, conversion, right, rightResultOpt); } else { VisitTupleDeconstructionArguments(variables, conversion.UnderlyingConversions, right); } } private void VisitDeconstructMethodArguments(ArrayBuilder<DeconstructionVariable> variables, Conversion conversion, BoundExpression right, TypeWithState? rightResultOpt) { VisitRvalue(right); // If we were passed an explicit right result, use that rather than the visited result if (rightResultOpt.HasValue) { SetResultType(right, rightResultOpt.Value); } var rightResult = ResultType; var invocation = conversion.DeconstructionInfo.Invocation as BoundCall; var deconstructMethod = invocation?.Method; if (deconstructMethod is object) { Debug.Assert(invocation is object); Debug.Assert(rightResult.Type is object); int n = variables.Count; if (!invocation.InvokedAsExtensionMethod) { _ = CheckPossibleNullReceiver(right); // update the deconstruct method with any inferred type parameters of the containing type if (deconstructMethod.OriginalDefinition != deconstructMethod) { deconstructMethod = deconstructMethod.OriginalDefinition.AsMember((NamedTypeSymbol)rightResult.Type); } } else { if (deconstructMethod.IsGenericMethod) { // re-infer the deconstruct parameters based on the 'this' parameter ArrayBuilder<BoundExpression> placeholderArgs = ArrayBuilder<BoundExpression>.GetInstance(n + 1); placeholderArgs.Add(CreatePlaceholderIfNecessary(right, rightResult.ToTypeWithAnnotations(compilation))); for (int i = 0; i < n; i++) { placeholderArgs.Add(new BoundExpressionWithNullability(variables[i].Expression.Syntax, variables[i].Expression, NullableAnnotation.Oblivious, conversion.DeconstructionInfo.OutputPlaceholders[i].Type)); } deconstructMethod = InferMethodTypeArguments(deconstructMethod, placeholderArgs.ToImmutableAndFree(), invocation.ArgumentRefKindsOpt, invocation.ArgsToParamsOpt, invocation.Expanded); // check the constraints remain valid with the re-inferred parameter types if (ConstraintsHelper.RequiresChecking(deconstructMethod)) { CheckMethodConstraints(invocation.Syntax, deconstructMethod); } } } var parameters = deconstructMethod.Parameters; int offset = invocation.InvokedAsExtensionMethod ? 1 : 0; Debug.Assert(parameters.Length - offset == n); if (invocation.InvokedAsExtensionMethod) { // Check nullability for `this` parameter var argConversion = RemoveConversion(invocation.Arguments[0], includeExplicitConversions: false).conversion; CheckExtensionMethodThisNullability(right, argConversion, deconstructMethod.Parameters[0], rightResult); } for (int i = 0; i < n; i++) { var variable = variables[i]; var parameter = parameters[i + offset]; var underlyingConversion = conversion.UnderlyingConversions[i]; var nestedVariables = variable.NestedVariables; if (nestedVariables != null) { var nestedRight = CreatePlaceholderIfNecessary(invocation.Arguments[i + offset], parameter.TypeWithAnnotations); VisitDeconstructionArguments(nestedVariables, underlyingConversion, right: nestedRight); } else { VisitArgumentConversionAndInboundAssignmentsAndPreConditions(conversionOpt: null, variable.Expression, underlyingConversion, parameter.RefKind, parameter, parameter.TypeWithAnnotations, GetParameterAnnotations(parameter), new VisitArgumentResult(new VisitResult(variable.Type.ToTypeWithState(), variable.Type), stateForLambda: default), extensionMethodThisArgument: false); } } for (int i = 0; i < n; i++) { var variable = variables[i]; var parameter = parameters[i + offset]; var nestedVariables = variable.NestedVariables; if (nestedVariables == null) { VisitArgumentOutboundAssignmentsAndPostConditions( variable.Expression, parameter.RefKind, parameter, parameter.TypeWithAnnotations, GetRValueAnnotations(parameter), new VisitArgumentResult(new VisitResult(variable.Type.ToTypeWithState(), variable.Type), stateForLambda: default), notNullParametersOpt: null, compareExchangeInfoOpt: default); } } } } private void VisitTupleDeconstructionArguments(ArrayBuilder<DeconstructionVariable> variables, ImmutableArray<Conversion> conversions, BoundExpression right) { int n = variables.Count; var rightParts = GetDeconstructionRightParts(right); Debug.Assert(rightParts.Length == n); for (int i = 0; i < n; i++) { var variable = variables[i]; var underlyingConversion = conversions[i]; var rightPart = rightParts[i]; var nestedVariables = variable.NestedVariables; if (nestedVariables != null) { VisitDeconstructionArguments(nestedVariables, underlyingConversion, rightPart); } else { var lvalueType = variable.Type; var leftAnnotations = GetLValueAnnotations(variable.Expression); lvalueType = ApplyLValueAnnotations(lvalueType, leftAnnotations); TypeWithState operandType; TypeWithState valueType; int valueSlot; if (underlyingConversion.IsIdentity) { if (variable.Expression is BoundLocal { DeclarationKind: BoundLocalDeclarationKind.WithInferredType } local) { // when the LHS is a var declaration, we can just visit the right part to infer the type valueType = operandType = VisitRvalueWithState(rightPart); _variables.SetType(local.LocalSymbol, operandType.ToAnnotatedTypeWithAnnotations(compilation)); } else { operandType = default; valueType = VisitOptionalImplicitConversion(rightPart, lvalueType, useLegacyWarnings: true, trackMembers: true, AssignmentKind.Assignment); } valueSlot = MakeSlot(rightPart); } else { operandType = VisitRvalueWithState(rightPart); valueType = VisitConversion( conversionOpt: null, rightPart, underlyingConversion, lvalueType, operandType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: true, AssignmentKind.Assignment, reportTopLevelWarnings: true, reportRemainingWarnings: true, trackMembers: false); valueSlot = -1; } // If the LHS has annotations, we perform an additional check for nullable value types CheckDisallowedNullAssignment(valueType, leftAnnotations, right.Syntax.Location); int targetSlot = MakeSlot(variable.Expression); AdjustSetValue(variable.Expression, ref valueType); TrackNullableStateForAssignment(rightPart, lvalueType, targetSlot, valueType, valueSlot); // Conversion of T to Nullable<T> is equivalent to new Nullable<T>(t). if (targetSlot > 0 && underlyingConversion.Kind == ConversionKind.ImplicitNullable && AreNullableAndUnderlyingTypes(lvalueType.Type, operandType.Type, out TypeWithAnnotations underlyingType)) { valueSlot = MakeSlot(rightPart); if (valueSlot > 0) { var valueBeforeNullableWrapping = TypeWithState.Create(underlyingType.Type, NullableFlowState.NotNull); TrackNullableStateOfNullableValue(targetSlot, lvalueType.Type, rightPart, valueBeforeNullableWrapping, valueSlot); } } } } } private readonly struct DeconstructionVariable { internal readonly BoundExpression Expression; internal readonly TypeWithAnnotations Type; internal readonly ArrayBuilder<DeconstructionVariable>? NestedVariables; internal DeconstructionVariable(BoundExpression expression, TypeWithAnnotations type) { Expression = expression; Type = type; NestedVariables = null; } internal DeconstructionVariable(BoundExpression expression, ArrayBuilder<DeconstructionVariable> nestedVariables) { Expression = expression; Type = default; NestedVariables = nestedVariables; } } private ArrayBuilder<DeconstructionVariable> GetDeconstructionAssignmentVariables(BoundTupleExpression tuple) { var arguments = tuple.Arguments; var builder = ArrayBuilder<DeconstructionVariable>.GetInstance(arguments.Length); foreach (var argument in arguments) { builder.Add(getDeconstructionAssignmentVariable(argument)); } return builder; DeconstructionVariable getDeconstructionAssignmentVariable(BoundExpression expr) { switch (expr.Kind) { case BoundKind.TupleLiteral: case BoundKind.ConvertedTupleLiteral: return new DeconstructionVariable(expr, GetDeconstructionAssignmentVariables((BoundTupleExpression)expr)); default: VisitLValue(expr); return new DeconstructionVariable(expr, LvalueResultType); } } } /// <summary> /// Return the sub-expressions for the righthand side of a deconstruction /// assignment. cf. LocalRewriter.GetRightParts. /// </summary> private ImmutableArray<BoundExpression> GetDeconstructionRightParts(BoundExpression expr) { switch (expr.Kind) { case BoundKind.TupleLiteral: case BoundKind.ConvertedTupleLiteral: return ((BoundTupleExpression)expr).Arguments; case BoundKind.Conversion: { var conv = (BoundConversion)expr; switch (conv.ConversionKind) { case ConversionKind.Identity: case ConversionKind.ImplicitTupleLiteral: return GetDeconstructionRightParts(conv.Operand); } } break; } if (expr.Type is NamedTypeSymbol { IsTupleType: true } tupleType) { // https://github.com/dotnet/roslyn/issues/33011: Should include conversion.UnderlyingConversions[i]. // For instance, Boxing conversions (see Deconstruction_ImplicitBoxingConversion_02) and // ImplicitNullable conversions (see Deconstruction_ImplicitNullableConversion_02). var fields = tupleType.TupleElements; return fields.SelectAsArray((f, e) => (BoundExpression)new BoundFieldAccess(e.Syntax, e, f, constantValueOpt: null), expr); } throw ExceptionUtilities.Unreachable; } public override BoundNode? VisitIncrementOperator(BoundIncrementOperator node) { Debug.Assert(!IsConditionalState); var operandType = VisitRvalueWithState(node.Operand); var operandLvalue = LvalueResultType; bool setResult = false; if (this.State.Reachable) { // https://github.com/dotnet/roslyn/issues/29961 Update increment method based on operand type. MethodSymbol? incrementOperator = (node.OperatorKind.IsUserDefined() && node.MethodOpt?.ParameterCount == 1) ? node.MethodOpt : null; TypeWithAnnotations targetTypeOfOperandConversion; AssignmentKind assignmentKind = AssignmentKind.Assignment; ParameterSymbol? parameter = null; // Analyze operator call properly (honoring [Disallow|Allow|Maybe|NotNull] attribute annotations) https://github.com/dotnet/roslyn/issues/32671 // https://github.com/dotnet/roslyn/issues/29961 Update conversion method based on operand type. if (node.OperandConversion.IsUserDefined && node.OperandConversion.Method?.ParameterCount == 1) { targetTypeOfOperandConversion = node.OperandConversion.Method.ReturnTypeWithAnnotations; } else if (incrementOperator is object) { targetTypeOfOperandConversion = incrementOperator.Parameters[0].TypeWithAnnotations; assignmentKind = AssignmentKind.Argument; parameter = incrementOperator.Parameters[0]; } else { // Either a built-in increment, or an error case. targetTypeOfOperandConversion = default; } TypeWithState resultOfOperandConversionType; if (targetTypeOfOperandConversion.HasType) { // https://github.com/dotnet/roslyn/issues/29961 Should something special be done for targetTypeOfOperandConversion for lifted case? resultOfOperandConversionType = VisitConversion( conversionOpt: null, node.Operand, node.OperandConversion, targetTypeOfOperandConversion, operandType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, assignmentKind, parameter, reportTopLevelWarnings: true, reportRemainingWarnings: true); } else { resultOfOperandConversionType = operandType; } TypeWithState resultOfIncrementType; if (incrementOperator is null) { resultOfIncrementType = resultOfOperandConversionType; } else { resultOfIncrementType = incrementOperator.ReturnTypeWithAnnotations.ToTypeWithState(); } var operandTypeWithAnnotations = operandType.ToTypeWithAnnotations(compilation); resultOfIncrementType = VisitConversion( conversionOpt: null, node, node.ResultConversion, operandTypeWithAnnotations, resultOfIncrementType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Assignment); // https://github.com/dotnet/roslyn/issues/29961 Check node.Type.IsErrorType() instead? if (!node.HasErrors) { var op = node.OperatorKind.Operator(); TypeWithState resultType = (op == UnaryOperatorKind.PrefixIncrement || op == UnaryOperatorKind.PrefixDecrement) ? resultOfIncrementType : operandType; SetResultType(node, resultType); setResult = true; TrackNullableStateForAssignment(node, targetType: operandLvalue, targetSlot: MakeSlot(node.Operand), valueType: resultOfIncrementType); } } if (!setResult) { SetNotNullResult(node); } return null; } public override BoundNode? VisitCompoundAssignmentOperator(BoundCompoundAssignmentOperator node) { var left = node.Left; var right = node.Right; Visit(left); TypeWithAnnotations declaredType = LvalueResultType; TypeWithAnnotations leftLValueType = declaredType; TypeWithState leftResultType = ResultType; Debug.Assert(!IsConditionalState); TypeWithState leftOnRightType = GetAdjustedResult(leftResultType, MakeSlot(node.Left)); // https://github.com/dotnet/roslyn/issues/29962 Update operator based on inferred argument types. if ((object)node.Operator.LeftType != null) { // https://github.com/dotnet/roslyn/issues/29962 Ignoring top-level nullability of operator left parameter. leftOnRightType = VisitConversion( conversionOpt: null, node.Left, node.LeftConversion, TypeWithAnnotations.Create(node.Operator.LeftType), leftOnRightType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Assignment, reportTopLevelWarnings: false, reportRemainingWarnings: true); } else { leftOnRightType = default; } TypeWithState resultType; TypeWithState rightType = VisitRvalueWithState(right); if ((object)node.Operator.ReturnType != null) { if (node.Operator.Kind.IsUserDefined() && (object)node.Operator.Method != null && node.Operator.Method.ParameterCount == 2) { MethodSymbol method = node.Operator.Method; VisitArguments(node, ImmutableArray.Create(node.Left, right), method.ParameterRefKinds, method.Parameters, argsToParamsOpt: default, defaultArguments: default, expanded: true, invokedAsExtensionMethod: false, method); } resultType = InferResultNullability(node.Operator.Kind, node.Operator.Method, node.Operator.ReturnType, leftOnRightType, rightType); FlowAnalysisAnnotations leftAnnotations = GetLValueAnnotations(node.Left); leftLValueType = ApplyLValueAnnotations(leftLValueType, leftAnnotations); resultType = VisitConversion( conversionOpt: null, node, node.FinalConversion, leftLValueType, resultType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Assignment); // If the LHS has annotations, we perform an additional check for nullable value types CheckDisallowedNullAssignment(resultType, leftAnnotations, node.Syntax.Location); } else { resultType = TypeWithState.Create(node.Type, NullableFlowState.NotNull); } AdjustSetValue(left, ref resultType); TrackNullableStateForAssignment(node, leftLValueType, MakeSlot(node.Left), resultType); SetResultType(node, resultType); return null; } public override BoundNode? VisitFixedLocalCollectionInitializer(BoundFixedLocalCollectionInitializer node) { var initializer = node.Expression; if (initializer.Kind == BoundKind.AddressOfOperator) { initializer = ((BoundAddressOfOperator)initializer).Operand; } VisitRvalue(initializer); if (node.Expression.Kind == BoundKind.AddressOfOperator) { SetResultType(node.Expression, TypeWithState.Create(node.Expression.Type, ResultType.State)); } SetNotNullResult(node); return null; } public override BoundNode? VisitAddressOfOperator(BoundAddressOfOperator node) { Visit(node.Operand); SetNotNullResult(node); return null; } private void ReportArgumentWarnings(BoundExpression argument, TypeWithState argumentType, ParameterSymbol parameter) { var paramType = parameter.TypeWithAnnotations; ReportNullableAssignmentIfNecessary(argument, paramType, argumentType, useLegacyWarnings: false, AssignmentKind.Argument, parameterOpt: parameter); if (argumentType.Type is { } argType && IsNullabilityMismatch(paramType.Type, argType)) { ReportNullabilityMismatchInArgument(argument.Syntax, argType, parameter, paramType.Type, forOutput: false); } } private void ReportNullabilityMismatchInRefArgument(BoundExpression argument, TypeSymbol argumentType, ParameterSymbol parameter, TypeSymbol parameterType) { ReportDiagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, argument.Syntax, argumentType, parameterType, GetParameterAsDiagnosticArgument(parameter), GetContainingSymbolAsDiagnosticArgument(parameter)); } /// <summary> /// Report warning passing argument where nested nullability does not match /// parameter (e.g.: calling `void F(object[] o)` with `F(new[] { maybeNull })`). /// </summary> private void ReportNullabilityMismatchInArgument(SyntaxNode argument, TypeSymbol argumentType, ParameterSymbol parameter, TypeSymbol parameterType, bool forOutput) { ReportNullabilityMismatchInArgument(argument.GetLocation(), argumentType, parameter, parameterType, forOutput); } private void ReportNullabilityMismatchInArgument(Location argumentLocation, TypeSymbol argumentType, ParameterSymbol? parameterOpt, TypeSymbol parameterType, bool forOutput) { ReportDiagnostic(forOutput ? ErrorCode.WRN_NullabilityMismatchInArgumentForOutput : ErrorCode.WRN_NullabilityMismatchInArgument, argumentLocation, argumentType, parameterOpt?.Type.IsNonNullableValueType() == true && parameterType.IsNullableType() ? parameterOpt.Type : parameterType, // Compensate for operator lifting GetParameterAsDiagnosticArgument(parameterOpt), GetContainingSymbolAsDiagnosticArgument(parameterOpt)); } private TypeWithAnnotations GetDeclaredLocalResult(LocalSymbol local) { return _variables.TryGetType(local, out TypeWithAnnotations type) ? type : local.TypeWithAnnotations; } private TypeWithAnnotations GetDeclaredParameterResult(ParameterSymbol parameter) { return _variables.TryGetType(parameter, out TypeWithAnnotations type) ? type : parameter.TypeWithAnnotations; } public override BoundNode? VisitBaseReference(BoundBaseReference node) { VisitThisOrBaseReference(node); return null; } public override BoundNode? VisitFieldAccess(BoundFieldAccess node) { var updatedSymbol = VisitMemberAccess(node, node.ReceiverOpt, node.FieldSymbol); SplitIfBooleanConstant(node); SetUpdatedSymbol(node, node.FieldSymbol, updatedSymbol); return null; } public override BoundNode? VisitPropertyAccess(BoundPropertyAccess node) { var property = node.PropertySymbol; var updatedMember = VisitMemberAccess(node, node.ReceiverOpt, property); if (!IsAnalyzingAttribute) { if (_expressionIsRead) { ApplyMemberPostConditions(node.ReceiverOpt, property.GetMethod); } else { ApplyMemberPostConditions(node.ReceiverOpt, property.SetMethod); } } SetUpdatedSymbol(node, property, updatedMember); return null; } public override BoundNode? VisitIndexerAccess(BoundIndexerAccess node) { var receiverOpt = node.ReceiverOpt; var receiverType = VisitRvalueWithState(receiverOpt).Type; // https://github.com/dotnet/roslyn/issues/30598: Mark receiver as not null // after indices have been visited, and only if the receiver has not changed. _ = CheckPossibleNullReceiver(receiverOpt); var indexer = node.Indexer; if (receiverType is object) { // Update indexer based on inferred receiver type. indexer = (PropertySymbol)AsMemberOfType(receiverType, indexer); } VisitArguments(node, node.Arguments, node.ArgumentRefKindsOpt, indexer, node.ArgsToParamsOpt, node.DefaultArguments, node.Expanded); var resultType = ApplyUnconditionalAnnotations(indexer.TypeWithAnnotations.ToTypeWithState(), GetRValueAnnotations(indexer)); SetResult(node, resultType, indexer.TypeWithAnnotations); SetUpdatedSymbol(node, node.Indexer, indexer); return null; } public override BoundNode? VisitIndexOrRangePatternIndexerAccess(BoundIndexOrRangePatternIndexerAccess node) { BoundExpression receiver = node.Receiver; var receiverType = VisitRvalueWithState(receiver).Type; // https://github.com/dotnet/roslyn/issues/30598: Mark receiver as not null // after indices have been visited, and only if the receiver has not changed. _ = CheckPossibleNullReceiver(receiver); VisitRvalue(node.Argument); var patternSymbol = node.PatternSymbol; if (receiverType is object) { patternSymbol = AsMemberOfType(receiverType, patternSymbol); } SetLvalueResultType(node, patternSymbol.GetTypeOrReturnType()); SetUpdatedSymbol(node, node.PatternSymbol, patternSymbol); return null; } public override BoundNode? VisitEventAccess(BoundEventAccess node) { var updatedSymbol = VisitMemberAccess(node, node.ReceiverOpt, node.EventSymbol); SetUpdatedSymbol(node, node.EventSymbol, updatedSymbol); return null; } private Symbol VisitMemberAccess(BoundExpression node, BoundExpression? receiverOpt, Symbol member) { Debug.Assert(!IsConditionalState); var receiverType = (receiverOpt != null) ? VisitRvalueWithState(receiverOpt) : default; SpecialMember? nullableOfTMember = null; if (member.RequiresInstanceReceiver()) { member = AsMemberOfType(receiverType.Type, member); nullableOfTMember = GetNullableOfTMember(member); // https://github.com/dotnet/roslyn/issues/30598: For l-values, mark receiver as not null // after RHS has been visited, and only if the receiver has not changed. bool skipReceiverNullCheck = nullableOfTMember != SpecialMember.System_Nullable_T_get_Value; _ = CheckPossibleNullReceiver(receiverOpt, checkNullableValueType: !skipReceiverNullCheck); } var type = member.GetTypeOrReturnType(); var memberAnnotations = GetRValueAnnotations(member); var resultType = ApplyUnconditionalAnnotations(type.ToTypeWithState(), memberAnnotations); // We are supposed to track information for the node. Use whatever we managed to // accumulate so far. if (PossiblyNullableType(resultType.Type)) { int slot = MakeMemberSlot(receiverOpt, member); if (this.State.HasValue(slot)) { var state = this.State[slot]; resultType = TypeWithState.Create(resultType.Type, state); } } Debug.Assert(!IsConditionalState); if (nullableOfTMember == SpecialMember.System_Nullable_T_get_HasValue && !(receiverOpt is null)) { int containingSlot = MakeSlot(receiverOpt); if (containingSlot > 0) { Split(); this.StateWhenTrue[containingSlot] = NullableFlowState.NotNull; } } SetResult(node, resultType, type); return member; } private SpecialMember? GetNullableOfTMember(Symbol member) { if (member.Kind == SymbolKind.Property) { var getMethod = ((PropertySymbol)member.OriginalDefinition).GetMethod; if ((object)getMethod != null && getMethod.ContainingType.SpecialType == SpecialType.System_Nullable_T) { if (getMethod == compilation.GetSpecialTypeMember(SpecialMember.System_Nullable_T_get_Value)) { return SpecialMember.System_Nullable_T_get_Value; } if (getMethod == compilation.GetSpecialTypeMember(SpecialMember.System_Nullable_T_get_HasValue)) { return SpecialMember.System_Nullable_T_get_HasValue; } } } return null; } private int GetNullableOfTValueSlot(TypeSymbol containingType, int containingSlot, out Symbol? valueProperty, bool forceSlotEvenIfEmpty = false) { Debug.Assert(containingType.IsNullableType()); Debug.Assert(TypeSymbol.Equals(NominalSlotType(containingSlot), containingType, TypeCompareKind.ConsiderEverything2)); var getValue = (MethodSymbol)compilation.GetSpecialTypeMember(SpecialMember.System_Nullable_T_get_Value); valueProperty = getValue?.AsMember((NamedTypeSymbol)containingType)?.AssociatedSymbol; return (valueProperty is null) ? -1 : GetOrCreateSlot(valueProperty, containingSlot, forceSlotEvenIfEmpty: forceSlotEvenIfEmpty); } protected override void VisitForEachExpression(BoundForEachStatement node) { if (node.Expression.Kind != BoundKind.Conversion) { // If we're in this scenario, there was a binding error, and we should suppress any further warnings. Debug.Assert(node.HasErrors); VisitRvalue(node.Expression); return; } var (expr, conversion) = RemoveConversion(node.Expression, includeExplicitConversions: false); SnapshotWalkerThroughConversionGroup(node.Expression, expr); // There are 7 ways that a foreach can be created: // 1. The collection type is an array type. For this, initial binding will generate an implicit reference conversion to // IEnumerable, and we do not need to do any reinferring of enumerators here. // 2. The collection type is dynamic. For this we do the same as 1. // 3. The collection type implements the GetEnumerator pattern. For this, there is an identity conversion. Because // this identity conversion uses nested types from initial binding, we cannot trust them and must instead use // the type of the expression returned from VisitResult to reinfer the enumerator information. // 4. The collection type implements IEnumerable<T>. Only a few cases can hit this without being caught by number 3, // such as a type with a private implementation of IEnumerable<T>, or a type parameter constrained to that type. // In these cases, there will be an implicit conversion to IEnumerable<T>, but this will use types from // initial binding. For this scenario, we need to look through the list of implemented interfaces on the type and // find the version of IEnumerable<T> that it has after nullable analysis, as type substitution could have changed // nested nullability of type parameters. See ForEach_22 for a concrete example of this. // 5. The collection type implements IEnumerable (non-generic). Because this version isn't generic, we don't need to // do any reinference, and the existing conversion can stand as is. // 6. The target framework's System.String doesn't implement IEnumerable. This is a compat case: System.String normally // does implement IEnumerable, but there are certain target frameworks where this isn't the case. The compiler will // still emit code for foreach in these scenarios. // 7. The collection type implements the GetEnumerator pattern via an extension GetEnumerator. For this, there will be // conversion to the parameter of the extension method. // 8. Some binding error occurred, and some other error has already been reported. Usually this doesn't have any kind // of conversion on top, but if there was an explicit conversion in code then we could get past the initial check // for a BoundConversion node. var resultTypeWithState = VisitRvalueWithState(expr); var resultType = resultTypeWithState.Type; Debug.Assert(resultType is object); SetAnalyzedNullability(expr, _visitResult); TypeWithAnnotations targetTypeWithAnnotations; MethodSymbol? reinferredGetEnumeratorMethod = null; if (node.EnumeratorInfoOpt?.GetEnumeratorInfo is { Method: { IsExtensionMethod: true, Parameters: var parameters } } enumeratorMethodInfo) { // this is case 7 // We do not need to do this same analysis for non-extension methods because they do not have generic parameters that // can be inferred from usage like extension methods can. We don't warn about default arguments at the call site, so // there's nothing that can be learned from the non-extension case. var (method, results, _) = VisitArguments( node, enumeratorMethodInfo.Arguments, refKindsOpt: default, parameters, argsToParamsOpt: enumeratorMethodInfo.ArgsToParamsOpt, defaultArguments: enumeratorMethodInfo.DefaultArguments, expanded: false, invokedAsExtensionMethod: true, enumeratorMethodInfo.Method); targetTypeWithAnnotations = results[0].LValueType; reinferredGetEnumeratorMethod = method; } else if (conversion.IsIdentity || (conversion.Kind == ConversionKind.ExplicitReference && resultType.SpecialType == SpecialType.System_String)) { // This is case 3 or 6. targetTypeWithAnnotations = resultTypeWithState.ToTypeWithAnnotations(compilation); } else if (conversion.IsImplicit) { bool isAsync = node.AwaitOpt != null; if (node.Expression.Type!.SpecialType == SpecialType.System_Collections_IEnumerable) { // If this is a conversion to IEnumerable (non-generic), nothing to do. This is cases 1, 2, and 5. targetTypeWithAnnotations = TypeWithAnnotations.Create(node.Expression.Type); } else if (ForEachLoopBinder.IsIEnumerableT(node.Expression.Type.OriginalDefinition, isAsync, compilation)) { // This is case 4. We need to look for the IEnumerable<T> that this reinferred expression implements, // so that we pick up any nested type substitutions that could have occurred. var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; targetTypeWithAnnotations = TypeWithAnnotations.Create(ForEachLoopBinder.GetIEnumerableOfT(resultType, isAsync, compilation, ref discardedUseSiteInfo, out bool foundMultiple)); Debug.Assert(!foundMultiple); Debug.Assert(targetTypeWithAnnotations.HasType); } else { // This is case 8. There was not a successful binding, as a successful binding will _always_ generate one of the // above conversions. Just return, as we want to suppress further errors. return; } } else { // This is also case 8. return; } var convertedResult = VisitConversion( GetConversionIfApplicable(node.Expression, expr), expr, conversion, targetTypeWithAnnotations, resultTypeWithState, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Assignment); bool reportedDiagnostic = node.EnumeratorInfoOpt?.GetEnumeratorInfo.Method is { IsExtensionMethod: true } ? false : CheckPossibleNullReceiver(expr); SetAnalyzedNullability(node.Expression, new VisitResult(convertedResult, convertedResult.ToTypeWithAnnotations(compilation))); TypeWithState currentPropertyGetterTypeWithState; if (node.EnumeratorInfoOpt is null) { currentPropertyGetterTypeWithState = default; } else if (resultType is ArrayTypeSymbol arrayType) { // Even though arrays use the IEnumerator pattern, we use the array element type as the foreach target type, so // directly get our source type from there instead of doing method reinference. currentPropertyGetterTypeWithState = arrayType.ElementTypeWithAnnotations.ToTypeWithState(); } else if (resultType.SpecialType == SpecialType.System_String) { // There are frameworks where System.String does not implement IEnumerable, but we still lower it to a for loop // using the indexer over the individual characters anyway. So the type must be not annotated char. currentPropertyGetterTypeWithState = TypeWithAnnotations.Create(node.EnumeratorInfoOpt.ElementType, NullableAnnotation.NotAnnotated).ToTypeWithState(); } else { // Reinfer the return type of the node.Expression.GetEnumerator().Current property, so that if // the collection changed nested generic types we pick up those changes. reinferredGetEnumeratorMethod ??= (MethodSymbol)AsMemberOfType(convertedResult.Type, node.EnumeratorInfoOpt.GetEnumeratorInfo.Method); var enumeratorReturnType = GetReturnTypeWithState(reinferredGetEnumeratorMethod); if (enumeratorReturnType.State != NullableFlowState.NotNull) { if (!reportedDiagnostic && !(node.Expression is BoundConversion { Operand: { IsSuppressed: true } })) { ReportDiagnostic(ErrorCode.WRN_NullReferenceReceiver, expr.Syntax.GetLocation()); } } var currentPropertyGetter = (MethodSymbol)AsMemberOfType(enumeratorReturnType.Type, node.EnumeratorInfoOpt.CurrentPropertyGetter); currentPropertyGetterTypeWithState = ApplyUnconditionalAnnotations( currentPropertyGetter.ReturnTypeWithAnnotations.ToTypeWithState(), currentPropertyGetter.ReturnTypeFlowAnalysisAnnotations); // Analyze `await MoveNextAsync()` if (node.AwaitOpt is { AwaitableInstancePlaceholder: BoundAwaitableValuePlaceholder moveNextPlaceholder } awaitMoveNextInfo) { var moveNextAsyncMethod = (MethodSymbol)AsMemberOfType(reinferredGetEnumeratorMethod.ReturnType, node.EnumeratorInfoOpt.MoveNextInfo.Method); EnsureAwaitablePlaceholdersInitialized(); var result = new VisitResult(GetReturnTypeWithState(moveNextAsyncMethod), moveNextAsyncMethod.ReturnTypeWithAnnotations); _awaitablePlaceholdersOpt.Add(moveNextPlaceholder, (moveNextPlaceholder, result)); Visit(awaitMoveNextInfo); _awaitablePlaceholdersOpt.Remove(moveNextPlaceholder); } // Analyze `await DisposeAsync()` if (node.EnumeratorInfoOpt is { NeedsDisposal: true, DisposeAwaitableInfo: BoundAwaitableInfo awaitDisposalInfo }) { var disposalPlaceholder = awaitDisposalInfo.AwaitableInstancePlaceholder; bool addedPlaceholder = false; if (node.EnumeratorInfoOpt.PatternDisposeInfo is { Method: var originalDisposeMethod }) // no statically known Dispose method if doing a runtime check { Debug.Assert(disposalPlaceholder is not null); var disposeAsyncMethod = (MethodSymbol)AsMemberOfType(reinferredGetEnumeratorMethod.ReturnType, originalDisposeMethod); EnsureAwaitablePlaceholdersInitialized(); var result = new VisitResult(GetReturnTypeWithState(disposeAsyncMethod), disposeAsyncMethod.ReturnTypeWithAnnotations); _awaitablePlaceholdersOpt.Add(disposalPlaceholder, (disposalPlaceholder, result)); addedPlaceholder = true; } Visit(awaitDisposalInfo); if (addedPlaceholder) { _awaitablePlaceholdersOpt!.Remove(disposalPlaceholder!); } } } SetResultType(expression: null, currentPropertyGetterTypeWithState); } public override void VisitForEachIterationVariables(BoundForEachStatement node) { // ResultType should have been set by VisitForEachExpression, called just before this. var sourceState = node.EnumeratorInfoOpt == null ? default : ResultType; TypeWithAnnotations sourceType = sourceState.ToTypeWithAnnotations(compilation); #pragma warning disable IDE0055 // Fix formatting var variableLocation = node.Syntax switch { ForEachStatementSyntax statement => statement.Identifier.GetLocation(), ForEachVariableStatementSyntax variableStatement => variableStatement.Variable.GetLocation(), _ => throw ExceptionUtilities.UnexpectedValue(node.Syntax) }; #pragma warning restore IDE0055 // Fix formatting if (node.DeconstructionOpt is object) { var assignment = node.DeconstructionOpt.DeconstructionAssignment; // Visit the assignment as a deconstruction with an explicit type VisitDeconstructionAssignmentOperator(assignment, sourceState.HasNullType ? (TypeWithState?)null : sourceState); // https://github.com/dotnet/roslyn/issues/35010: if the iteration variable is a tuple deconstruction, we need to put something in the tree Visit(node.IterationVariableType); } else { Visit(node.IterationVariableType); foreach (var iterationVariable in node.IterationVariables) { var state = NullableFlowState.NotNull; if (!sourceState.HasNullType) { TypeWithAnnotations destinationType = iterationVariable.TypeWithAnnotations; TypeWithState result = sourceState; TypeWithState resultForType = sourceState; if (iterationVariable.IsRef) { // foreach (ref DestinationType variable in collection) if (IsNullabilityMismatch(sourceType, destinationType)) { var foreachSyntax = (ForEachStatementSyntax)node.Syntax; ReportNullabilityMismatchInAssignment(foreachSyntax.Type, sourceType, destinationType); } } else if (iterationVariable is SourceLocalSymbol { IsVar: true }) { // foreach (var variable in collection) destinationType = sourceState.ToAnnotatedTypeWithAnnotations(compilation); _variables.SetType(iterationVariable, destinationType); resultForType = destinationType.ToTypeWithState(); } else { // foreach (DestinationType variable in collection) // and asynchronous variants var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; Conversion conversion = node.ElementConversion.Kind == ConversionKind.UnsetConversionKind ? _conversions.ClassifyImplicitConversionFromType(sourceType.Type, destinationType.Type, ref discardedUseSiteInfo) : node.ElementConversion; result = VisitConversion( conversionOpt: null, conversionOperand: node.IterationVariableType, conversion, destinationType, sourceState, checkConversion: true, fromExplicitCast: !conversion.IsImplicit, useLegacyWarnings: true, AssignmentKind.ForEachIterationVariable, reportTopLevelWarnings: true, reportRemainingWarnings: true, diagnosticLocationOpt: variableLocation); } // In non-error cases we'll only run this loop a single time. In error cases we'll set the nullability of the VariableType multiple times, but at least end up with something SetAnalyzedNullability(node.IterationVariableType, new VisitResult(resultForType, destinationType), isLvalue: true); state = result.State; } int slot = GetOrCreateSlot(iterationVariable); if (slot > 0) { this.State[slot] = state; } } } } public override BoundNode? VisitFromEndIndexExpression(BoundFromEndIndexExpression node) { var result = base.VisitFromEndIndexExpression(node); SetNotNullResult(node); return result; } public override BoundNode? VisitObjectInitializerMember(BoundObjectInitializerMember node) { // Should be handled by VisitObjectCreationExpression. throw ExceptionUtilities.Unreachable; } public override BoundNode? VisitDynamicObjectInitializerMember(BoundDynamicObjectInitializerMember node) { SetNotNullResult(node); return null; } public override BoundNode? VisitBadExpression(BoundBadExpression node) { foreach (var child in node.ChildBoundNodes) { // https://github.com/dotnet/roslyn/issues/35042, we need to implement similar workarounds for object, collection, and dynamic initializers. if (child is BoundLambda lambda) { TakeIncrementalSnapshot(lambda); VisitLambda(lambda, delegateTypeOpt: null); VisitRvalueEpilogue(lambda); } else { VisitRvalue(child as BoundExpression); } } var type = TypeWithAnnotations.Create(node.Type); SetLvalueResultType(node, type); return null; } public override BoundNode? VisitTypeExpression(BoundTypeExpression node) { var result = base.VisitTypeExpression(node); if (node.BoundContainingTypeOpt != null) { VisitTypeExpression(node.BoundContainingTypeOpt); } SetNotNullResult(node); return result; } public override BoundNode? VisitTypeOrValueExpression(BoundTypeOrValueExpression node) { // These should not appear after initial binding except in error cases. var result = base.VisitTypeOrValueExpression(node); SetNotNullResult(node); return result; } public override BoundNode? VisitUnaryOperator(BoundUnaryOperator node) { Debug.Assert(!IsConditionalState); TypeWithState resultType; switch (node.OperatorKind) { case UnaryOperatorKind.BoolLogicalNegation: Visit(node.Operand); if (IsConditionalState) SetConditionalState(StateWhenFalse, StateWhenTrue); resultType = adjustForLifting(ResultType); break; case UnaryOperatorKind.DynamicTrue: // We cannot use VisitCondition, because the operand is not of type bool. // Yet we want to keep the result split if it was split. So we simply visit. Visit(node.Operand); resultType = adjustForLifting(ResultType); break; case UnaryOperatorKind.DynamicLogicalNegation: // We cannot use VisitCondition, because the operand is not of type bool. // Yet we want to keep the result split if it was split. So we simply visit. Visit(node.Operand); // If the state is split, the result is `bool` at runtime and we invert it here. if (IsConditionalState) SetConditionalState(StateWhenFalse, StateWhenTrue); resultType = adjustForLifting(ResultType); break; default: if (node.OperatorKind.IsUserDefined() && node.MethodOpt is MethodSymbol method && method.ParameterCount == 1) { var (operand, conversion) = RemoveConversion(node.Operand, includeExplicitConversions: false); VisitRvalue(operand); var operandResult = ResultType; bool isLifted = node.OperatorKind.IsLifted(); var operandType = GetNullableUnderlyingTypeIfNecessary(isLifted, operandResult); // Update method based on inferred operand type. method = (MethodSymbol)AsMemberOfType(operandType.Type!.StrippedType(), method); // Analyze operator call properly (honoring [Disallow|Allow|Maybe|NotNull] attribute annotations) https://github.com/dotnet/roslyn/issues/32671 var parameter = method.Parameters[0]; _ = VisitConversion( node.Operand as BoundConversion, operand, conversion, parameter.TypeWithAnnotations, operandType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, assignmentKind: AssignmentKind.Argument, parameterOpt: parameter); resultType = GetLiftedReturnTypeIfNecessary(isLifted, method.ReturnTypeWithAnnotations, operandResult.State); SetUpdatedSymbol(node, node.MethodOpt, method); } else { VisitRvalue(node.Operand); resultType = adjustForLifting(ResultType); } break; } SetResultType(node, resultType); return null; TypeWithState adjustForLifting(TypeWithState argumentResult) => TypeWithState.Create(node.Type, node.OperatorKind.IsLifted() ? argumentResult.State : NullableFlowState.NotNull); } public override BoundNode? VisitPointerIndirectionOperator(BoundPointerIndirectionOperator node) { var result = base.VisitPointerIndirectionOperator(node); var type = TypeWithAnnotations.Create(node.Type); SetLvalueResultType(node, type); return result; } public override BoundNode? VisitPointerElementAccess(BoundPointerElementAccess node) { var result = base.VisitPointerElementAccess(node); var type = TypeWithAnnotations.Create(node.Type); SetLvalueResultType(node, type); return result; } public override BoundNode? VisitRefTypeOperator(BoundRefTypeOperator node) { VisitRvalue(node.Operand); SetNotNullResult(node); return null; } public override BoundNode? VisitMakeRefOperator(BoundMakeRefOperator node) { var result = base.VisitMakeRefOperator(node); SetNotNullResult(node); return result; } public override BoundNode? VisitRefValueOperator(BoundRefValueOperator node) { var result = base.VisitRefValueOperator(node); var type = TypeWithAnnotations.Create(node.Type, node.NullableAnnotation); SetLvalueResultType(node, type); return result; } private TypeWithState InferResultNullability(BoundUserDefinedConditionalLogicalOperator node) { if (node.OperatorKind.IsLifted()) { // https://github.com/dotnet/roslyn/issues/33879 Conversions: Lifted operator // Should this use the updated flow type and state? How should it compute nullability? return TypeWithState.Create(node.Type, NullableFlowState.NotNull); } // Update method based on inferred operand types: see https://github.com/dotnet/roslyn/issues/29605. // Analyze operator result properly (honoring [Maybe|NotNull] and [Maybe|NotNullWhen] attribute annotations) https://github.com/dotnet/roslyn/issues/32671 if ((object)node.LogicalOperator != null && node.LogicalOperator.ParameterCount == 2) { return GetReturnTypeWithState(node.LogicalOperator); } else { return default; } } protected override void AfterLeftChildOfBinaryLogicalOperatorHasBeenVisited(BoundExpression node, BoundExpression right, bool isAnd, bool isBool, ref LocalState leftTrue, ref LocalState leftFalse) { Debug.Assert(!IsConditionalState); TypeWithState leftType = ResultType; // https://github.com/dotnet/roslyn/issues/29605 Update operator methods based on inferred operand types. MethodSymbol? logicalOperator = null; MethodSymbol? trueFalseOperator = null; BoundExpression? left = null; switch (node.Kind) { case BoundKind.BinaryOperator: Debug.Assert(!((BoundBinaryOperator)node).OperatorKind.IsUserDefined()); break; case BoundKind.UserDefinedConditionalLogicalOperator: var binary = (BoundUserDefinedConditionalLogicalOperator)node; if (binary.LogicalOperator != null && binary.LogicalOperator.ParameterCount == 2) { logicalOperator = binary.LogicalOperator; left = binary.Left; trueFalseOperator = isAnd ? binary.FalseOperator : binary.TrueOperator; if ((object)trueFalseOperator != null && trueFalseOperator.ParameterCount != 1) { trueFalseOperator = null; } } break; default: throw ExceptionUtilities.UnexpectedValue(node.Kind); } Debug.Assert(trueFalseOperator is null || logicalOperator is object); Debug.Assert(logicalOperator is null || left is object); // Analyze operator call properly (honoring [Disallow|Allow|Maybe|NotNull] attribute annotations) https://github.com/dotnet/roslyn/issues/32671 if (trueFalseOperator is object) { ReportArgumentWarnings(left!, leftType, trueFalseOperator.Parameters[0]); } if (logicalOperator is object) { ReportArgumentWarnings(left!, leftType, logicalOperator.Parameters[0]); } Visit(right); TypeWithState rightType = ResultType; SetResultType(node, InferResultNullabilityOfBinaryLogicalOperator(node, leftType, rightType)); if (logicalOperator is object) { ReportArgumentWarnings(right, rightType, logicalOperator.Parameters[1]); } AfterRightChildOfBinaryLogicalOperatorHasBeenVisited(node, right, isAnd, isBool, ref leftTrue, ref leftFalse); } private TypeWithState InferResultNullabilityOfBinaryLogicalOperator(BoundExpression node, TypeWithState leftType, TypeWithState rightType) { return node switch { BoundBinaryOperator binary => InferResultNullability(binary.OperatorKind, binary.Method, binary.Type, leftType, rightType), BoundUserDefinedConditionalLogicalOperator userDefined => InferResultNullability(userDefined), _ => throw ExceptionUtilities.UnexpectedValue(node) }; } public override BoundNode? VisitAwaitExpression(BoundAwaitExpression node) { var result = base.VisitAwaitExpression(node); var awaitableInfo = node.AwaitableInfo; var placeholder = awaitableInfo.AwaitableInstancePlaceholder; Debug.Assert(placeholder is object); EnsureAwaitablePlaceholdersInitialized(); _awaitablePlaceholdersOpt.Add(placeholder, (node.Expression, _visitResult)); Visit(awaitableInfo); _awaitablePlaceholdersOpt.Remove(placeholder); if (node.Type.IsValueType || node.HasErrors || awaitableInfo.GetResult is null) { SetNotNullResult(node); } else { // It is possible for the awaiter type returned from GetAwaiter to not be a named type. e.g. it could be a type parameter. // Proper handling of this is additional work which only benefits a very uncommon scenario, // so we will just use the originally bound GetResult method in this case. var getResult = awaitableInfo.GetResult; var reinferredGetResult = _visitResult.RValueType.Type is NamedTypeSymbol taskAwaiterType ? getResult.OriginalDefinition.AsMember(taskAwaiterType) : getResult; SetResultType(node, reinferredGetResult.ReturnTypeWithAnnotations.ToTypeWithState()); } return result; } public override BoundNode? VisitTypeOfOperator(BoundTypeOfOperator node) { var result = base.VisitTypeOfOperator(node); SetResultType(node, TypeWithState.Create(node.Type, NullableFlowState.NotNull)); return result; } public override BoundNode? VisitMethodInfo(BoundMethodInfo node) { var result = base.VisitMethodInfo(node); SetNotNullResult(node); return result; } public override BoundNode? VisitFieldInfo(BoundFieldInfo node) { var result = base.VisitFieldInfo(node); SetNotNullResult(node); return result; } public override BoundNode? VisitDefaultLiteral(BoundDefaultLiteral node) { // Can occur in error scenarios and lambda scenarios var result = base.VisitDefaultLiteral(node); SetResultType(node, TypeWithState.Create(node.Type, NullableFlowState.MaybeDefault)); return result; } public override BoundNode? VisitDefaultExpression(BoundDefaultExpression node) { Debug.Assert(!this.IsConditionalState); var result = base.VisitDefaultExpression(node); TypeSymbol type = node.Type; if (EmptyStructTypeCache.IsTrackableStructType(type)) { int slot = GetOrCreatePlaceholderSlot(node); if (slot > 0) { this.State[slot] = NullableFlowState.NotNull; InheritNullableStateOfTrackableStruct(type, slot, valueSlot: -1, isDefaultValue: true); } } // https://github.com/dotnet/roslyn/issues/33344: this fails to produce an updated tuple type for a default expression // (should produce nullable element types for those elements that are of reference types) SetResultType(node, TypeWithState.ForType(type)); return result; } public override BoundNode? VisitIsOperator(BoundIsOperator node) { Debug.Assert(!this.IsConditionalState); var operand = node.Operand; var typeExpr = node.TargetType; VisitPossibleConditionalAccess(operand, out var conditionalStateWhenNotNull); Unsplit(); LocalState stateWhenNotNull; if (!conditionalStateWhenNotNull.IsConditionalState) { stateWhenNotNull = conditionalStateWhenNotNull.State; } else { stateWhenNotNull = conditionalStateWhenNotNull.StateWhenTrue; Join(ref stateWhenNotNull, ref conditionalStateWhenNotNull.StateWhenFalse); } Debug.Assert(node.Type.SpecialType == SpecialType.System_Boolean); SetConditionalState(stateWhenNotNull, State); if (typeExpr.Type?.SpecialType == SpecialType.System_Object) { LearnFromNullTest(operand, ref StateWhenFalse); } VisitTypeExpression(typeExpr); SetNotNullResult(node); return null; } public override BoundNode? VisitAsOperator(BoundAsOperator node) { var argumentType = VisitRvalueWithState(node.Operand); NullableFlowState resultState = NullableFlowState.NotNull; var type = node.Type; if (type.CanContainNull()) { switch (node.Conversion.Kind) { case ConversionKind.Identity: case ConversionKind.ImplicitReference: case ConversionKind.Boxing: case ConversionKind.ImplicitNullable: resultState = argumentType.State; break; default: resultState = NullableFlowState.MaybeDefault; break; } } VisitTypeExpression(node.TargetType); SetResultType(node, TypeWithState.Create(type, resultState)); return null; } public override BoundNode? VisitSizeOfOperator(BoundSizeOfOperator node) { var result = base.VisitSizeOfOperator(node); VisitTypeExpression(node.SourceType); SetNotNullResult(node); return result; } public override BoundNode? VisitArgList(BoundArgList node) { var result = base.VisitArgList(node); Debug.Assert(node.Type.SpecialType == SpecialType.System_RuntimeArgumentHandle); SetNotNullResult(node); return result; } public override BoundNode? VisitArgListOperator(BoundArgListOperator node) { VisitArgumentsEvaluate(node.Syntax, node.Arguments, node.ArgumentRefKindsOpt, parametersOpt: default, argsToParamsOpt: default, defaultArguments: default, expanded: false); Debug.Assert(node.Type is null); SetNotNullResult(node); return null; } public override BoundNode? VisitLiteral(BoundLiteral node) { Debug.Assert(!IsConditionalState); var result = base.VisitLiteral(node); SetResultType(node, TypeWithState.Create(node.Type, node.Type?.CanContainNull() != false && node.ConstantValue?.IsNull == true ? NullableFlowState.MaybeDefault : NullableFlowState.NotNull)); return result; } public override BoundNode? VisitPreviousSubmissionReference(BoundPreviousSubmissionReference node) { var result = base.VisitPreviousSubmissionReference(node); Debug.Assert(node.WasCompilerGenerated); SetNotNullResult(node); return result; } public override BoundNode? VisitHostObjectMemberReference(BoundHostObjectMemberReference node) { var result = base.VisitHostObjectMemberReference(node); Debug.Assert(node.WasCompilerGenerated); SetNotNullResult(node); return result; } public override BoundNode? VisitPseudoVariable(BoundPseudoVariable node) { var result = base.VisitPseudoVariable(node); SetNotNullResult(node); return result; } public override BoundNode? VisitRangeExpression(BoundRangeExpression node) { var result = base.VisitRangeExpression(node); SetNotNullResult(node); return result; } public override BoundNode? VisitRangeVariable(BoundRangeVariable node) { VisitWithoutDiagnostics(node.Value); SetNotNullResult(node); // https://github.com/dotnet/roslyn/issues/29863 Need to review this return null; } public override BoundNode? VisitLabel(BoundLabel node) { var result = base.VisitLabel(node); SetUnknownResultNullability(node); return result; } public override BoundNode? VisitDynamicMemberAccess(BoundDynamicMemberAccess node) { var receiver = node.Receiver; VisitRvalue(receiver); _ = CheckPossibleNullReceiver(receiver); Debug.Assert(node.Type.IsDynamic()); var result = TypeWithAnnotations.Create(node.Type); SetLvalueResultType(node, result); return null; } public override BoundNode? VisitDynamicInvocation(BoundDynamicInvocation node) { var expr = node.Expression; VisitRvalue(expr); // If the expression was a MethodGroup, check nullability of receiver. var receiverOpt = (expr as BoundMethodGroup)?.ReceiverOpt; if (TryGetMethodGroupReceiverNullability(receiverOpt, out TypeWithState receiverType)) { CheckPossibleNullReceiver(receiverOpt, receiverType, checkNullableValueType: false); } VisitArgumentsEvaluate(node.Syntax, node.Arguments, node.ArgumentRefKindsOpt, parametersOpt: default, argsToParamsOpt: default, defaultArguments: default, expanded: false); Debug.Assert(node.Type.IsDynamic()); Debug.Assert(node.Type.IsReferenceType); var result = TypeWithAnnotations.Create(node.Type, NullableAnnotation.Oblivious); SetLvalueResultType(node, result); return null; } public override BoundNode? VisitEventAssignmentOperator(BoundEventAssignmentOperator node) { var receiverOpt = node.ReceiverOpt; VisitRvalue(receiverOpt); Debug.Assert(!IsConditionalState); var @event = node.Event; if ([email protected]) { @event = (EventSymbol)AsMemberOfType(ResultType.Type, @event); // https://github.com/dotnet/roslyn/issues/30598: Mark receiver as not null // after arguments have been visited, and only if the receiver has not changed. _ = CheckPossibleNullReceiver(receiverOpt); SetUpdatedSymbol(node, node.Event, @event); } VisitRvalue(node.Argument); // https://github.com/dotnet/roslyn/issues/31018: Check for delegate mismatch. if (node.Argument.ConstantValue?.IsNull != true && MakeMemberSlot(receiverOpt, @event) is > 0 and var memberSlot) { this.State[memberSlot] = node.IsAddition ? this.State[memberSlot].Meet(ResultType.State) : NullableFlowState.MaybeNull; } SetNotNullResult(node); // https://github.com/dotnet/roslyn/issues/29969 Review whether this is the correct result return null; } public override BoundNode? VisitDynamicObjectCreationExpression(BoundDynamicObjectCreationExpression node) { Debug.Assert(!IsConditionalState); var arguments = node.Arguments; var argumentResults = VisitArgumentsEvaluate(node.Syntax, arguments, node.ArgumentRefKindsOpt, parametersOpt: default, argsToParamsOpt: default, defaultArguments: default, expanded: false); VisitObjectOrDynamicObjectCreation(node, arguments, argumentResults, node.InitializerExpressionOpt); return null; } public override BoundNode? VisitObjectInitializerExpression(BoundObjectInitializerExpression node) { // Only reachable from bad expression. Otherwise handled in VisitObjectCreationExpression(). // https://github.com/dotnet/roslyn/issues/35042: Do we need to analyze child expressions anyway for the public API? SetNotNullResult(node); return null; } public override BoundNode? VisitCollectionInitializerExpression(BoundCollectionInitializerExpression node) { // Only reachable from bad expression. Otherwise handled in VisitObjectCreationExpression(). // https://github.com/dotnet/roslyn/issues/35042: Do we need to analyze child expressions anyway for the public API? SetNotNullResult(node); return null; } public override BoundNode? VisitDynamicCollectionElementInitializer(BoundDynamicCollectionElementInitializer node) { // Only reachable from bad expression. Otherwise handled in VisitObjectCreationExpression(). // https://github.com/dotnet/roslyn/issues/35042: Do we need to analyze child expressions anyway for the public API? SetNotNullResult(node); return null; } public override BoundNode? VisitImplicitReceiver(BoundImplicitReceiver node) { var result = base.VisitImplicitReceiver(node); SetNotNullResult(node); return result; } public override BoundNode? VisitAnonymousPropertyDeclaration(BoundAnonymousPropertyDeclaration node) { throw ExceptionUtilities.Unreachable; } public override BoundNode? VisitNoPiaObjectCreationExpression(BoundNoPiaObjectCreationExpression node) { var result = base.VisitNoPiaObjectCreationExpression(node); SetResultType(node, TypeWithState.Create(node.Type, NullableFlowState.NotNull)); return result; } public override BoundNode? VisitNewT(BoundNewT node) { VisitObjectOrDynamicObjectCreation(node, ImmutableArray<BoundExpression>.Empty, ImmutableArray<VisitArgumentResult>.Empty, node.InitializerExpressionOpt); return null; } public override BoundNode? VisitArrayInitialization(BoundArrayInitialization node) { var result = base.VisitArrayInitialization(node); SetNotNullResult(node); return result; } private void SetUnknownResultNullability(BoundExpression expression) { SetResultType(expression, TypeWithState.Create(expression.Type, default)); } public override BoundNode? VisitStackAllocArrayCreation(BoundStackAllocArrayCreation node) { var result = base.VisitStackAllocArrayCreation(node); Debug.Assert(node.Type is null || node.Type.IsErrorType() || node.Type.IsRefLikeType); SetNotNullResult(node); return result; } public override BoundNode? VisitDynamicIndexerAccess(BoundDynamicIndexerAccess node) { var receiver = node.Receiver; VisitRvalue(receiver); // https://github.com/dotnet/roslyn/issues/30598: Mark receiver as not null // after indices have been visited, and only if the receiver has not changed. _ = CheckPossibleNullReceiver(receiver); VisitArgumentsEvaluate(node.Syntax, node.Arguments, node.ArgumentRefKindsOpt, parametersOpt: default, argsToParamsOpt: default, defaultArguments: default, expanded: false); Debug.Assert(node.Type.IsDynamic()); var result = TypeWithAnnotations.Create(node.Type, NullableAnnotation.Oblivious); SetLvalueResultType(node, result); return null; } private bool CheckPossibleNullReceiver(BoundExpression? receiverOpt, bool checkNullableValueType = false) { return CheckPossibleNullReceiver(receiverOpt, ResultType, checkNullableValueType); } private bool CheckPossibleNullReceiver(BoundExpression? receiverOpt, TypeWithState resultType, bool checkNullableValueType) { Debug.Assert(!this.IsConditionalState); bool reportedDiagnostic = false; if (receiverOpt != null && this.State.Reachable) { var resultTypeSymbol = resultType.Type; if (resultTypeSymbol is null) { return false; } #if DEBUG Debug.Assert(receiverOpt.Type is null || AreCloseEnough(receiverOpt.Type, resultTypeSymbol)); #endif if (!ReportPossibleNullReceiverIfNeeded(resultTypeSymbol, resultType.State, checkNullableValueType, receiverOpt.Syntax, out reportedDiagnostic)) { return reportedDiagnostic; } LearnFromNonNullTest(receiverOpt, ref this.State); } return reportedDiagnostic; } // Returns false if the type wasn't interesting private bool ReportPossibleNullReceiverIfNeeded(TypeSymbol type, NullableFlowState state, bool checkNullableValueType, SyntaxNode syntax, out bool reportedDiagnostic) { reportedDiagnostic = false; if (state.MayBeNull()) { bool isValueType = type.IsValueType; if (isValueType && (!checkNullableValueType || !type.IsNullableTypeOrTypeParameter() || type.GetNullableUnderlyingType().IsErrorType())) { return false; } ReportDiagnostic(isValueType ? ErrorCode.WRN_NullableValueTypeMayBeNull : ErrorCode.WRN_NullReferenceReceiver, syntax); reportedDiagnostic = true; } return true; } private void CheckExtensionMethodThisNullability(BoundExpression expr, Conversion conversion, ParameterSymbol parameter, TypeWithState result) { VisitArgumentConversionAndInboundAssignmentsAndPreConditions( conversionOpt: null, expr, conversion, parameter.RefKind, parameter, parameter.TypeWithAnnotations, GetParameterAnnotations(parameter), new VisitArgumentResult(new VisitResult(result, result.ToTypeWithAnnotations(compilation)), stateForLambda: default), extensionMethodThisArgument: true); } private static bool IsNullabilityMismatch(TypeWithAnnotations type1, TypeWithAnnotations type2) { // Note, when we are paying attention to nullability, we ignore oblivious mismatch. // See TypeCompareKind.ObliviousNullableModifierMatchesAny return type1.Equals(type2, TypeCompareKind.AllIgnoreOptions) && !type1.Equals(type2, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.IgnoreNullableModifiersForReferenceTypes); } private static bool IsNullabilityMismatch(TypeSymbol type1, TypeSymbol type2) { // Note, when we are paying attention to nullability, we ignore oblivious mismatch. // See TypeCompareKind.ObliviousNullableModifierMatchesAny return type1.Equals(type2, TypeCompareKind.AllIgnoreOptions) && !type1.Equals(type2, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.IgnoreNullableModifiersForReferenceTypes); } public override BoundNode? VisitQueryClause(BoundQueryClause node) { var result = base.VisitQueryClause(node); SetNotNullResult(node); // https://github.com/dotnet/roslyn/issues/29863 Implement nullability analysis in LINQ queries return result; } public override BoundNode? VisitNameOfOperator(BoundNameOfOperator node) { var result = base.VisitNameOfOperator(node); SetResultType(node, TypeWithState.Create(node.Type, NullableFlowState.NotNull)); return result; } public override BoundNode? VisitNamespaceExpression(BoundNamespaceExpression node) { var result = base.VisitNamespaceExpression(node); SetUnknownResultNullability(node); return result; } // https://github.com/dotnet/roslyn/issues/54583 // Better handle the constructor propagation //public override BoundNode? VisitInterpolatedString(BoundInterpolatedString node) //{ //} public override BoundNode? VisitUnconvertedInterpolatedString(BoundUnconvertedInterpolatedString node) { // This is only involved with unbound lambdas or when visiting the source of a converted tuple literal var result = base.VisitUnconvertedInterpolatedString(node); SetResultType(node, TypeWithState.Create(node.Type, NullableFlowState.NotNull)); return result; } public override BoundNode? VisitStringInsert(BoundStringInsert node) { var result = base.VisitStringInsert(node); SetUnknownResultNullability(node); return result; } public override BoundNode? VisitInterpolatedStringHandlerPlaceholder(BoundInterpolatedStringHandlerPlaceholder node) { SetNotNullResult(node); return null; } public override BoundNode? VisitInterpolatedStringArgumentPlaceholder(BoundInterpolatedStringArgumentPlaceholder node) { SetNotNullResult(node); return null; } public override BoundNode? VisitConvertedStackAllocExpression(BoundConvertedStackAllocExpression node) { var result = base.VisitConvertedStackAllocExpression(node); SetNotNullResult(node); return result; } public override BoundNode? VisitDiscardExpression(BoundDiscardExpression node) { var result = TypeWithAnnotations.Create(node.Type); var rValueType = TypeWithState.ForType(node.Type); SetResult(node, rValueType, result); return null; } public override BoundNode? VisitThrowExpression(BoundThrowExpression node) { VisitThrow(node.Expression); SetResultType(node, default); return null; } public override BoundNode? VisitThrowStatement(BoundThrowStatement node) { VisitThrow(node.ExpressionOpt); return null; } private void VisitThrow(BoundExpression? expr) { if (expr != null) { var result = VisitRvalueWithState(expr); // Cases: // null // null! // Other (typed) expression, including suppressed ones if (result.MayBeNull) { ReportDiagnostic(ErrorCode.WRN_ThrowPossibleNull, expr.Syntax); } } SetUnreachable(); } public override BoundNode? VisitYieldReturnStatement(BoundYieldReturnStatement node) { BoundExpression expr = node.Expression; if (expr == null) { return null; } var method = (MethodSymbol)CurrentSymbol; TypeWithAnnotations elementType = InMethodBinder.GetIteratorElementTypeFromReturnType(compilation, RefKind.None, method.ReturnType, errorLocation: null, diagnostics: null); _ = VisitOptionalImplicitConversion(expr, elementType, useLegacyWarnings: false, trackMembers: false, AssignmentKind.Return); return null; } protected override void VisitCatchBlock(BoundCatchBlock node, ref LocalState finallyState) { TakeIncrementalSnapshot(node); if (node.Locals.Length > 0) { LocalSymbol local = node.Locals[0]; if (local.DeclarationKind == LocalDeclarationKind.CatchVariable) { int slot = GetOrCreateSlot(local); if (slot > 0) this.State[slot] = NullableFlowState.NotNull; } } if (node.ExceptionSourceOpt != null) { VisitWithoutDiagnostics(node.ExceptionSourceOpt); } base.VisitCatchBlock(node, ref finallyState); } public override BoundNode? VisitLockStatement(BoundLockStatement node) { VisitRvalue(node.Argument); _ = CheckPossibleNullReceiver(node.Argument); VisitStatement(node.Body); return null; } public override BoundNode? VisitAttribute(BoundAttribute node) { VisitArguments(node, node.ConstructorArguments, ImmutableArray<RefKind>.Empty, node.Constructor, argsToParamsOpt: node.ConstructorArgumentsToParamsOpt, defaultArguments: default, expanded: node.ConstructorExpanded, invokedAsExtensionMethod: false); foreach (var assignment in node.NamedArguments) { Visit(assignment); } SetNotNullResult(node); return null; } public override BoundNode? VisitExpressionWithNullability(BoundExpressionWithNullability node) { var typeWithAnnotations = TypeWithAnnotations.Create(node.Type, node.NullableAnnotation); SetResult(node.Expression, typeWithAnnotations.ToTypeWithState(), typeWithAnnotations); return null; } public override BoundNode? VisitDeconstructValuePlaceholder(BoundDeconstructValuePlaceholder node) { SetNotNullResult(node); return null; } public override BoundNode? VisitObjectOrCollectionValuePlaceholder(BoundObjectOrCollectionValuePlaceholder node) { SetNotNullResult(node); return null; } [MemberNotNull(nameof(_awaitablePlaceholdersOpt))] private void EnsureAwaitablePlaceholdersInitialized() { _awaitablePlaceholdersOpt ??= PooledDictionary<BoundAwaitableValuePlaceholder, (BoundExpression AwaitableExpression, VisitResult Result)>.GetInstance(); } public override BoundNode? VisitAwaitableValuePlaceholder(BoundAwaitableValuePlaceholder node) { if (_awaitablePlaceholdersOpt != null && _awaitablePlaceholdersOpt.TryGetValue(node, out var value)) { var result = value.Result; SetResult(node, result.RValueType, result.LValueType); } else { SetNotNullResult(node); } return null; } public override BoundNode? VisitAwaitableInfo(BoundAwaitableInfo node) { Visit(node.AwaitableInstancePlaceholder); Visit(node.GetAwaiter); return null; } public override BoundNode? VisitFunctionPointerInvocation(BoundFunctionPointerInvocation node) { _ = Visit(node.InvokedExpression); Debug.Assert(ResultType is TypeWithState { Type: FunctionPointerTypeSymbol { }, State: NullableFlowState.NotNull }); _ = VisitArguments( node, node.Arguments, node.ArgumentRefKindsOpt, node.FunctionPointer.Signature, argsToParamsOpt: default, defaultArguments: default, expanded: false, invokedAsExtensionMethod: false); var returnTypeWithAnnotations = node.FunctionPointer.Signature.ReturnTypeWithAnnotations; SetResult(node, returnTypeWithAnnotations.ToTypeWithState(), returnTypeWithAnnotations); return null; } protected override string Dump(LocalState state) { return state.Dump(_variables); } protected override bool Meet(ref LocalState self, ref LocalState other) { if (!self.Reachable) return false; if (!other.Reachable) { self = other.Clone(); return true; } Normalize(ref self); Normalize(ref other); return self.Meet(in other); } protected override bool Join(ref LocalState self, ref LocalState other) { if (!other.Reachable) return false; if (!self.Reachable) { self = other.Clone(); return true; } Normalize(ref self); Normalize(ref other); return self.Join(in other); } private void Join(ref PossiblyConditionalState other) { var otherIsConditional = other.IsConditionalState; if (otherIsConditional) { Split(); } if (IsConditionalState) { Join(ref StateWhenTrue, ref otherIsConditional ? ref other.StateWhenTrue : ref other.State); Join(ref StateWhenFalse, ref otherIsConditional ? ref other.StateWhenFalse : ref other.State); } else { Debug.Assert(!otherIsConditional); Join(ref State, ref other.State); } } private LocalState CloneAndUnsplit(ref PossiblyConditionalState conditionalState) { if (!conditionalState.IsConditionalState) { return conditionalState.State.Clone(); } var state = conditionalState.StateWhenTrue.Clone(); Join(ref state, ref conditionalState.StateWhenFalse); return state; } private void SetPossiblyConditionalState(in PossiblyConditionalState conditionalState) { if (!conditionalState.IsConditionalState) { SetState(conditionalState.State); } else { SetConditionalState(conditionalState.StateWhenTrue, conditionalState.StateWhenFalse); } } internal sealed class LocalStateSnapshot { internal readonly int Id; internal readonly LocalStateSnapshot? Container; internal readonly BitVector State; internal LocalStateSnapshot(int id, LocalStateSnapshot? container, BitVector state) { Id = id; Container = container; State = state; } } /// <summary> /// A bit array containing the nullability of variables associated with a method scope. If the method is a /// nested function (a lambda or a local function), there is a reference to the corresponding instance for /// the containing method scope. The instances in the chain are associated with a corresponding /// <see cref="Variables"/> chain, and the <see cref="Id"/> field in this type matches <see cref="Variables.Id"/>. /// </summary> [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] internal struct LocalState : ILocalDataFlowState { private sealed class Boxed { internal LocalState Value; internal Boxed(LocalState value) { Value = value; } } internal readonly int Id; private readonly Boxed? _container; // The representation of a state is a bit vector with two bits per slot: // (false, false) => NotNull, (false, true) => MaybeNull, (true, true) => MaybeDefault. // Slot 0 is used to represent whether the state is reachable (true) or not. private BitVector _state; private LocalState(int id, Boxed? container, BitVector state) { Id = id; _container = container; _state = state; } internal static LocalState Create(LocalStateSnapshot snapshot) { var container = snapshot.Container is null ? null : new Boxed(Create(snapshot.Container)); return new LocalState(snapshot.Id, container, snapshot.State.Clone()); } internal LocalStateSnapshot CreateSnapshot() { return new LocalStateSnapshot(Id, _container?.Value.CreateSnapshot(), _state.Clone()); } public bool Reachable => _state[0]; public bool NormalizeToBottom => false; public static LocalState ReachableState(Variables variables) { return CreateReachableOrUnreachableState(variables, reachable: true); } public static LocalState UnreachableState(Variables variables) { return CreateReachableOrUnreachableState(variables, reachable: false); } private static LocalState CreateReachableOrUnreachableState(Variables variables, bool reachable) { var container = variables.Container is null ? null : new Boxed(CreateReachableOrUnreachableState(variables.Container, reachable)); int capacity = reachable ? variables.NextAvailableIndex : 1; return new LocalState(variables.Id, container, CreateBitVector(capacity, reachable)); } public LocalState CreateNestedMethodState(Variables variables) { Debug.Assert(Id == variables.Container!.Id); return new LocalState(variables.Id, container: new Boxed(this), CreateBitVector(capacity: variables.NextAvailableIndex, reachable: true)); } private static BitVector CreateBitVector(int capacity, bool reachable) { if (capacity < 1) capacity = 1; BitVector state = BitVector.Create(capacity * 2); state[0] = reachable; return state; } private int Capacity => _state.Capacity / 2; private void EnsureCapacity(int capacity) { _state.EnsureCapacity(capacity * 2); } public bool HasVariable(int slot) { if (slot <= 0) { return false; } (int id, int index) = Variables.DeconstructSlot(slot); return HasVariable(id, index); } private bool HasVariable(int id, int index) { if (Id > id) { return _container!.Value.HasValue(id, index); } else { return Id == id; } } public bool HasValue(int slot) { if (slot <= 0) { return false; } (int id, int index) = Variables.DeconstructSlot(slot); return HasValue(id, index); } private bool HasValue(int id, int index) { if (Id != id) { Debug.Assert(Id > id); return _container!.Value.HasValue(id, index); } else { return index < Capacity; } } public void Normalize(NullableWalker walker, Variables variables) { if (Id != variables.Id) { Debug.Assert(Id < variables.Id); Normalize(walker, variables.Container!); } else { _container?.Value.Normalize(walker, variables.Container!); int start = Capacity; EnsureCapacity(variables.NextAvailableIndex); Populate(walker, start); } } public void PopulateAll(NullableWalker walker) { _container?.Value.PopulateAll(walker); Populate(walker, start: 1); } private void Populate(NullableWalker walker, int start) { int capacity = Capacity; for (int index = start; index < capacity; index++) { int slot = Variables.ConstructSlot(Id, index); SetValue(Id, index, walker.GetDefaultState(ref this, slot)); } } public NullableFlowState this[int slot] { get { (int id, int index) = Variables.DeconstructSlot(slot); return GetValue(id, index); } set { (int id, int index) = Variables.DeconstructSlot(slot); SetValue(id, index, value); } } private NullableFlowState GetValue(int id, int index) { if (Id != id) { Debug.Assert(Id > id); return _container!.Value.GetValue(id, index); } else { if (index < Capacity && this.Reachable) { index *= 2; var result = (_state[index + 1], _state[index]) switch { (false, false) => NullableFlowState.NotNull, (false, true) => NullableFlowState.MaybeNull, (true, false) => throw ExceptionUtilities.UnexpectedValue(index), (true, true) => NullableFlowState.MaybeDefault }; return result; } return NullableFlowState.NotNull; } } private void SetValue(int id, int index, NullableFlowState value) { if (Id != id) { Debug.Assert(Id > id); _container!.Value.SetValue(id, index, value); } else { // No states should be modified in unreachable code, as there is only one unreachable state. if (!this.Reachable) return; index *= 2; _state[index] = (value != NullableFlowState.NotNull); _state[index + 1] = (value == NullableFlowState.MaybeDefault); } } internal void ForEach<TArg>(Action<int, TArg> action, TArg arg) { _container?.Value.ForEach(action, arg); for (int index = 1; index < Capacity; index++) { action(Variables.ConstructSlot(Id, index), arg); } } internal LocalState GetStateForVariables(int id) { var state = this; while (state.Id != id) { state = state._container!.Value; } return state; } /// <summary> /// Produce a duplicate of this flow analysis state. /// </summary> /// <returns></returns> public LocalState Clone() { var container = _container is null ? null : new Boxed(_container.Value.Clone()); return new LocalState(Id, container, _state.Clone()); } public bool Join(in LocalState other) { Debug.Assert(Id == other.Id); bool result = false; if (_container is { } && _container.Value.Join(in other._container!.Value)) { result = true; } if (_state.UnionWith(in other._state)) { result = true; } return result; } public bool Meet(in LocalState other) { Debug.Assert(Id == other.Id); bool result = false; if (_container is { } && _container.Value.Meet(in other._container!.Value)) { result = true; } if (_state.IntersectWith(in other._state)) { result = true; } return result; } internal string GetDebuggerDisplay() { var pooledBuilder = PooledStringBuilder.GetInstance(); var builder = pooledBuilder.Builder; builder.Append(" "); int n = Math.Min(Capacity, 8); for (int i = n - 1; i >= 0; i--) builder.Append(_state[i * 2] ? '?' : '!'); return pooledBuilder.ToStringAndFree(); } internal string Dump(Variables variables) { if (!this.Reachable) return "unreachable"; if (Id != variables.Id) return "invalid"; var builder = PooledStringBuilder.GetInstance(); Dump(builder, variables); return builder.ToStringAndFree(); } private void Dump(StringBuilder builder, Variables variables) { _container?.Value.Dump(builder, variables.Container!); for (int index = 1; index < Capacity; index++) { if (getName(Variables.ConstructSlot(Id, index)) is string name) { builder.Append(name); var annotation = GetValue(Id, index) switch { NullableFlowState.MaybeNull => "?", NullableFlowState.MaybeDefault => "??", _ => "!" }; builder.Append(annotation); } } string? getName(int slot) { VariableIdentifier id = variables[slot]; var name = id.Symbol.Name; int containingSlot = id.ContainingSlot; return containingSlot > 0 ? getName(containingSlot) + "." + name : name; } } } internal sealed class LocalFunctionState : AbstractLocalFunctionState { /// <summary> /// Defines the starting state used in the local function body to /// produce diagnostics and determine types. /// </summary> public LocalState StartingState; public LocalFunctionState(LocalState unreachableState) : base(unreachableState.Clone(), unreachableState.Clone()) { StartingState = unreachableState; } } protected override LocalFunctionState CreateLocalFunctionState(LocalFunctionSymbol symbol) { var variables = (symbol.ContainingSymbol is MethodSymbol containingMethod ? _variables.GetVariablesForMethodScope(containingMethod) : null) ?? _variables.GetRootScope(); return new LocalFunctionState(LocalState.UnreachableState(variables)); } private sealed class NullabilityInfoTypeComparer : IEqualityComparer<(NullabilityInfo info, TypeSymbol? type)> { public static readonly NullabilityInfoTypeComparer Instance = new NullabilityInfoTypeComparer(); public bool Equals((NullabilityInfo info, TypeSymbol? type) x, (NullabilityInfo info, TypeSymbol? type) y) { return x.info.Equals(y.info) && Symbols.SymbolEqualityComparer.ConsiderEverything.Equals(x.type, y.type); } public int GetHashCode((NullabilityInfo info, TypeSymbol? type) obj) { return obj.GetHashCode(); } } private sealed class ExpressionAndSymbolEqualityComparer : IEqualityComparer<(BoundNode? expr, Symbol symbol)> { internal static readonly ExpressionAndSymbolEqualityComparer Instance = new ExpressionAndSymbolEqualityComparer(); private ExpressionAndSymbolEqualityComparer() { } public bool Equals((BoundNode? expr, Symbol symbol) x, (BoundNode? expr, Symbol symbol) y) { RoslynDebug.Assert(x.symbol is object); RoslynDebug.Assert(y.symbol is object); // We specifically use reference equality for the symbols here because the BoundNode should be immutable. // We should be storing and retrieving the exact same instance of the symbol, not just an "equivalent" // symbol. return x.expr == y.expr && (object)x.symbol == y.symbol; } public int GetHashCode((BoundNode? expr, Symbol symbol) obj) { RoslynDebug.Assert(obj.symbol is object); return Hash.Combine(obj.expr, obj.symbol.GetHashCode()); } } } }
1
dotnet/roslyn
56,416
Do not include function type conversions in user-defined conversions
Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
cston
"2021-09-15T18:16:38Z"
"2021-09-24T23:24:46Z"
bb99d0bc89bde01650d2a694d720d600dd952dcb
3913f352cf066fa485869d866e4753fa721cbe93
Do not include function type conversions in user-defined conversions. Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
./src/Compilers/CSharp/Test/Semantic/Semantics/DelegateTypeTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class DelegateTypeTests : CSharpTestBase { private const string s_utils = @"using System; using System.Linq; static class Utils { internal static string GetDelegateMethodName(this Delegate d) { var method = d.Method; return Concat(GetTypeName(method.DeclaringType), method.Name); } internal static string GetDelegateTypeName(this Delegate d) { return d.GetType().GetTypeName(); } internal static string GetTypeName(this Type type) { if (type.IsArray) { return GetTypeName(type.GetElementType()) + ""[]""; } string typeName = type.Name; int index = typeName.LastIndexOf('`'); if (index >= 0) { typeName = typeName.Substring(0, index); } typeName = Concat(type.Namespace, typeName); if (!type.IsGenericType) { return typeName; } return $""{typeName}<{string.Join("", "", type.GetGenericArguments().Select(GetTypeName))}>""; } private static string Concat(string container, string name) { return string.IsNullOrEmpty(container) ? name : container + ""."" + name; } }"; private static readonly string s_expressionOfTDelegate0ArgTypeName = ExecutionConditionUtil.IsDesktop ? "System.Linq.Expressions.Expression`1" : "System.Linq.Expressions.Expression0`1"; private static readonly string s_expressionOfTDelegate1ArgTypeName = ExecutionConditionUtil.IsDesktop ? "System.Linq.Expressions.Expression`1" : "System.Linq.Expressions.Expression1`1"; [Fact] public void LanguageVersion() { var source = @"class Program { static void Main() { System.Delegate d; d = Main; d = () => { }; d = delegate () { }; System.Linq.Expressions.Expression e = () => 1; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,13): error CS0428: Cannot convert method group 'Main' to non-delegate type 'Delegate'. Did you intend to invoke the method? // d = Main; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "Main").WithArguments("Main", "System.Delegate").WithLocation(6, 13), // (7,13): error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type // d = () => { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "System.Delegate").WithLocation(7, 13), // (8,13): error CS1660: Cannot convert anonymous method to type 'Delegate' because it is not a delegate type // d = delegate () { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate () { }").WithArguments("anonymous method", "System.Delegate").WithLocation(8, 13), // (9,48): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // System.Linq.Expressions.Expression e = () => 1; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(9, 48)); comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(); } [Fact] public void MethodGroupConversions_01() { var source = @"using System; class Program { static void Main() { object o = Main; ICloneable c = Main; Delegate d = Main; MulticastDelegate m = Main; Report(o); Report(c); Report(d); Report(m); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,20): error CS0428: Cannot convert method group 'Main' to non-delegate type 'object'. Did you intend to invoke the method? // object o = Main; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "Main").WithArguments("Main", "object").WithLocation(6, 20), // (7,24): error CS0428: Cannot convert method group 'Main' to non-delegate type 'ICloneable'. Did you intend to invoke the method? // ICloneable c = Main; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "Main").WithArguments("Main", "System.ICloneable").WithLocation(7, 24), // (8,22): error CS0428: Cannot convert method group 'Main' to non-delegate type 'Delegate'. Did you intend to invoke the method? // Delegate d = Main; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "Main").WithArguments("Main", "System.Delegate").WithLocation(8, 22), // (9,31): error CS0428: Cannot convert method group 'Main' to non-delegate type 'MulticastDelegate'. Did you intend to invoke the method? // MulticastDelegate m = Main; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "Main").WithArguments("Main", "System.MulticastDelegate").WithLocation(9, 31)); comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics( // (6,20): warning CS8974: Converting method group 'Main' to non-delegate type 'object'. Did you intend to invoke the method? // object o = Main; Diagnostic(ErrorCode.WRN_MethGrpToNonDel, "Main").WithArguments("Main", "object").WithLocation(6, 20)); CompileAndVerify(comp, expectedOutput: @"System.Action System.Action System.Action System.Action "); } [Fact] public void MethodGroupConversions_02() { var source = @"using System; class Program { static void Main() { var o = (object)Main; var c = (ICloneable)Main; var d = (Delegate)Main; var m = (MulticastDelegate)Main; Report(o); Report(c); Report(d); Report(m); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,17): error CS0030: Cannot convert type 'method' to 'object' // var o = (object)Main; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(object)Main").WithArguments("method", "object").WithLocation(6, 17), // (7,17): error CS0030: Cannot convert type 'method' to 'ICloneable' // var c = (ICloneable)Main; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(ICloneable)Main").WithArguments("method", "System.ICloneable").WithLocation(7, 17), // (8,17): error CS0030: Cannot convert type 'method' to 'Delegate' // var d = (Delegate)Main; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(Delegate)Main").WithArguments("method", "System.Delegate").WithLocation(8, 17), // (9,17): error CS0030: Cannot convert type 'method' to 'MulticastDelegate' // var m = (MulticastDelegate)Main; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(MulticastDelegate)Main").WithArguments("method", "System.MulticastDelegate").WithLocation(9, 17)); comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"System.Action System.Action System.Action System.Action "); } [Fact] public void MethodGroupConversions_03() { var source = @"class Program { static void Main() { System.Linq.Expressions.Expression e = F; e = (System.Linq.Expressions.Expression)F; System.Linq.Expressions.LambdaExpression l = F; l = (System.Linq.Expressions.LambdaExpression)F; } static int F() => 1; }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (5,48): error CS0428: Cannot convert method group 'F' to non-delegate type 'Expression'. Did you intend to invoke the method? // System.Linq.Expressions.Expression e = F; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "System.Linq.Expressions.Expression").WithLocation(5, 48), // (6,13): error CS0030: Cannot convert type 'method' to 'Expression' // e = (System.Linq.Expressions.Expression)F; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(System.Linq.Expressions.Expression)F").WithArguments("method", "System.Linq.Expressions.Expression").WithLocation(6, 13), // (7,54): error CS0428: Cannot convert method group 'F' to non-delegate type 'LambdaExpression'. Did you intend to invoke the method? // System.Linq.Expressions.LambdaExpression l = F; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "System.Linq.Expressions.LambdaExpression").WithLocation(7, 54), // (8,13): error CS0030: Cannot convert type 'method' to 'LambdaExpression' // l = (System.Linq.Expressions.LambdaExpression)F; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(System.Linq.Expressions.LambdaExpression)F").WithArguments("method", "System.Linq.Expressions.LambdaExpression").WithLocation(8, 13)); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,48): error CS0428: Cannot convert method group 'F' to non-delegate type 'Expression'. Did you intend to invoke the method? // System.Linq.Expressions.Expression e = F; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "System.Linq.Expressions.Expression").WithLocation(5, 48), // (6,13): error CS0428: Cannot convert method group 'F' to non-delegate type 'Expression'. Did you intend to invoke the method? // e = (System.Linq.Expressions.Expression)F; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "(System.Linq.Expressions.Expression)F").WithArguments("F", "System.Linq.Expressions.Expression").WithLocation(6, 13), // (7,54): error CS0428: Cannot convert method group 'F' to non-delegate type 'LambdaExpression'. Did you intend to invoke the method? // System.Linq.Expressions.LambdaExpression l = F; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "System.Linq.Expressions.LambdaExpression").WithLocation(7, 54), // (8,13): error CS0428: Cannot convert method group 'F' to non-delegate type 'LambdaExpression'. Did you intend to invoke the method? // l = (System.Linq.Expressions.LambdaExpression)F; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "(System.Linq.Expressions.LambdaExpression)F").WithArguments("F", "System.Linq.Expressions.LambdaExpression").WithLocation(8, 13)); } [Fact] public void MethodGroupConversions_04() { var source = @"using System; using System.Linq.Expressions; class Program { static void F() { } static void F(object o) { } static void Main() { object o = F; ICloneable c = F; Delegate d = F; MulticastDelegate m = F; Expression e = F; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,20): error CS8917: The delegate type could not be inferred. // object o = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F").WithLocation(9, 20), // (10,24): error CS8917: The delegate type could not be inferred. // ICloneable c = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F").WithLocation(10, 24), // (11,22): error CS8917: The delegate type could not be inferred. // Delegate d = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F").WithLocation(11, 22), // (12,31): error CS8917: The delegate type could not be inferred. // MulticastDelegate m = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F").WithLocation(12, 31), // (13,24): error CS0428: Cannot convert method group 'F' to non-delegate type 'Expression'. Did you intend to invoke the method? // Expression e = F; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "System.Linq.Expressions.Expression").WithLocation(13, 24)); } [Fact] public void LambdaConversions_01() { var source = @"using System; class Program { static void Main() { object o = () => { }; ICloneable c = () => { }; Delegate d = () => { }; MulticastDelegate m = () => { }; Report(o); Report(c); Report(d); Report(m); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,20): error CS1660: Cannot convert lambda expression to type 'object' because it is not a delegate type // object o = () => { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "object").WithLocation(6, 20), // (7,24): error CS1660: Cannot convert lambda expression to type 'ICloneable' because it is not a delegate type // ICloneable c = () => { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "System.ICloneable").WithLocation(7, 24), // (8,22): error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type // Delegate d = () => { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "System.Delegate").WithLocation(8, 22), // (9,31): error CS1660: Cannot convert lambda expression to type 'MulticastDelegate' because it is not a delegate type // MulticastDelegate m = () => { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "System.MulticastDelegate").WithLocation(9, 31)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Action System.Action System.Action System.Action "); } [Fact] public void LambdaConversions_02() { var source = @"using System; class Program { static void Main() { var o = (object)(() => { }); var c = (ICloneable)(() => { }); var d = (Delegate)(() => { }); var m = (MulticastDelegate)(() => { }); Report(o); Report(c); Report(d); Report(m); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,26): error CS1660: Cannot convert lambda expression to type 'object' because it is not a delegate type // var o = (object)(() => { }); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "object").WithLocation(6, 26), // (7,30): error CS1660: Cannot convert lambda expression to type 'ICloneable' because it is not a delegate type // var c = (ICloneable)(() => { }); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "System.ICloneable").WithLocation(7, 30), // (8,28): error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type // var d = (Delegate)(() => { }); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "System.Delegate").WithLocation(8, 28), // (9,37): error CS1660: Cannot convert lambda expression to type 'MulticastDelegate' because it is not a delegate type // var m = (MulticastDelegate)(() => { }); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "System.MulticastDelegate").WithLocation(9, 37)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Action System.Action System.Action System.Action "); } [Fact] public void LambdaConversions_03() { var source = @"using System; using System.Linq.Expressions; class Program { static void Main() { Expression e = () => 1; Report(e); e = (Expression)(() => 2); Report(e); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,24): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // Expression e = () => 1; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(7, 24), // (9,26): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // e = (Expression)(() => 2); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 2").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(9, 26)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: $@"{s_expressionOfTDelegate0ArgTypeName}[System.Func`1[System.Int32]] {s_expressionOfTDelegate0ArgTypeName}[System.Func`1[System.Int32]] "); } [Fact] public void LambdaConversions_04() { var source = @"using System; using System.Linq.Expressions; class Program { static void Main() { LambdaExpression e = () => 1; Report(e); e = (LambdaExpression)(() => 2); Report(e); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,30): error CS1660: Cannot convert lambda expression to type 'LambdaExpression' because it is not a delegate type // LambdaExpression e = () => 1; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Linq.Expressions.LambdaExpression").WithLocation(7, 30), // (9,32): error CS1660: Cannot convert lambda expression to type 'LambdaExpression' because it is not a delegate type // e = (LambdaExpression)(() => 2); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 2").WithArguments("lambda expression", "System.Linq.Expressions.LambdaExpression").WithLocation(9, 32)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: $@"{s_expressionOfTDelegate0ArgTypeName}[System.Func`1[System.Int32]] {s_expressionOfTDelegate0ArgTypeName}[System.Func`1[System.Int32]] "); } [Fact] public void LambdaConversions_05() { var source = @"using System; using System.Linq.Expressions; class Program { static void Main() { Delegate d = x => x; object o = (object)(x => x); Expression e = x => x; e = (Expression)(x => x); LambdaExpression l = x => x; l = (LambdaExpression)(x => x); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,22): error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type // Delegate d = x => x; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "x => x").WithArguments("lambda expression", "System.Delegate").WithLocation(7, 22), // (8,29): error CS1660: Cannot convert lambda expression to type 'object' because it is not a delegate type // object o = (object)(x => x); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "x => x").WithArguments("lambda expression", "object").WithLocation(8, 29), // (9,24): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // Expression e = x => x; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "x => x").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(9, 24), // (10,26): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // e = (Expression)(x => x); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "x => x").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(10, 26), // (11,30): error CS1660: Cannot convert lambda expression to type 'LambdaExpression' because it is not a delegate type // LambdaExpression l = x => x; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "x => x").WithArguments("lambda expression", "System.Linq.Expressions.LambdaExpression").WithLocation(11, 30), // (12,32): error CS1660: Cannot convert lambda expression to type 'LambdaExpression' because it is not a delegate type // l = (LambdaExpression)(x => x); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "x => x").WithArguments("lambda expression", "System.Linq.Expressions.LambdaExpression").WithLocation(12, 32)); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,22): error CS8917: The delegate type could not be inferred. // Delegate d = x => x; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(7, 22), // (8,29): error CS8917: The delegate type could not be inferred. // object o = (object)(x => x); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(8, 29), // (9,24): error CS8917: The delegate type could not be inferred. // Expression e = x => x; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(9, 24), // (10,26): error CS8917: The delegate type could not be inferred. // e = (Expression)(x => x); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(10, 26), // (11,30): error CS8917: The delegate type could not be inferred. // LambdaExpression l = x => x; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(11, 30), // (12,32): error CS8917: The delegate type could not be inferred. // l = (LambdaExpression)(x => x); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(12, 32)); } [Fact] public void LambdaConversions_06() { var sourceA = @"namespace System.Linq.Expressions { public class LambdaExpression<T> { } }"; var sourceB = @"using System; using System.Linq.Expressions; class Program { static void Main() { LambdaExpression<Func<int>> l = () => 1; l = (LambdaExpression<Func<int>>)(() => 2); } }"; var expectedDiagnostics = new[] { // (7,41): error CS1660: Cannot convert lambda expression to type 'LambdaExpression<Func<int>>' because it is not a delegate type // LambdaExpression<Func<int>> l = () => 1; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Linq.Expressions.LambdaExpression<System.Func<int>>").WithLocation(7, 41), // (8,43): error CS1660: Cannot convert lambda expression to type 'LambdaExpression<Func<int>>' because it is not a delegate type // l = (LambdaExpression<Func<int>>)(() => 2); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 2").WithArguments("lambda expression", "System.Linq.Expressions.LambdaExpression<System.Func<int>>").WithLocation(8, 43) }; var comp = CreateCompilation(new[] { sourceA, sourceB }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(new[] { sourceA, sourceB }); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void LambdaConversions_07() { var source = @"using System; class Program { static void Main() { System.Delegate d = () => Main; System.Linq.Expressions.Expression e = () => Main; Report(d); Report(e); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: $@"System.Func`1[System.Action] {s_expressionOfTDelegate0ArgTypeName}[System.Func`1[System.Action]] "); } [Fact] public void AnonymousMethod_01() { var source = @"using System; class Program { static void Main() { object o = delegate () { }; ICloneable c = delegate () { }; Delegate d = delegate () { }; MulticastDelegate m = delegate () { }; Report(o); Report(c); Report(d); Report(m); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,20): error CS1660: Cannot convert anonymous method to type 'object' because it is not a delegate type // object o = delegate () { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate () { }").WithArguments("anonymous method", "object").WithLocation(6, 20), // (7,24): error CS1660: Cannot convert anonymous method to type 'ICloneable' because it is not a delegate type // ICloneable c = delegate () { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate () { }").WithArguments("anonymous method", "System.ICloneable").WithLocation(7, 24), // (8,22): error CS1660: Cannot convert anonymous method to type 'Delegate' because it is not a delegate type // Delegate d = delegate () { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate () { }").WithArguments("anonymous method", "System.Delegate").WithLocation(8, 22), // (9,31): error CS1660: Cannot convert anonymous method to type 'MulticastDelegate' because it is not a delegate type // MulticastDelegate m = delegate () { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate () { }").WithArguments("anonymous method", "System.MulticastDelegate").WithLocation(9, 31)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Action System.Action System.Action System.Action "); } [Fact] public void AnonymousMethod_02() { var source = @"using System.Linq.Expressions; class Program { static void Main() { System.Linq.Expressions.Expression e = delegate () { return 1; }; e = (Expression)delegate () { return 2; }; LambdaExpression l = delegate () { return 3; }; l = (LambdaExpression)delegate () { return 4; }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,48): error CS1660: Cannot convert anonymous method to type 'Expression' because it is not a delegate type // System.Linq.Expressions.Expression e = delegate () { return 1; }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate () { return 1; }").WithArguments("anonymous method", "System.Linq.Expressions.Expression").WithLocation(6, 48), // (7,25): error CS1660: Cannot convert anonymous method to type 'Expression' because it is not a delegate type // e = (Expression)delegate () { return 2; }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate () { return 2; }").WithArguments("anonymous method", "System.Linq.Expressions.Expression").WithLocation(7, 25), // (8,30): error CS1660: Cannot convert anonymous method to type 'LambdaExpression' because it is not a delegate type // LambdaExpression l = delegate () { return 3; }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate () { return 3; }").WithArguments("anonymous method", "System.Linq.Expressions.LambdaExpression").WithLocation(8, 30), // (9,31): error CS1660: Cannot convert anonymous method to type 'LambdaExpression' because it is not a delegate type // l = (LambdaExpression)delegate () { return 4; }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate () { return 4; }").WithArguments("anonymous method", "System.Linq.Expressions.LambdaExpression").WithLocation(9, 31)); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,48): error CS1946: An anonymous method expression cannot be converted to an expression tree // System.Linq.Expressions.Expression e = delegate () { return 1; }; Diagnostic(ErrorCode.ERR_AnonymousMethodToExpressionTree, "delegate () { return 1; }").WithLocation(6, 48), // (7,13): error CS1946: An anonymous method expression cannot be converted to an expression tree // e = (Expression)delegate () { return 2; }; Diagnostic(ErrorCode.ERR_AnonymousMethodToExpressionTree, "(Expression)delegate () { return 2; }").WithLocation(7, 13), // (8,30): error CS1946: An anonymous method expression cannot be converted to an expression tree // LambdaExpression l = delegate () { return 3; }; Diagnostic(ErrorCode.ERR_AnonymousMethodToExpressionTree, "delegate () { return 3; }").WithLocation(8, 30), // (9,13): error CS1946: An anonymous method expression cannot be converted to an expression tree // l = (LambdaExpression)delegate () { return 4; }; Diagnostic(ErrorCode.ERR_AnonymousMethodToExpressionTree, "(LambdaExpression)delegate () { return 4; }").WithLocation(9, 13)); } [Fact] public void DynamicConversion() { var source = @"using System; class Program { static void Main() { dynamic d; d = Main; d = () => 1; } static void Report(dynamic d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,13): error CS0428: Cannot convert method group 'Main' to non-delegate type 'dynamic'. Did you intend to invoke the method? // d = Main; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "Main").WithArguments("Main", "dynamic").WithLocation(7, 13), // (8,13): error CS1660: Cannot convert lambda expression to type 'dynamic' because it is not a delegate type // d = () => 1; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "dynamic").WithLocation(8, 13)); } private static IEnumerable<object?[]> GetMethodGroupData(Func<string, string, DiagnosticDescription[]> getExpectedDiagnostics) { yield return getData("static int F() => 0;", "Program.F", "F", "System.Func<System.Int32>"); yield return getData("static int F() => 0;", "F", "F", "System.Func<System.Int32>"); yield return getData("int F() => 0;", "(new Program()).F", "F", "System.Func<System.Int32>"); yield return getData("static T F<T>() => default;", "Program.F<int>", "F", "System.Func<System.Int32>"); yield return getData("static void F<T>() where T : class { }", "F<object>", "F", "System.Action"); yield return getData("static void F<T>() where T : struct { }", "F<int>", "F", "System.Action"); yield return getData("T F<T>() => default;", "(new Program()).F<int>", "F", "System.Func<System.Int32>"); yield return getData("T F<T>() => default;", "(new Program()).F", "F", null); yield return getData("void F<T>(T t) { }", "(new Program()).F<string>", "F", "System.Action<System.String>"); yield return getData("void F<T>(T t) { }", "(new Program()).F", "F", null); yield return getData("static ref int F() => throw null;", "F", "F", "<>F{00000001}<System.Int32>"); yield return getData("static ref readonly int F() => throw null;", "F", "F", "<>F{00000003}<System.Int32>"); yield return getData("static void F() { }", "F", "F", "System.Action"); yield return getData("static void F(int x, int y) { }", "F", "F", "System.Action<System.Int32, System.Int32>"); yield return getData("static void F(out int x, int y) { x = 0; }", "F", "F", "<>A{00000002}<System.Int32, System.Int32>"); yield return getData("static void F(int x, ref int y) { }", "F", "F", "<>A{00000004}<System.Int32, System.Int32>"); yield return getData("static void F(int x, in int y) { }", "F", "F", "<>A{0000000c}<System.Int32, System.Int32>"); yield return getData("static void F(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16) { }", "F", "F", "System.Action<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object>"); yield return getData("static void F(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) { }", "F", "F", "<>A<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32>"); yield return getData("static object F(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16) => null;", "F", "F", "System.Func<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Object>"); yield return getData("static object F(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) => null;", "F", "F", "<>F<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object>"); object?[] getData(string methodDeclaration, string methodGroupExpression, string methodGroupOnly, string? expectedType) => new object?[] { methodDeclaration, methodGroupExpression, expectedType is null ? getExpectedDiagnostics(methodGroupExpression, methodGroupOnly) : null, expectedType }; } public static IEnumerable<object?[]> GetMethodGroupImplicitConversionData() { return GetMethodGroupData((methodGroupExpression, methodGroupOnly) => { int offset = methodGroupExpression.Length - methodGroupOnly.Length; return new[] { // (6,29): error CS8917: The delegate type could not be inferred. // System.Delegate d = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, methodGroupOnly).WithLocation(6, 29 + offset) }; }); } [Theory] [MemberData(nameof(GetMethodGroupImplicitConversionData))] public void MethodGroup_ImplicitConversion(string methodDeclaration, string methodGroupExpression, DiagnosticDescription[]? expectedDiagnostics, string? expectedType) { var source = $@"class Program {{ {methodDeclaration} static void Main() {{ System.Delegate d = {methodGroupExpression}; System.Console.Write(d.GetDelegateTypeName()); }} }}"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); if (expectedDiagnostics is null) { CompileAndVerify(comp, expectedOutput: expectedType); } else { comp.VerifyDiagnostics(expectedDiagnostics); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value; var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); } public static IEnumerable<object?[]> GetMethodGroupExplicitConversionData() { return GetMethodGroupData((methodGroupExpression, methodGroupOnly) => { int offset = methodGroupExpression.Length - methodGroupOnly.Length; return new[] { // (6,20): error CS0030: Cannot convert type 'method' to 'Delegate' // object o = (System.Delegate)F; Diagnostic(ErrorCode.ERR_NoExplicitConv, $"(System.Delegate){methodGroupExpression}").WithArguments("method", "System.Delegate").WithLocation(6, 20) }; }); } [Theory] [MemberData(nameof(GetMethodGroupExplicitConversionData))] public void MethodGroup_ExplicitConversion(string methodDeclaration, string methodGroupExpression, DiagnosticDescription[]? expectedDiagnostics, string? expectedType) { var source = $@"class Program {{ {methodDeclaration} static void Main() {{ object o = (System.Delegate){methodGroupExpression}; System.Console.Write(o.GetType().GetTypeName()); }} }}"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); if (expectedDiagnostics is null) { CompileAndVerify(comp, expectedOutput: expectedType); } else { comp.VerifyDiagnostics(expectedDiagnostics); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = ((CastExpressionSyntax)tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value).Expression; var typeInfo = model.GetTypeInfo(expr); // https://github.com/dotnet/roslyn/issues/52874: GetTypeInfo() for method group should return inferred delegate type. Assert.Null(typeInfo.Type); Assert.Null(typeInfo.ConvertedType); } public static IEnumerable<object?[]> GetLambdaData() { yield return getData("x => x", null); yield return getData("x => { return x; }", null); yield return getData("x => ref args[0]", null); yield return getData("(x, y) => { }", null); yield return getData("() => 1", "System.Func<System.Int32>"); yield return getData("() => ref args[0]", "<>F{00000001}<System.String>"); yield return getData("() => { }", "System.Action"); yield return getData("(int x, int y) => { }", "System.Action<System.Int32, System.Int32>"); yield return getData("(out int x, int y) => { x = 0; }", "<>A{00000002}<System.Int32, System.Int32>"); yield return getData("(int x, ref int y) => { x = 0; }", "<>A{00000004}<System.Int32, System.Int32>"); yield return getData("(int x, in int y) => { x = 0; }", "<>A{0000000c}<System.Int32, System.Int32>"); yield return getData("(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16) => { }", "System.Action<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object>"); yield return getData("(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) => { }", "<>A<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32>"); yield return getData("(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16) => _1", "System.Func<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32>"); yield return getData("(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) => _1", "<>F<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Int32>"); yield return getData("static () => 1", "System.Func<System.Int32>"); yield return getData("async () => { await System.Threading.Tasks.Task.Delay(0); }", "System.Func<System.Threading.Tasks.Task>"); yield return getData("static async () => { await System.Threading.Tasks.Task.Delay(0); return 0; }", "System.Func<System.Threading.Tasks.Task<System.Int32>>"); yield return getData("() => Main", "System.Func<System.Action<System.String[]>>"); yield return getData("(int x) => x switch { _ => null }", null); yield return getData("_ => { }", null); yield return getData("_ => _", null); yield return getData("() => throw null", null); yield return getData("x => throw null", null); yield return getData("(int x) => throw null", null); yield return getData("() => { throw null; }", "System.Action"); yield return getData("(int x) => { throw null; }", "System.Action<System.Int32>"); yield return getData("(string s) => { if (s.Length > 0) return s; return null; }", "System.Func<System.String, System.String>"); yield return getData("(string s) => { if (s.Length > 0) return default; return s; }", "System.Func<System.String, System.String>"); yield return getData("(int i) => { if (i > 0) return i; return default; }", "System.Func<System.Int32, System.Int32>"); yield return getData("(int x, short y) => { if (x > 0) return x; return y; }", "System.Func<System.Int32, System.Int16, System.Int32>"); yield return getData("(int x, short y) => { if (x > 0) return y; return x; }", "System.Func<System.Int32, System.Int16, System.Int32>"); yield return getData("object () => default", "System.Func<System.Object>"); yield return getData("void () => { }", "System.Action"); // Distinct names for distinct signatures with > 16 parameters: https://github.com/dotnet/roslyn/issues/55570 yield return getData("(int _1, int _2, int _3, int _4, int _5, int _6, int _7, int _8, int _9, int _10, int _11, int _12, int _13, int _14, int _15, int _16, ref int _17) => { }", "<>A{100000000}<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32>"); yield return getData("(int _1, int _2, int _3, int _4, int _5, int _6, int _7, int _8, int _9, int _10, int _11, int _12, int _13, int _14, int _15, int _16, in int _17) => { }", "<>A{300000000}<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32>"); static object?[] getData(string expr, string? expectedType) => new object?[] { expr, expectedType }; } public static IEnumerable<object?[]> GetAnonymousMethodData() { yield return getData("delegate { }", null); yield return getData("delegate () { return 1; }", "System.Func<System.Int32>"); yield return getData("delegate () { return ref args[0]; }", "<>F{00000001}<System.String>"); yield return getData("delegate () { }", "System.Action"); yield return getData("delegate (int x, int y) { }", "System.Action<System.Int32, System.Int32>"); yield return getData("delegate (out int x, int y) { x = 0; }", "<>A{00000002}<System.Int32, System.Int32>"); yield return getData("delegate (int x, ref int y) { x = 0; }", "<>A{00000004}<System.Int32, System.Int32>"); yield return getData("delegate (int x, in int y) { x = 0; }", "<>A{0000000c}<System.Int32, System.Int32>"); yield return getData("delegate (int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16) { }", "System.Action<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object>"); yield return getData("delegate (int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) { }", "<>A<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32>"); yield return getData("delegate (int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16) { return _1; }", "System.Func<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32>"); yield return getData("delegate (int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) { return _1; }", "<>F<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Int32>"); static object?[] getData(string expr, string? expectedType) => new object?[] { expr, expectedType }; } [Theory] [MemberData(nameof(GetLambdaData))] [MemberData(nameof(GetAnonymousMethodData))] public void AnonymousFunction_ImplicitConversion(string anonymousFunction, string? expectedType) { var source = $@"class Program {{ static void Main(string[] args) {{ System.Delegate d = {anonymousFunction}; System.Console.Write(d.GetDelegateTypeName()); }} }}"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); if (expectedType is null) { comp.VerifyDiagnostics( // (5,29): error CS8917: The delegate type could not be inferred. // System.Delegate d = x => x; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, anonymousFunction).WithLocation(5, 29)); } else { CompileAndVerify(comp, expectedOutput: expectedType); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<AnonymousFunctionExpressionSyntax>().Single(); var typeInfo = model.GetTypeInfo(expr); if (expectedType == null) { Assert.Null(typeInfo.Type); } else { Assert.Equal(expectedType, typeInfo.Type.ToTestDisplayString()); } Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); var symbolInfo = model.GetSymbolInfo(expr); var method = (IMethodSymbol)symbolInfo.Symbol!; Assert.Equal(MethodKind.LambdaMethod, method.MethodKind); if (typeInfo.Type is { }) { Assert.True(HaveMatchingSignatures(((INamedTypeSymbol)typeInfo.Type!).DelegateInvokeMethod!, method)); } } [Theory] [MemberData(nameof(GetLambdaData))] [MemberData(nameof(GetAnonymousMethodData))] public void AnonymousFunction_ExplicitConversion(string anonymousFunction, string? expectedType) { var source = $@"class Program {{ static void Main(string[] args) {{ object o = (System.Delegate)({anonymousFunction}); System.Console.Write(o.GetType().GetTypeName()); }} }}"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); if (expectedType is null) { comp.VerifyDiagnostics( // (5,38): error CS8917: The delegate type could not be inferred. // object o = (System.Delegate)(x => x); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, anonymousFunction).WithLocation(5, 38)); } else { CompileAndVerify(comp, expectedOutput: expectedType); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = ((CastExpressionSyntax)tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value).Expression; var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); Assert.Equal(expectedType, typeInfo.ConvertedType?.ToTestDisplayString()); var symbolInfo = model.GetSymbolInfo(expr); var method = (IMethodSymbol)symbolInfo.Symbol!; Assert.Equal(MethodKind.LambdaMethod, method.MethodKind); if (typeInfo.Type is { }) { Assert.True(HaveMatchingSignatures(((INamedTypeSymbol)typeInfo.Type!).DelegateInvokeMethod!, method)); } } private static bool HaveMatchingSignatures(IMethodSymbol methodA, IMethodSymbol methodB) { return MemberSignatureComparer.MethodGroupSignatureComparer.Equals(methodA.GetSymbol<MethodSymbol>(), methodB.GetSymbol<MethodSymbol>()); } public static IEnumerable<object?[]> GetExpressionData() { yield return getData("x => x", null); yield return getData("() => 1", "System.Func<System.Int32>"); yield return getData("(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16) => _1", "System.Func<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32>"); yield return getData("(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) => _1", "<>F<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Int32>"); yield return getData("static () => 1", "System.Func<System.Int32>"); static object?[] getData(string expr, string? expectedType) => new object?[] { expr, expectedType }; } [Theory] [MemberData(nameof(GetExpressionData))] public void Expression_ImplicitConversion(string anonymousFunction, string? expectedType) { var source = $@"class Program {{ static void Main(string[] args) {{ System.Linq.Expressions.Expression e = {anonymousFunction}; }} }}"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); if (expectedType is null) { comp.VerifyDiagnostics( // (5,48): error CS8917: The delegate type could not be inferred. // System.Linq.Expressions.Expression e = x => x; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, anonymousFunction).WithLocation(5, 48)); } else { comp.VerifyDiagnostics(); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<AnonymousFunctionExpressionSyntax>().Single(); var typeInfo = model.GetTypeInfo(expr); if (expectedType == null) { Assert.Null(typeInfo.Type); } else { Assert.Equal($"System.Linq.Expressions.Expression<{expectedType}>", typeInfo.Type.ToTestDisplayString()); } Assert.Equal("System.Linq.Expressions.Expression", typeInfo.ConvertedType!.ToTestDisplayString()); } [Theory] [MemberData(nameof(GetExpressionData))] public void Expression_ExplicitConversion(string anonymousFunction, string? expectedType) { var source = $@"class Program {{ static void Main(string[] args) {{ object o = (System.Linq.Expressions.Expression)({anonymousFunction}); }} }}"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); if (expectedType is null) { comp.VerifyDiagnostics( // (5,57): error CS8917: The delegate type could not be inferred. // object o = (System.Linq.Expressions.Expression)(x => x); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, anonymousFunction).WithLocation(5, 57)); } else { comp.VerifyDiagnostics(); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = ((CastExpressionSyntax)tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value).Expression; var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); if (expectedType is null) { Assert.Null(typeInfo.ConvertedType); } else { Assert.Equal($"System.Linq.Expressions.Expression<{expectedType}>", typeInfo.ConvertedType.ToTestDisplayString()); } } /// <summary> /// Should bind and report diagnostics from anonymous method body /// regardless of whether the delegate type can be inferred. /// </summary> [Fact] public void AnonymousMethodBodyErrors() { var source = @"using System; class Program { static void Main() { Delegate d0 = x0 => { _ = x0.Length; object y0 = 0; _ = y0.Length; }; Delegate d1 = (object x1) => { _ = x1.Length; }; Delegate d2 = (ref object x2) => { _ = x2.Length; }; Delegate d3 = delegate (object x3) { _ = x3.Length; }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (6,23): error CS8917: The delegate type could not be inferred. // Delegate d0 = x0 => { _ = x0.Length; object y0 = 0; _ = y0.Length; }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x0 => { _ = x0.Length; object y0 = 0; _ = y0.Length; }").WithLocation(6, 23), // (6,68): error CS1061: 'object' does not contain a definition for 'Length' and no accessible extension method 'Length' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) // Delegate d0 = x0 => { _ = x0.Length; object y0 = 0; _ = y0.Length; }; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Length").WithArguments("object", "Length").WithLocation(6, 68), // (7,47): error CS1061: 'object' does not contain a definition for 'Length' and no accessible extension method 'Length' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) // Delegate d1 = (object x1) => { _ = x1.Length; }; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Length").WithArguments("object", "Length").WithLocation(7, 47), // (8,51): error CS1061: 'object' does not contain a definition for 'Length' and no accessible extension method 'Length' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) // Delegate d2 = (ref object x2) => { _ = x2.Length; }; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Length").WithArguments("object", "Length").WithLocation(8, 51), // (9,53): error CS1061: 'object' does not contain a definition for 'Length' and no accessible extension method 'Length' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) // Delegate d3 = delegate (object x3) { _ = x3.Length; }; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Length").WithArguments("object", "Length").WithLocation(9, 53)); } public static IEnumerable<object?[]> GetBaseAndDerivedTypesData() { yield return getData("internal void F(object x) { }", "internal static new void F(object x) { }", "F", "F", null, "System.Action<System.Object>"); // instance and static // https://github.com/dotnet/roslyn/issues/52701: Assert failure: Unexpected value 'LessDerived' of type 'Microsoft.CodeAnalysis.CSharp.MemberResolutionKind' #if !DEBUG yield return getData("internal void F(object x) { }", "internal static new void F(object x) { }", "this.F", "F", new[] { // (5,29): error CS0176: Member 'B.F(object)' cannot be accessed with an instance reference; qualify it with a type name instead // System.Delegate d = this.F; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.F").WithArguments("B.F(object)").WithLocation(5, 29) }); // instance and static #endif yield return getData("internal void F(object x) { }", "internal static new void F(object x) { }", "base.F", "F", null, "System.Action<System.Object>"); // instance and static yield return getData("internal static void F(object x) { }", "internal new void F(object x) { }", "F", "F", null, "System.Action<System.Object>"); // static and instance yield return getData("internal static void F(object x) { }", "internal new void F(object x) { }", "this.F", "F", null, "System.Action<System.Object>"); // static and instance yield return getData("internal static void F(object x) { }", "internal new void F(object x) { }", "base.F", "F"); // static and instance yield return getData("internal void F(object x) { }", "internal static void F() { }", "F", "F"); // instance and static, different number of parameters yield return getData("internal void F(object x) { }", "internal static void F() { }", "B.F", "F", null, "System.Action"); // instance and static, different number of parameters yield return getData("internal void F(object x) { }", "internal static void F() { }", "this.F", "F", null, "System.Action<System.Object>"); // instance and static, different number of parameters yield return getData("internal void F(object x) { }", "internal static void F() { }", "base.F", "F", null, "System.Action<System.Object>"); // instance and static, different number of parameters yield return getData("internal static void F() { }", "internal void F(object x) { }", "F", "F"); // static and instance, different number of parameters yield return getData("internal static void F() { }", "internal void F(object x) { }", "B.F", "F", null, "System.Action"); // static and instance, different number of parameters yield return getData("internal static void F() { }", "internal void F(object x) { }", "this.F", "F", null, "System.Action<System.Object>"); // static and instance, different number of parameters yield return getData("internal static void F() { }", "internal void F(object x) { }", "base.F", "F"); // static and instance, different number of parameters yield return getData("internal static void F(object x) { }", "private static void F() { }", "F", "F"); // internal and private yield return getData("private static void F(object x) { }", "internal static void F() { }", "F", "F", null, "System.Action"); // internal and private yield return getData("internal abstract void F(object x);", "internal override void F(object x) { }", "F", "F", null, "System.Action<System.Object>"); // override yield return getData("internal virtual void F(object x) { }", "internal override void F(object x) { }", "F", "F", null, "System.Action<System.Object>"); // override yield return getData("internal void F(object x) { }", "internal void F(object x) { }", "F", "F", null, "System.Action<System.Object>"); // hiding yield return getData("internal void F(object x) { }", "internal new void F(object x) { }", "F", "F", null, "System.Action<System.Object>"); // hiding yield return getData("internal void F(object x) { }", "internal new void F(object y) { }", "F", "F", null, "System.Action<System.Object>"); // different parameter name yield return getData("internal void F(object x) { }", "internal void F(string x) { }", "F", "F"); // different parameter type yield return getData("internal void F(object x) { }", "internal void F(object x, object y) { }", "F", "F"); // different number of parameters yield return getData("internal void F(object x) { }", "internal void F(ref object x) { }", "F", "F"); // different parameter ref kind yield return getData("internal void F(ref object x) { }", "internal void F(object x) { }", "F", "F"); // different parameter ref kind yield return getData("internal abstract object F();", "internal override object F() => throw null;", "F", "F", null, "System.Func<System.Object>"); // override yield return getData("internal virtual object F() => throw null;", "internal override object F() => throw null;", "F", "F", null, "System.Func<System.Object>"); // override yield return getData("internal object F() => throw null;", "internal object F() => throw null;", "F", "F", null, "System.Func<System.Object>"); // hiding yield return getData("internal object F() => throw null;", "internal new object F() => throw null;", "F", "F", null, "System.Func<System.Object>"); // hiding yield return getData("internal string F() => throw null;", "internal new object F() => throw null;", "F", "F"); // different return type yield return getData("internal object F() => throw null;", "internal new ref object F() => throw null;", "F", "F"); // different return ref kind yield return getData("internal ref object F() => throw null;", "internal new object F() => throw null;", "F", "F"); // different return ref kind yield return getData("internal void F(object x) { }", "internal new void F(dynamic x) { }", "F", "F", null, "System.Action<System.Object>"); // object/dynamic yield return getData("internal dynamic F() => throw null;", "internal new object F() => throw null;", "F", "F", null, "System.Func<System.Object>"); // object/dynamic yield return getData("internal void F((object, int) x) { }", "internal new void F((object a, int b) x) { }", "F", "F", null, "System.Action<System.ValueTuple<System.Object, System.Int32>>"); // tuple names yield return getData("internal (object a, int b) F() => throw null;", "internal new (object, int) F() => throw null;", "F", "F", null, "System.Func<System.ValueTuple<System.Object, System.Int32>>"); // tuple names yield return getData("internal void F(System.IntPtr x) { }", "internal new void F(nint x) { }", "F", "F", null, "System.Action<System.IntPtr>"); // System.IntPtr/nint yield return getData("internal nint F() => throw null;", "internal new System.IntPtr F() => throw null;", "F", "F", null, "System.Func<System.IntPtr>"); // System.IntPtr/nint yield return getData("internal void F(object x) { }", @"#nullable enable internal new void F(object? x) { } #nullable disable", "F", "F", null, "System.Action<System.Object>"); // different nullability yield return getData( @"#nullable enable internal object? F() => throw null!; #nullable disable", "internal new object F() => throw null;", "F", "F", null, "System.Func<System.Object>"); // different nullability yield return getData("internal void F() { }", "internal void F<T>() { }", "F", "F"); // different arity yield return getData("internal void F() { }", "internal void F<T>() { }", "F<int>", "F<int>", null, "System.Action"); // different arity yield return getData("internal void F<T>() { }", "internal void F() { }", "F", "F"); // different arity yield return getData("internal void F<T>() { }", "internal void F() { }", "F<int>", "F<int>", null, "System.Action"); // different arity yield return getData("internal void F<T>() { }", "internal void F<T, U>() { }", "F<int>", "F<int>", null, "System.Action"); // different arity yield return getData("internal void F<T>() { }", "internal void F<T, U>() { }", "F<int, object>", "F<int, object>", null, "System.Action"); // different arity yield return getData("internal void F<T>(T t) { }", "internal new void F<U>(U u) { }", "F<int>", "F<int>", null, "System.Action<System.Int32>"); // different type parameter names yield return getData("internal void F<T>(T t) where T : class { }", "internal new void F<T>(T t) { }", "F<object>", "F<object>", null, "System.Action<System.Object>"); // different type parameter constraints yield return getData("internal void F<T>(T t) { }", "internal new void F<T>(T t) where T : class { }", "F<object>", "F<object>", null, "System.Action<System.Object>"); // different type parameter constraints yield return getData("internal void F<T>(T t) { }", "internal new void F<T>(T t) where T : class { }", "base.F<object>", "F<object>", null, "System.Action<System.Object>"); // different type parameter constraints yield return getData("internal void F<T>(T t) where T : class { }", "internal new void F<T>(T t) where T : struct { }", "F<int>", "F<int>", null, "System.Action<System.Int32>"); // different type parameter constraints // https://github.com/dotnet/roslyn/issues/52701: Assert failure: Unexpected value 'LessDerived' of type 'Microsoft.CodeAnalysis.CSharp.MemberResolutionKind' #if !DEBUG yield return getData("internal void F<T>(T t) where T : class { }", "internal new void F<T>(T t) where T : struct { }", "F<object>", "F<object>", new[] { // (5,29): error CS0453: The type 'object' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'B.F<T>(T)' // System.Delegate d = F<object>; Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F<object>").WithArguments("B.F<T>(T)", "T", "object").WithLocation(5, 29) }); // different type parameter constraints #endif static object?[] getData(string methodA, string methodB, string methodGroupExpression, string methodGroupOnly, DiagnosticDescription[]? expectedDiagnostics = null, string? expectedType = null) { if (expectedDiagnostics is null && expectedType is null) { int offset = methodGroupExpression.Length - methodGroupOnly.Length; expectedDiagnostics = new[] { // (5,29): error CS8917: The delegate type could not be inferred. // System.Delegate d = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, methodGroupOnly).WithLocation(5, 29 + offset) }; } return new object?[] { methodA, methodB, methodGroupExpression, expectedDiagnostics, expectedType }; } } [Theory] [MemberData(nameof(GetBaseAndDerivedTypesData))] public void MethodGroup_BaseAndDerivedTypes(string methodA, string methodB, string methodGroupExpression, DiagnosticDescription[]? expectedDiagnostics, string? expectedType) { var source = $@"partial class B {{ void M() {{ System.Delegate d = {methodGroupExpression}; System.Console.Write(d.GetDelegateTypeName()); }} static void Main() {{ new B().M(); }} }} abstract class A {{ {methodA} }} partial class B : A {{ {methodB} }}"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); if (expectedDiagnostics is null) { CompileAndVerify(comp, expectedOutput: expectedType); } else { comp.VerifyDiagnostics(expectedDiagnostics); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value; var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); } public static IEnumerable<object?[]> GetExtensionMethodsSameScopeData() { yield return getData("internal static void F(this object x) { }", "internal static void F(this string x) { }", "string.Empty.F", "F", null, "B.F", "System.Action"); // different parameter type yield return getData("internal static void F(this object x) { }", "internal static void F(this string x) { }", "this.F", "F", null, "A.F", "System.Action"); // different parameter type yield return getData("internal static void F(this object x) { }", "internal static void F(this object x, object y) { }", "this.F", "F"); // different number of parameters yield return getData("internal static void F(this object x, object y) { }", "internal static void F(this object x, ref object y) { }", "this.F", "F"); // different parameter ref kind yield return getData("internal static void F(this object x, ref object y) { }", "internal static void F(this object x, object y) { }", "this.F", "F"); // different parameter ref kind yield return getData("internal static object F(this object x) => throw null;", "internal static ref object F(this object x) => throw null;", "this.F", "F"); // different return ref kind yield return getData("internal static ref object F(this object x) => throw null;", "internal static object F(this object x) => throw null;", "this.F", "F"); // different return ref kind yield return getData("internal static void F(this object x, object y) { }", "internal static void F<T>(this object x, T y) { }", "this.F", "F"); // different arity yield return getData("internal static void F(this object x, object y) { }", "internal static void F<T>(this object x, T y) { }", "this.F<int>", "F<int>", null, "B.F", "System.Action<System.Int32>"); // different arity yield return getData("internal static void F<T>(this object x) { }", "internal static void F(this object x) { }", "this.F", "F"); // different arity yield return getData("internal static void F<T>(this object x) { }", "internal static void F(this object x) { }", "this.F<int>", "F<int>", null, "A.F", "System.Action"); // different arity yield return getData("internal static void F<T>(this T t) where T : class { }", "internal static void F<T>(this T t) { }", "this.F<object>", "F<object>", new[] { // (5,29): error CS0121: The call is ambiguous between the following methods or properties: 'A.F<T>(T)' and 'B.F<T>(T)' // System.Delegate d = this.F<object>; Diagnostic(ErrorCode.ERR_AmbigCall, "this.F<object>").WithArguments("A.F<T>(T)", "B.F<T>(T)").WithLocation(5, 29) }); // different type parameter constraints yield return getData("internal static void F<T>(this T t) { }", "internal static void F<T>(this T t) where T : class { }", "this.F<object>", "F<object>", new[] { // (5,29): error CS0121: The call is ambiguous between the following methods or properties: 'A.F<T>(T)' and 'B.F<T>(T)' // System.Delegate d = this.F<object>; Diagnostic(ErrorCode.ERR_AmbigCall, "this.F<object>").WithArguments("A.F<T>(T)", "B.F<T>(T)").WithLocation(5, 29) }); // different type parameter constraints yield return getData("internal static void F<T>(this T t) where T : class { }", "internal static void F<T>(this T t) where T : struct { }", "this.F<int>", "F<int>", new[] { // (5,34): error CS0123: No overload for 'F' matches delegate 'Action' // System.Delegate d = this.F<int>; Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "F<int>").WithArguments("F", "System.Action").WithLocation(5, 34) }); // different type parameter constraints static object?[] getData(string methodA, string methodB, string methodGroupExpression, string methodGroupOnly, DiagnosticDescription[]? expectedDiagnostics = null, string? expectedMethod = null, string? expectedType = null) { if (expectedDiagnostics is null && expectedType is null) { int offset = methodGroupExpression.Length - methodGroupOnly.Length; expectedDiagnostics = new[] { // (5,29): error CS8917: The delegate type could not be inferred. // System.Delegate d = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, methodGroupOnly).WithLocation(5, 29 + offset) }; } return new object?[] { methodA, methodB, methodGroupExpression, expectedDiagnostics, expectedMethod, expectedType }; } } [Theory] [MemberData(nameof(GetExtensionMethodsSameScopeData))] public void MethodGroup_ExtensionMethodsSameScope(string methodA, string methodB, string methodGroupExpression, DiagnosticDescription[]? expectedDiagnostics, string? expectedMethod, string? expectedType) { var source = $@"class Program {{ void M() {{ System.Delegate d = {methodGroupExpression}; System.Console.Write(""{{0}}: {{1}}"", d.GetDelegateMethodName(), d.GetDelegateTypeName()); }} static void Main() {{ new Program().M(); }} }} static class A {{ {methodA} }} static class B {{ {methodB} }}"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); if (expectedDiagnostics is null) { CompileAndVerify(comp, expectedOutput: $"{expectedMethod}: {expectedType}"); } else { comp.VerifyDiagnostics(expectedDiagnostics); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value; var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); var symbolInfo = model.GetSymbolInfo(expr); // https://github.com/dotnet/roslyn/issues/52870: GetSymbolInfo() should return resolved method from method group. Assert.Null(symbolInfo.Symbol); } public static IEnumerable<object?[]> GetExtensionMethodsDifferentScopeData() { yield return getData("internal static void F(this object x) { }", "internal static void F(this object x) { }", "this.F", "F", null, "A.F", "System.Action"); // hiding yield return getData("internal static void F(this object x) { }", "internal static void F(this object y) { }", "this.F", "F", null, "A.F", "System.Action"); // different parameter name yield return getData("internal static void F(this object x) { }", "internal static void F(this string x) { }", "string.Empty.F", "F", null, "A.F", "System.Action"); // different parameter type yield return getData("internal static void F(this object x) { }", "internal static void F(this string x) { }", "this.F", "F", null, "A.F", "System.Action"); // different parameter type yield return getData("internal static void F(this object x) { }", "internal static void F(this object x, object y) { }", "this.F", "F"); // different number of parameters yield return getData("internal static void F(this object x, object y) { }", "internal static void F(this object x, ref object y) { }", "this.F", "F"); // different parameter ref kind yield return getData("internal static void F(this object x, ref object y) { }", "internal static void F(this object x, object y) { }", "this.F", "F"); // different parameter ref kind yield return getData("internal static object F(this object x) => throw null;", "internal static ref object F(this object x) => throw null;", "this.F", "F"); // different return ref kind yield return getData("internal static ref object F(this object x) => throw null;", "internal static object F(this object x) => throw null;", "this.F", "F"); // different return ref kind yield return getData("internal static void F(this object x, System.IntPtr y) { }", "internal static void F(this object x, nint y) { }", "this.F", "F", null, "A.F", "System.Action<System.IntPtr>"); // System.IntPtr/nint yield return getData("internal static nint F(this object x) => throw null;", "internal static System.IntPtr F(this object x) => throw null;", "this.F", "F", null, "A.F", "System.Func<System.IntPtr>"); // System.IntPtr/nint yield return getData("internal static void F(this object x, object y) { }", "internal static void F<T>(this object x, T y) { }", "this.F", "F"); // different arity yield return getData("internal static void F(this object x, object y) { }", "internal static void F<T>(this object x, T y) { }", "this.F<int>", "F<int>", null, "N.B.F", "System.Action<System.Int32>"); // different arity yield return getData("internal static void F<T>(this object x) { }", "internal static void F(this object x) { }", "this.F", "F"); // different arity yield return getData("internal static void F<T>(this object x) { }", "internal static void F(this object x) { }", "this.F<int>", "F<int>", null, "A.F", "System.Action"); // different arity yield return getData("internal static void F<T>(this T t) where T : class { }", "internal static void F<T>(this T t) { }", "this.F<object>", "F<object>", null, "A.F", "System.Action"); // different type parameter constraints yield return getData("internal static void F<T>(this T t) { }", "internal static void F<T>(this T t) where T : class { }", "this.F<object>", "F<object>", null, "A.F", "System.Action"); // different type parameter constraints yield return getData("internal static void F<T>(this T t) where T : class { }", "internal static void F<T>(this T t) where T : struct { }", "this.F<int>", "F<int>", new[] { // (6,34): error CS0123: No overload for 'F' matches delegate 'Action' // System.Delegate d = this.F<int>; Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "F<int>").WithArguments("F", "System.Action").WithLocation(6, 34) }); // different type parameter constraints static object?[] getData(string methodA, string methodB, string methodGroupExpression, string methodGroupOnly, DiagnosticDescription[]? expectedDiagnostics = null, string? expectedMethod = null, string? expectedType = null) { if (expectedDiagnostics is null && expectedType is null) { int offset = methodGroupExpression.Length - methodGroupOnly.Length; expectedDiagnostics = new[] { // (6,29): error CS8917: The delegate type could not be inferred. // System.Delegate d = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, methodGroupOnly).WithLocation(6, 29 + offset) }; } return new object?[] { methodA, methodB, methodGroupExpression, expectedDiagnostics, expectedMethod, expectedType }; } } [Theory] [MemberData(nameof(GetExtensionMethodsDifferentScopeData))] public void MethodGroup_ExtensionMethodsDifferentScope(string methodA, string methodB, string methodGroupExpression, DiagnosticDescription[]? expectedDiagnostics, string? expectedMethod, string? expectedType) { var source = $@"using N; class Program {{ void M() {{ System.Delegate d = {methodGroupExpression}; System.Console.Write(""{{0}}: {{1}}"", d.GetDelegateMethodName(), d.GetDelegateTypeName()); }} static void Main() {{ new Program().M(); }} }} static class A {{ {methodA} }} namespace N {{ static class B {{ {methodB} }} }}"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); if (expectedDiagnostics is null) { CompileAndVerify(comp, expectedOutput: $"{expectedMethod}: {expectedType}"); } else { comp.VerifyDiagnostics(expectedDiagnostics); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value; var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); var symbolInfo = model.GetSymbolInfo(expr); // https://github.com/dotnet/roslyn/issues/52870: GetSymbolInfo() should return resolved method from method group. Assert.Null(symbolInfo.Symbol); } [WorkItem(55923, "https://github.com/dotnet/roslyn/issues/55923")] [Fact] public void ConvertMethodGroupToObject_01() { var source = @"class Program { static object GetValue() => 0; static void Main() { object x = GetValue; x = GetValue; x = (object)GetValue; #pragma warning disable 8974 object y = GetValue; y = GetValue; y = (object)GetValue; #pragma warning restore 8974 } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,20): error CS0428: Cannot convert method group 'GetValue' to non-delegate type 'object'. Did you intend to invoke the method? // object x = GetValue; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "GetValue").WithArguments("GetValue", "object").WithLocation(6, 20), // (7,13): error CS0428: Cannot convert method group 'GetValue' to non-delegate type 'object'. Did you intend to invoke the method? // x = GetValue; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "GetValue").WithArguments("GetValue", "object").WithLocation(7, 13), // (8,13): error CS0030: Cannot convert type 'method' to 'object' // x = (object)GetValue; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(object)GetValue").WithArguments("method", "object").WithLocation(8, 13), // (10,20): error CS0428: Cannot convert method group 'GetValue' to non-delegate type 'object'. Did you intend to invoke the method? // object y = GetValue; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "GetValue").WithArguments("GetValue", "object").WithLocation(10, 20), // (11,13): error CS0428: Cannot convert method group 'GetValue' to non-delegate type 'object'. Did you intend to invoke the method? // y = GetValue; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "GetValue").WithArguments("GetValue", "object").WithLocation(11, 13), // (12,13): error CS0030: Cannot convert type 'method' to 'object' // y = (object)GetValue; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(object)GetValue").WithArguments("method", "object").WithLocation(12, 13)); var expectedDiagnostics = new[] { // (6,20): warning CS8974: Converting method group 'GetValue' to non-delegate type 'object'. Did you intend to invoke the method? // object x = GetValue; Diagnostic(ErrorCode.WRN_MethGrpToNonDel, "GetValue").WithArguments("GetValue", "object").WithLocation(6, 20), // (7,13): warning CS8974: Converting method group 'GetValue' to non-delegate type 'object'. Did you intend to invoke the method? // x = GetValue; Diagnostic(ErrorCode.WRN_MethGrpToNonDel, "GetValue").WithArguments("GetValue", "object").WithLocation(7, 13) }; comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [WorkItem(55923, "https://github.com/dotnet/roslyn/issues/55923")] [Fact] public void ConvertMethodGroupToObject_02() { var source = @"class Program { static int F() => 0; static object F1() => F; static object F2() => (object)F; static object F3() { return F; } static object F4() { return (object)F; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (4,27): error CS0428: Cannot convert method group 'F' to non-delegate type 'object'. Did you intend to invoke the method? // static object F1() => F; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "object").WithLocation(4, 27), // (5,27): error CS0030: Cannot convert type 'method' to 'object' // static object F2() => (object)F; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(object)F").WithArguments("method", "object").WithLocation(5, 27), // (6,33): error CS0428: Cannot convert method group 'F' to non-delegate type 'object'. Did you intend to invoke the method? // static object F3() { return F; } Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "object").WithLocation(6, 33), // (7,33): error CS0030: Cannot convert type 'method' to 'object' // static object F4() { return (object)F; } Diagnostic(ErrorCode.ERR_NoExplicitConv, "(object)F").WithArguments("method", "object").WithLocation(7, 33)); var expectedDiagnostics = new[] { // (4,27): warning CS8974: Converting method group 'F' to non-delegate type 'object'. Did you intend to invoke the method? // static object F1() => F; Diagnostic(ErrorCode.WRN_MethGrpToNonDel, "F").WithArguments("F", "object").WithLocation(4, 27), // (6,33): warning CS8974: Converting method group 'F' to non-delegate type 'object'. Did you intend to invoke the method? // static object F3() { return F; } Diagnostic(ErrorCode.WRN_MethGrpToNonDel, "F").WithArguments("F", "object").WithLocation(6, 33) }; comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [WorkItem(55923, "https://github.com/dotnet/roslyn/issues/55923")] [Fact] public void ConvertMethodGroupToObject_03() { var source = @"class Program { static int F() => 0; static void Main() { object[] a = new[] { F, (object)F, F }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,30): error CS0428: Cannot convert method group 'F' to non-delegate type 'object'. Did you intend to invoke the method? // object[] a = new[] { F, (object)F, F }; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "object").WithLocation(6, 30), // (6,33): error CS0030: Cannot convert type 'method' to 'object' // object[] a = new[] { F, (object)F, F }; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(object)F").WithArguments("method", "object").WithLocation(6, 33), // (6,44): error CS0428: Cannot convert method group 'F' to non-delegate type 'object'. Did you intend to invoke the method? // object[] a = new[] { F, (object)F, F }; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "object").WithLocation(6, 44)); var expectedDiagnostics = new[] { // (6,30): warning CS8974: Converting method group 'F' to non-delegate type 'object'. Did you intend to invoke the method? // object[] a = new[] { F, (object)F, F }; Diagnostic(ErrorCode.WRN_MethGrpToNonDel, "F").WithArguments("F", "object").WithLocation(6, 30), // (6,44): warning CS8974: Converting method group 'F' to non-delegate type 'object'. Did you intend to invoke the method? // object[] a = new[] { F, (object)F, F }; Diagnostic(ErrorCode.WRN_MethGrpToNonDel, "F").WithArguments("F", "object").WithLocation(6, 44) }; comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void InstanceMethods_01() { var source = @"using System; class Program { object F1() => null; void F2(object x, int y) { } void F() { Delegate d1 = F1; Delegate d2 = this.F2; Console.WriteLine(""{0}, {1}"", d1.GetDelegateTypeName(), d2.GetDelegateTypeName()); } static void Main() { new Program().F(); } }"; CompileAndVerify(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, expectedOutput: "System.Func<System.Object>, System.Action<System.Object, System.Int32>"); } [Fact] public void InstanceMethods_02() { var source = @"using System; class A { protected virtual void F() { Console.WriteLine(nameof(A)); } } class B : A { protected override void F() { Console.WriteLine(nameof(B)); } static void Invoke(Delegate d) { d.DynamicInvoke(); } void M() { Invoke(F); Invoke(this.F); Invoke(base.F); } static void Main() { new B().M(); } }"; CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, expectedOutput: @"B B A"); } [Fact] public void InstanceMethods_03() { var source = @"using System; class A { protected void F() { Console.WriteLine(nameof(A)); } } class B : A { protected new void F() { Console.WriteLine(nameof(B)); } static void Invoke(Delegate d) { d.DynamicInvoke(); } void M() { Invoke(F); Invoke(this.F); Invoke(base.F); } static void Main() { new B().M(); } }"; CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, expectedOutput: @"B B A"); } [Fact] public void InstanceMethods_04() { var source = @"class Program { T F<T>() => default; static void Main() { var p = new Program(); System.Delegate d = p.F; object o = (System.Delegate)p.F; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (7,31): error CS8917: The delegate type could not be inferred. // System.Delegate d = p.F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F").WithLocation(7, 31), // (8,20): error CS0030: Cannot convert type 'method' to 'Delegate' // object o = (System.Delegate)p.F; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(System.Delegate)p.F").WithArguments("method", "System.Delegate").WithLocation(8, 20)); } [Fact] public void MethodGroup_Inaccessible() { var source = @"using System; class A { private static void F() { } internal static void F(object o) { } } class B { static void Main() { Delegate d = A.F; Console.WriteLine(d.GetDelegateTypeName()); } }"; CompileAndVerify(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, expectedOutput: "System.Action<System.Object>"); } [Fact] public void MethodGroup_IncorrectArity() { var source = @"class Program { static void F0(object o) { } static void F0<T>(object o) { } static void F1(object o) { } static void F1<T, U>(object o) { } static void F2<T>(object o) { } static void F2<T, U>(object o) { } static void Main() { System.Delegate d; d = F0<int, object>; d = F1<int>; d = F2; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (12,13): error CS0308: The non-generic method 'Program.F0(object)' cannot be used with type arguments // d = F0<int, object>; Diagnostic(ErrorCode.ERR_HasNoTypeVars, "F0<int, object>").WithArguments("Program.F0(object)", "method").WithLocation(12, 13), // (13,13): error CS0308: The non-generic method 'Program.F1(object)' cannot be used with type arguments // d = F1<int>; Diagnostic(ErrorCode.ERR_HasNoTypeVars, "F1<int>").WithArguments("Program.F1(object)", "method").WithLocation(13, 13), // (14,13): error CS8917: The delegate type could not be inferred. // d = F2; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F2").WithLocation(14, 13)); } [Fact] public void ExtensionMethods_01() { var source = @"static class E { internal static void F1(this object x, int y) { } internal static void F2(this object x) { } } class Program { void F2(int x) { } static void Main() { System.Delegate d; var p = new Program(); d = p.F1; d = p.F2; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (14,15): error CS8917: The delegate type could not be inferred. // d = p.F2; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F2").WithLocation(14, 15)); } [Fact] public void ExtensionMethods_02() { var source = @"using System; static class E { internal static void F(this System.Type x, int y) { } internal static void F(this string x) { } } class Program { static void Main() { Delegate d1 = typeof(Program).F; Delegate d2 = """".F; Console.WriteLine(""{0}, {1}"", d1.GetDelegateTypeName(), d2.GetDelegateTypeName()); } }"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "System.Action<System.Int32>, System.Action"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var exprs = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Select(d => d.Initializer!.Value).ToArray(); Assert.Equal(2, exprs.Length); foreach (var expr in exprs) { var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); } } [Fact] public void ExtensionMethods_03() { var source = @"using N; namespace N { static class E1 { internal static void F1(this object x, int y) { } internal static void F2(this object x, int y) { } internal static void F2(this object x) { } internal static void F3(this object x) { } } } static class E2 { internal static void F1(this object x) { } } class Program { static void Main() { System.Delegate d; var p = new Program(); d = p.F1; d = p.F2; d = p.F3; d = E1.F1; d = E2.F1; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (22,15): error CS8917: The delegate type could not be inferred. // d = p.F1; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F1").WithLocation(22, 15), // (23,15): error CS8917: The delegate type could not be inferred. // d = p.F2; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F2").WithLocation(23, 15)); } [Fact] public void ExtensionMethods_04() { var source = @"static class E { internal static void F1(this object x, int y) { } } static class Program { static void F2(this object x) { } static void Main() { System.Delegate d; d = E.F1; d = F2; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics(); } [Fact] public void ExtensionMethods_05() { var source = @"using System; static class E { internal static void F(this A a) { } } class A { } class B : A { static void Invoke(Delegate d) { } void M() { Invoke(F); Invoke(this.F); Invoke(base.F); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (14,16): error CS0103: The name 'F' does not exist in the current context // Invoke(F); Diagnostic(ErrorCode.ERR_NameNotInContext, "F").WithArguments("F").WithLocation(14, 16), // (16,21): error CS0117: 'A' does not contain a definition for 'F' // Invoke(base.F); Diagnostic(ErrorCode.ERR_NoSuchMember, "F").WithArguments("A", "F").WithLocation(16, 21)); } [Fact] public void ExtensionMethods_06() { var source = @"static class E { internal static void F1<T>(this object x, T y) { } internal static void F2<T, U>(this T t) { } } class Program { static void F<T>(T t) where T : class { System.Delegate d; d = t.F1; d = t.F2; d = t.F1<int>; d = t.F1<T>; d = t.F2<T, object>; d = t.F2<object, T>; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (11,15): error CS8917: The delegate type could not be inferred. // d = t.F1; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F1").WithLocation(11, 15), // (12,15): error CS8917: The delegate type could not be inferred. // d = t.F2; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F2").WithLocation(12, 15)); } /// <summary> /// Method group with dynamic receiver does not use method group conversion. /// </summary> [Fact] public void DynamicReceiver() { var source = @"using System; class Program { void F() { } static void Main() { dynamic d = new Program(); object obj; try { obj = d.F; } catch (Exception e) { obj = e; } Console.WriteLine(obj.GetType().FullName); } }"; CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, references: new[] { CSharpRef }, expectedOutput: "Microsoft.CSharp.RuntimeBinder.RuntimeBinderException"); } // System.Func<> and System.Action<> cannot be used as the delegate type // when the parameters or return type are not valid type arguments. [WorkItem(55217, "https://github.com/dotnet/roslyn/issues/55217")] [Fact] public void InvalidTypeArguments() { var source = @"unsafe class Program { static int* F() => throw null; static void Main() { System.Delegate d; d = F; d = (int x, int* y) => { }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview, options: TestOptions.UnsafeReleaseExe); comp.VerifyDiagnostics( // (7,13): error CS8917: The delegate type could not be inferred. // d = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F").WithLocation(7, 13), // (8,13): error CS8917: The delegate type could not be inferred. // d = (int x, int* y) => { }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(int x, int* y) => { }").WithLocation(8, 13)); } [Fact] public void GenericDelegateType() { var source = @"using System; class Program { static void Main() { Delegate d = F<int>(); Console.WriteLine(d.GetDelegateTypeName()); } unsafe static Delegate F<T>() { return (T t, int* p) => { }; } }"; // When we synthesize delegate types with parameter types (such as int*) that cannot // be used as type arguments, run the program to report the actual delegate type. var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.UnsafeReleaseExe); comp.VerifyDiagnostics( // (11,16): error CS8917: The delegate type could not be inferred. // return (T t, int* p) => { }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(T t, int* p) => { }").WithLocation(11, 16)); } [Fact] public void Member_01() { var source = @"using System; class Program { static void Main() { Console.WriteLine((() => { }).GetType()); } }"; var expectedDiagnostics = new[] { // (6,27): error CS0023: Operator '.' cannot be applied to operand of type 'lambda expression' // Console.WriteLine((() => { }).GetType()); Diagnostic(ErrorCode.ERR_BadUnaryOp, "(() => { }).GetType").WithArguments(".", "lambda expression").WithLocation(6, 27) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void Member_02() { var source = @"using System; class Program { static void Main() { Console.WriteLine(Main.GetType()); } }"; var expectedDiagnostics = new[] { // (6,27): error CS0119: 'Program.Main()' is a method, which is not valid in the given context // Console.WriteLine(Main.GetType()); Diagnostic(ErrorCode.ERR_BadSKunknown, "Main").WithArguments("Program.Main()", "method").WithLocation(6, 27) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(expectedDiagnostics); } /// <summary> /// Custom modifiers should not affect delegate signature. /// </summary> [Fact] public void CustomModifiers_01() { var sourceA = @".class public A { .method public static void F1(object modopt(int32) x) { ldnull throw } .method public static object modopt(int32) F2() { ldnull throw } }"; var refA = CompileIL(sourceA); var sourceB = @"using System; class B { static void Report(Delegate d) { Console.WriteLine(d.GetDelegateTypeName()); } static void Main() { Report(A.F1); Report(A.F2); } }"; var comp = CreateCompilation(new[] { sourceB, s_utils }, new[] { refA }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"System.Action<System.Object> System.Func<System.Object>"); } /// <summary> /// Custom modifiers should not affect delegate signature. /// </summary> [Fact] public void CustomModifiers_02() { var sourceA = @".class public A { .method public static void F1(object modreq(int32) x) { ldnull throw } .method public static object modreq(int32) F2() { ldnull throw } }"; var refA = CompileIL(sourceA); var sourceB = @"using System; class B { static void Report(Delegate d) { Console.WriteLine(d.GetDelegateTypeName()); } static void Main() { Report(A.F1); Report(A.F2); } }"; var comp = CreateCompilation(new[] { sourceB, s_utils }, new[] { refA }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics( // (10,16): error CS0570: 'A.F1(object)' is not supported by the language // Report(A.F1); Diagnostic(ErrorCode.ERR_BindToBogus, "A.F1").WithArguments("A.F1(object)").WithLocation(10, 16), // (10,16): error CS0648: '' is a type not supported by the language // Report(A.F1); Diagnostic(ErrorCode.ERR_BogusType, "A.F1").WithArguments("").WithLocation(10, 16), // (11,16): error CS0570: 'A.F2()' is not supported by the language // Report(A.F2); Diagnostic(ErrorCode.ERR_BindToBogus, "A.F2").WithArguments("A.F2()").WithLocation(11, 16), // (11,16): error CS0648: '' is a type not supported by the language // Report(A.F2); Diagnostic(ErrorCode.ERR_BogusType, "A.F2").WithArguments("").WithLocation(11, 16)); } [Fact] public void UnmanagedCallersOnlyAttribute_01() { var source = @"using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; class Program { static void Main() { Delegate d = F; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] static void F() { } }"; var comp = CreateCompilation(new[] { source, UnmanagedCallersOnlyAttributeDefinition }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (8,22): error CS8902: 'Program.F()' is attributed with 'UnmanagedCallersOnly' and cannot be converted to a delegate type. Obtain a function pointer to this method. // Delegate d = F; Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeConvertedToDelegate, "F").WithArguments("Program.F()").WithLocation(8, 22)); } [Fact] public void UnmanagedCallersOnlyAttribute_02() { var source = @"using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; class Program { static void Main() { Delegate d = new S().F; } } struct S { } static class E1 { [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] public static void F(this S s) { } } static class E2 { [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] public static void F(this S s) { } }"; var comp = CreateCompilation(new[] { source, UnmanagedCallersOnlyAttributeDefinition }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (8,22): error CS0121: The call is ambiguous between the following methods or properties: 'E1.F(S)' and 'E2.F(S)' // Delegate d = new S().F; Diagnostic(ErrorCode.ERR_AmbigCall, "new S().F").WithArguments("E1.F(S)", "E2.F(S)").WithLocation(8, 22)); } [Fact] public void SystemActionAndFunc_Missing() { var sourceA = @".assembly mscorlib { .ver 0:0:0:0 } .class public System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.ValueType extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.String extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Void extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Boolean extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Int32 extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Delegate extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.MulticastDelegate extends System.Delegate { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } }"; var refA = CompileIL(sourceA, prependDefaultHeader: false, autoInherit: false); var sourceB = @"class Program { static void Main() { System.Delegate d; d = Main; d = () => 1; } }"; var comp = CreateEmptyCompilation(sourceB, new[] { refA }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (6,13): error CS8917: The delegate type could not be inferred. // d = Main; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "Main").WithLocation(6, 13), // (6,13): error CS0518: Predefined type 'System.Action' is not defined or imported // d = Main; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "Main").WithArguments("System.Action").WithLocation(6, 13), // (7,13): error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type // d = () => 1; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Delegate").WithLocation(7, 13), // (7,13): error CS0518: Predefined type 'System.Func`1' is not defined or imported // d = () => 1; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "() => 1").WithArguments("System.Func`1").WithLocation(7, 13)); } private static MetadataReference GetCorlibWithInvalidActionAndFuncOfT() { var sourceA = @".assembly mscorlib { .ver 0:0:0:0 } .class public System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.ValueType extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.String extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.Type extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Void extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Boolean extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Int32 extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Delegate extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Attribute extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Runtime.CompilerServices.RequiredAttributeAttribute extends System.Attribute { .method public hidebysig specialname rtspecialname instance void .ctor(class System.Type t) cil managed { ret } } .class public abstract System.MulticastDelegate extends System.Delegate { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Action`1<T> extends System.MulticastDelegate { .custom instance void System.Runtime.CompilerServices.RequiredAttributeAttribute::.ctor(class System.Type) = ( 01 00 FF 00 00 ) .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } .method public hidebysig instance void Invoke(!T t) { ret } } .class public sealed System.Func`1<T> extends System.MulticastDelegate { .custom instance void System.Runtime.CompilerServices.RequiredAttributeAttribute::.ctor(class System.Type) = ( 01 00 FF 00 00 ) .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } .method public hidebysig instance !T Invoke() { ldnull throw } }"; return CompileIL(sourceA, prependDefaultHeader: false, autoInherit: false); } [Fact] public void SystemActionAndFunc_UseSiteErrors() { var refA = GetCorlibWithInvalidActionAndFuncOfT(); var sourceB = @"class Program { static void F(object o) { } static void Main() { System.Delegate d; d = F; d = () => 1; } }"; var comp = CreateEmptyCompilation(sourceB, new[] { refA }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (9,13): error CS0648: 'Action<T>' is a type not supported by the language // d = F; Diagnostic(ErrorCode.ERR_BogusType, "F").WithArguments("System.Action<T>").WithLocation(9, 13), // (10,13): error CS0648: 'Func<T>' is a type not supported by the language // d = () => 1; Diagnostic(ErrorCode.ERR_BogusType, "() => 1").WithArguments("System.Func<T>").WithLocation(10, 13)); } [Fact] public void SystemLinqExpressionsExpression_Missing() { var sourceA = @".assembly mscorlib { .ver 0:0:0:0 } .class public System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.ValueType extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.String extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.Type extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Void extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Boolean extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Int32 extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Delegate extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.MulticastDelegate extends System.Delegate { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Func`1<T> extends System.MulticastDelegate { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } .method public hidebysig instance !T Invoke() { ldnull throw } } .class public abstract System.Linq.Expressions.Expression extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } }"; var refA = CompileIL(sourceA, prependDefaultHeader: false, autoInherit: false); var sourceB = @"class Program { static void Main() { System.Linq.Expressions.Expression e = () => 1; } }"; var comp = CreateEmptyCompilation(sourceB, new[] { refA }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (5,48): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // System.Linq.Expressions.Expression e = () => 1; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(5, 48), // (5,48): error CS0518: Predefined type 'System.Linq.Expressions.Expression`1' is not defined or imported // System.Linq.Expressions.Expression e = () => 1; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "() => 1").WithArguments("System.Linq.Expressions.Expression`1").WithLocation(5, 48)); } [Fact] public void SystemLinqExpressionsExpression_UseSiteErrors() { var sourceA = @".assembly mscorlib { .ver 0:0:0:0 } .class public System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.ValueType extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.String extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.Type extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Void extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Boolean extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Int32 extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Delegate extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Attribute extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Runtime.CompilerServices.RequiredAttributeAttribute extends System.Attribute { .method public hidebysig specialname rtspecialname instance void .ctor(class System.Type t) cil managed { ret } } .class public abstract System.MulticastDelegate extends System.Delegate { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Func`1<T> extends System.MulticastDelegate { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } .method public hidebysig instance !T Invoke() { ldnull throw } } .class public abstract System.Linq.Expressions.Expression extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Linq.Expressions.LambdaExpression extends System.Linq.Expressions.Expression { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Linq.Expressions.Expression`1<T> extends System.Linq.Expressions.LambdaExpression { .custom instance void System.Runtime.CompilerServices.RequiredAttributeAttribute::.ctor(class System.Type) = ( 01 00 FF 00 00 ) .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } }"; var refA = CompileIL(sourceA, prependDefaultHeader: false, autoInherit: false); var sourceB = @"class Program { static void Main() { System.Linq.Expressions.Expression e = () => 1; } }"; var comp = CreateEmptyCompilation(sourceB, new[] { refA }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (5,48): error CS0648: 'Expression<T>' is a type not supported by the language // System.Linq.Expressions.Expression e = () => 1; Diagnostic(ErrorCode.ERR_BogusType, "() => 1").WithArguments("System.Linq.Expressions.Expression<T>").WithLocation(5, 48)); } // Expression<T> not derived from Expression. private static MetadataReference GetCorlibWithExpressionOfTNotDerivedType() { var sourceA = @".assembly mscorlib { .ver 0:0:0:0 } .class public System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.ValueType extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.String extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.Type extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Void extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Boolean extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Int32 extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Delegate extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.MulticastDelegate extends System.Delegate { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Func`1<T> extends System.MulticastDelegate { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } .method public hidebysig instance !T Invoke() { ldnull throw } } .class public abstract System.Linq.Expressions.Expression extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Linq.Expressions.LambdaExpression extends System.Linq.Expressions.Expression { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Linq.Expressions.Expression`1<T> extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } }"; return CompileIL(sourceA, prependDefaultHeader: false, autoInherit: false); } [Fact] public void SystemLinqExpressionsExpression_NotDerivedType_01() { var refA = GetCorlibWithExpressionOfTNotDerivedType(); var sourceB = @"class Program { static void Main() { System.Linq.Expressions.Expression e = () => 1; } }"; var comp = CreateEmptyCompilation(sourceB, new[] { refA }); comp.VerifyDiagnostics( // (5,48): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // System.Linq.Expressions.Expression e = () => 1; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(5, 48)); } [Fact] public void SystemLinqExpressionsExpression_NotDerivedType_02() { var refA = GetCorlibWithExpressionOfTNotDerivedType(); var sourceB = @"class Program { static T F<T>(T t) where T : System.Linq.Expressions.Expression => t; static void Main() { var e = F(() => 1); } }"; var comp = CreateEmptyCompilation(sourceB, new[] { refA }); comp.VerifyDiagnostics( // (6,17): error CS0311: The type 'System.Linq.Expressions.Expression<System.Func<int>>' cannot be used as type parameter 'T' in the generic type or method 'Program.F<T>(T)'. There is no implicit reference conversion from 'System.Linq.Expressions.Expression<System.Func<int>>' to 'System.Linq.Expressions.Expression'. // var e = F(() => 1); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "F").WithArguments("Program.F<T>(T)", "System.Linq.Expressions.Expression", "T", "System.Linq.Expressions.Expression<System.Func<int>>").WithLocation(6, 17)); } /// <summary> /// System.Linq.Expressions as a type rather than a namespace. /// </summary> [Fact] public void SystemLinqExpressions_IsType() { var sourceA = @"namespace System { public class Object { } public abstract class ValueType { } public class String { } public class Type { } public struct Void { } public struct Boolean { } public struct Int32 { } public struct IntPtr { } public abstract class Delegate { } public abstract class MulticastDelegate : Delegate { } public delegate T Func<T>(); } namespace System.Linq { public class Expressions { public abstract class Expression { } public abstract class LambdaExpression : Expression { } public sealed class Expression<T> : LambdaExpression { } } }"; var sourceB = @"class Program { static void Main() { System.Linq.Expressions.Expression e1 = () => 1; System.Linq.Expressions.LambdaExpression e2 = () => 2; System.Linq.Expressions.Expression<System.Func<int>> e3 = () => 3; } }"; var comp = CreateEmptyCompilation(new[] { sourceA, sourceB }); comp.VerifyDiagnostics( // (5,49): error CS1660: Cannot convert lambda expression to type 'Expressions.Expression' because it is not a delegate type // System.Linq.Expressions.Expression e1 = () => 1; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(5, 49), // (6,55): error CS1660: Cannot convert lambda expression to type 'Expressions.LambdaExpression' because it is not a delegate type // System.Linq.Expressions.LambdaExpression e2 = () => 2; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 2").WithArguments("lambda expression", "System.Linq.Expressions.LambdaExpression").WithLocation(6, 55), // (7,67): error CS1660: Cannot convert lambda expression to type 'Expressions.Expression<Func<int>>' because it is not a delegate type // System.Linq.Expressions.Expression<System.Func<int>> e3 = () => 3; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 3").WithArguments("lambda expression", "System.Linq.Expressions.Expression<System.Func<int>>").WithLocation(7, 67)); } /// <summary> /// System.Linq.Expressions as a nested namespace. /// </summary> [Fact] public void SystemLinqExpressions_IsNestedNamespace() { var sourceA = @"namespace System { public class Object { } public abstract class ValueType { } public class String { } public class Type { } public struct Void { } public struct Boolean { } public struct Int32 { } public struct IntPtr { } public abstract class Delegate { } public abstract class MulticastDelegate : Delegate { } public delegate T Func<T>(); } namespace Root.System.Linq.Expressions { public abstract class Expression { } public abstract class LambdaExpression : Expression { } public sealed class Expression<T> : LambdaExpression { } }"; var sourceB = @"using System; using Root.System.Linq.Expressions; class Program { static void Main() { Expression e1 = () => 1; LambdaExpression e2 = () => 2; Expression<Func<int>> e3 = () => 3; } }"; var comp = CreateEmptyCompilation(new[] { sourceA, sourceB }); comp.VerifyDiagnostics( // (7,25): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // Expression e1 = () => 1; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "Root.System.Linq.Expressions.Expression").WithLocation(7, 25), // (8,31): error CS1660: Cannot convert lambda expression to type 'LambdaExpression' because it is not a delegate type // LambdaExpression e2 = () => 2; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 2").WithArguments("lambda expression", "Root.System.Linq.Expressions.LambdaExpression").WithLocation(8, 31), // (9,36): error CS1660: Cannot convert lambda expression to type 'Expression<Func<int>>' because it is not a delegate type // Expression<Func<int>> e3 = () => 3; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 3").WithArguments("lambda expression", "Root.System.Linq.Expressions.Expression<System.Func<int>>").WithLocation(9, 36)); } [WorkItem(4674, "https://github.com/dotnet/csharplang/issues/4674")] [Fact] public void OverloadResolution_01() { var source = @"using System; class Program { static void M<T>(T t) { Console.WriteLine(""M<T>(T t)""); } static void M(Action<string> a) { Console.WriteLine(""M(Action<string> a)""); } static void F(object o) { } static void Main() { M(F); // C#9: M(Action<string>) } }"; var expectedOutput = "M(Action<string> a)"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [WorkItem(4674, "https://github.com/dotnet/csharplang/issues/4674")] [Fact] public void OverloadResolution_02() { var source = @"using System; class Program { static void Main() { var c = new C(); c.M(Main); // C#9: E.M(object x, Action y) c.M(() => { }); // C#9: E.M(object x, Action y) } } class C { public void M(object y) { Console.WriteLine(""C.M(object y)""); } } static class E { public static void M(this object x, Action y) { Console.WriteLine(""E.M(object x, Action y)""); } }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: @"E.M(object x, Action y) E.M(object x, Action y) "); // Breaking change from C#9 which binds to E.M(object x, Action y). CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, expectedOutput: @"C.M(object y) C.M(object y) "); } [WorkItem(4674, "https://github.com/dotnet/csharplang/issues/4674")] [Fact] public void OverloadResolution_03() { var source = @"using System; class Program { static void Main() { var c = new C(); c.M(Main); // C#9: E.M(object x, Action y) c.M(() => { }); // C#9: E.M(object x, Action y) } } class C { public void M(Delegate d) { Console.WriteLine(""C.M""); } } static class E { public static void M(this object o, Action a) { Console.WriteLine(""E.M""); } }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: @"E.M E.M "); // Breaking change from C#9 which binds to E.M. CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: @"C.M C.M "); } [WorkItem(4674, "https://github.com/dotnet/csharplang/issues/4674")] [Fact] public void OverloadResolution_04() { var source = @"using System; using System.Linq.Expressions; class Program { static void Main() { var c = new C(); c.M(() => 1); } } class C { public void M(Expression e) { Console.WriteLine(""C.M""); } } static class E { public static void M(this object o, Func<int> a) { Console.WriteLine(""E.M""); } }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: @"E.M"); // Breaking change from C#9 which binds to E.M. CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: @"C.M"); } [Fact] public void OverloadResolution_05() { var source = @"using System; class Program { static void Report(string name) { Console.WriteLine(name); } static void FA(Delegate d) { Report(""FA(Delegate)""); } static void FA(Action d) { Report(""FA(Action)""); } static void FB(Delegate d) { Report(""FB(Delegate)""); } static void FB(Func<int> d) { Report(""FB(Func<int>)""); } static void F1() { } static int F2() => 0; static void Main() { FA(F1); FA(F2); FB(F1); FB(F2); FA(() => { }); FA(() => 0); FB(() => { }); FB(() => 0); FA(delegate () { }); FA(delegate () { return 0; }); FB(delegate () { }); FB(delegate () { return 0; }); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (14,12): error CS1503: Argument 1: cannot convert from 'method group' to 'Delegate' // FA(F2); Diagnostic(ErrorCode.ERR_BadArgType, "F2").WithArguments("1", "method group", "System.Delegate").WithLocation(14, 12), // (15,12): error CS1503: Argument 1: cannot convert from 'method group' to 'Delegate' // FB(F1); Diagnostic(ErrorCode.ERR_BadArgType, "F1").WithArguments("1", "method group", "System.Delegate").WithLocation(15, 12), // (18,18): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // FA(() => 0); Diagnostic(ErrorCode.ERR_IllegalStatement, "0").WithLocation(18, 18), // (19,15): error CS1643: Not all code paths return a value in lambda expression of type 'Func<int>' // FB(() => { }); Diagnostic(ErrorCode.ERR_AnonymousReturnExpected, "=>").WithArguments("lambda expression", "System.Func<int>").WithLocation(19, 15), // (22,26): error CS8030: Anonymous function converted to a void returning delegate cannot return a value // FA(delegate () { return 0; }); Diagnostic(ErrorCode.ERR_RetNoObjectRequiredLambda, "return").WithLocation(22, 26), // (23,12): error CS1643: Not all code paths return a value in anonymous method of type 'Func<int>' // FB(delegate () { }); Diagnostic(ErrorCode.ERR_AnonymousReturnExpected, "delegate").WithArguments("anonymous method", "System.Func<int>").WithLocation(23, 12)); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: @"FA(Action) FA(Delegate) FB(Delegate) FB(Func<int>) FA(Action) FA(Delegate) FB(Delegate) FB(Func<int>) FA(Action) FA(Delegate) FB(Delegate) FB(Func<int>) "); } [Fact] public void OverloadResolution_06() { var source = @"using System; using System.Linq.Expressions; class Program { static void Report(string name, Expression e) { Console.WriteLine(""{0}: {1}"", name, e); } static void F(Expression e) { Report(""F(Expression)"", e); } static void F(Expression<Func<int>> e) { Report(""F(Expression<Func<int>>)"", e); } static void Main() { F(() => 0); F(() => string.Empty); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (11,17): error CS0029: Cannot implicitly convert type 'string' to 'int' // F(() => string.Empty); Diagnostic(ErrorCode.ERR_NoImplicitConv, "string.Empty").WithArguments("string", "int").WithLocation(11, 17), // (11,17): error CS1662: Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type // F(() => string.Empty); Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, "string.Empty").WithArguments("lambda expression").WithLocation(11, 17)); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: @"F(Expression<Func<int>>): () => 0 F(Expression): () => String.Empty "); } [Fact] public void OverloadResolution_07() { var source = @"using System; using System.Linq.Expressions; class Program { static void F(Expression e) { } static void F(Expression<Func<int>> e) { } static void Main() { F(delegate () { return 0; }); F(delegate () { return string.Empty; }); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,11): error CS1660: Cannot convert anonymous method to type 'Expression' because it is not a delegate type // F(delegate () { return 0; }); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate () { return 0; }").WithArguments("anonymous method", "System.Linq.Expressions.Expression").WithLocation(9, 11), // (10,11): error CS1660: Cannot convert anonymous method to type 'Expression' because it is not a delegate type // F(delegate () { return string.Empty; }); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate () { return string.Empty; }").WithArguments("anonymous method", "System.Linq.Expressions.Expression").WithLocation(10, 11)); comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics( // (9,11): error CS1946: An anonymous method expression cannot be converted to an expression tree // F(delegate () { return 0; }); Diagnostic(ErrorCode.ERR_AnonymousMethodToExpressionTree, "delegate () { return 0; }").WithLocation(9, 11), // (10,11): error CS1946: An anonymous method expression cannot be converted to an expression tree // F(delegate () { return string.Empty; }); Diagnostic(ErrorCode.ERR_AnonymousMethodToExpressionTree, "delegate () { return string.Empty; }").WithLocation(10, 11)); } [WorkItem(55319, "https://github.com/dotnet/roslyn/issues/55319")] [Fact] public void OverloadResolution_08() { var source = @"using System; using static System.Console; class C { static void Main() { var c = new C(); c.F(x => x); c.F((int x) => x); } void F(Delegate d) => Write(""instance, ""); } static class Extensions { public static void F(this C c, Func<int, int> f) => Write(""extension, ""); }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: "extension, extension, "); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: "extension, instance, "); CompileAndVerify(source, expectedOutput: "extension, instance, "); } [WorkItem(55319, "https://github.com/dotnet/roslyn/issues/55319")] [Fact] public void OverloadResolution_09() { var source = @"using System; using System.Linq.Expressions; using static System.Console; class C { static void Main() { var c = new C(); c.F(x => x); c.F((int x) => x); } void F(Expression e) => Write(""instance, ""); } static class Extensions { public static void F(this C c, Expression<Func<int, int>> e) => Write(""extension, ""); }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: "extension, extension, "); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: "extension, instance, "); CompileAndVerify(source, expectedOutput: "extension, instance, "); } [WorkItem(55319, "https://github.com/dotnet/roslyn/issues/55319")] [Fact] public void OverloadResolution_10() { var source = @"using System; using static System.Console; class C { static object M1(object o) => o; static int M1(int i) => i; static int M2(int i) => i; static void Main() { var c = new C(); c.F(M1); c.F(M2); } void F(Delegate d) => Write(""instance, ""); } static class Extensions { public static void F(this C c, Func<int, int> f) => Write(""extension, ""); }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: "extension, extension, "); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: "extension, instance, "); CompileAndVerify(source, expectedOutput: "extension, instance, "); } [Fact] public void OverloadResolution_11() { var source = @"using System; using System.Linq.Expressions; class C { static object M1(object o) => o; static int M1(int i) => i; static void Main() { F1(x => x); F1(M1); F2(x => x); } static void F1(Delegate d) { } static void F2(Expression e) { } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,12): error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type // F1(x => x); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "x => x").WithArguments("lambda expression", "System.Delegate").WithLocation(9, 12), // (10,12): error CS1503: Argument 1: cannot convert from 'method group' to 'Delegate' // F1(M1); Diagnostic(ErrorCode.ERR_BadArgType, "M1").WithArguments("1", "method group", "System.Delegate").WithLocation(10, 12), // (11,12): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // F2(x => x); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "x => x").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(11, 12)); var expectedDiagnostics10AndLater = new[] { // (9,12): error CS8917: The delegate type could not be inferred. // F1(x => x); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(9, 12), // (10,12): error CS1503: Argument 1: cannot convert from 'method group' to 'Delegate' // F1(M1); Diagnostic(ErrorCode.ERR_BadArgType, "M1").WithArguments("1", "method group", "System.Delegate").WithLocation(10, 12), // (11,12): error CS8917: The delegate type could not be inferred. // F2(x => x); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(11, 12) }; comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics10AndLater); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics10AndLater); } [WorkItem(55691, "https://github.com/dotnet/roslyn/issues/55691")] [Fact] public void OverloadResolution_12() { var source = @"using System; #nullable enable var app = new WebApp(); app.Map(""/sub1"", builder => { builder.UseAuth(); }); app.Map(""/sub2"", (IAppBuilder builder) => { builder.UseAuth(); }); class WebApp : IAppBuilder, IRouteBuilder { public void UseAuth() { } } interface IAppBuilder { void UseAuth(); } interface IRouteBuilder { } static class AppBuilderExtensions { public static IAppBuilder Map(this IAppBuilder app, PathSring path, Action<IAppBuilder> callback) { Console.WriteLine(""AppBuilderExtensions.Map(this IAppBuilder app, PathSring path, Action<IAppBuilder> callback)""); return app; } } static class RouteBuilderExtensions { public static IRouteBuilder Map(this IRouteBuilder routes, string path, Delegate callback) { Console.WriteLine(""RouteBuilderExtensions.Map(this IRouteBuilder routes, string path, Delegate callback)""); return routes; } } struct PathSring { public PathSring(string? path) { Path = path; } public string? Path { get; } public static implicit operator PathSring(string? s) => new PathSring(s); public static implicit operator string?(PathSring path) => path.Path; }"; var expectedOutput = @"AppBuilderExtensions.Map(this IAppBuilder app, PathSring path, Action<IAppBuilder> callback) AppBuilderExtensions.Map(this IAppBuilder app, PathSring path, Action<IAppBuilder> callback) "; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [WorkItem(55691, "https://github.com/dotnet/roslyn/issues/55691")] [Fact] public void OverloadResolution_13() { var source = @"using System; class Program { static void Main() { F(1, () => { }); F(2, Main); } static void F(object obj, Action a) { Console.WriteLine(""F(object obj, Action a)""); } static void F(int i, Delegate d) { Console.WriteLine(""F(int i, Delegate d)""); } }"; var expectedOutput = @"F(object obj, Action a) F(object obj, Action a) "; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [WorkItem(55691, "https://github.com/dotnet/roslyn/issues/55691")] [Fact] public void OverloadResolution_14() { var source = @"using System; using System.Linq.Expressions; class Program { static void Main() { F(() => 1, 2); } static void F(Expression<Func<object>> f, object obj) { Console.WriteLine(""F(Expression<Func<object>> f, object obj)""); } static void F(Expression e, int i) { Console.WriteLine(""F(Expression e, int i)""); } }"; var expectedOutput = @"F(Expression<Func<object>> f, object obj)"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [WorkItem(4674, "https://github.com/dotnet/csharplang/issues/4674")] [Fact] public void OverloadResolution_15() { var source = @"using System; delegate void StringAction(string arg); class Program { static void F<T>(T t) { Console.WriteLine(typeof(T).Name); } static void F(StringAction a) { Console.WriteLine(""StringAction""); } static void M(string arg) { } static void Main() { F((string s) => { }); // C#9: F(StringAction) F(M); // C#9: F(StringAction) } }"; var expectedOutput = @"StringAction StringAction "; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void OverloadResolution_16() { var source = @"using System; class Program { static void F(Func<Func<object>> f, int i) => Report(f); static void F(Func<Func<int>> f, object o) => Report(f); static void Main() { F(() => () => 1, 2); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: @"System.Func`1[System.Func`1[System.Object]]"); // Breaking change from C#9 which binds calls to F(Func<Func<object>>, int). var expectedDiagnostics = new[] { // (8,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.F(Func<Func<object>>, int)' and 'Program.F(Func<Func<int>>, object)' // F(() => () => 1, 2); Diagnostic(ErrorCode.ERR_AmbigCall, "F").WithArguments("Program.F(System.Func<System.Func<object>>, int)", "Program.F(System.Func<System.Func<int>>, object)").WithLocation(8, 9) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void OverloadResolution_17() { var source = @"delegate void StringAction(string arg); class Program { static void F<T>(System.Action<T> a) { } static void F(StringAction a) { } static void Main() { F((string s) => { }); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.F<T>(Action<T>)' and 'Program.F(StringAction)' // F((string s) => { }); Diagnostic(ErrorCode.ERR_AmbigCall, "F").WithArguments("Program.F<T>(System.Action<T>)", "Program.F(StringAction)").WithLocation(8, 9)); } [Fact] public void OverloadResolution_18() { var source = @"delegate void StringAction(string arg); class Program { static void F0<T>(System.Action<T> a) { } static void F1<T>(System.Action<T> a) { } static void F1(StringAction a) { } static void M(string arg) { } static void Main() { F0(M); F1(M); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,9): error CS0411: The type arguments for method 'Program.F0<T>(Action<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F0(M); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F0").WithArguments("Program.F0<T>(System.Action<T>)").WithLocation(10, 9)); } [Fact] public void OverloadResolution_19() { var source = @"delegate void MyAction<T>(T arg); class Program { static void F<T>(System.Action<T> a) { } static void F<T>(MyAction<T> a) { } static void M(string arg) { } static void Main() { F((string s) => { }); F(M); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.F<T>(Action<T>)' and 'Program.F<T>(MyAction<T>)' // F((string s) => { }); Diagnostic(ErrorCode.ERR_AmbigCall, "F").WithArguments("Program.F<T>(System.Action<T>)", "Program.F<T>(MyAction<T>)").WithLocation(9, 9), // (10,9): error CS0411: The type arguments for method 'Program.F<T>(Action<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F(M); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("Program.F<T>(System.Action<T>)").WithLocation(10, 9)); } [Fact] public void OverloadResolution_20() { var source = @"using System; delegate void StringAction(string s); class Program { static void F(Action<string> a) { } static void F(StringAction a) { } static void M(string s) { } static void Main() { F(M); F((string s) => { }); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.F(Action<string>)' and 'Program.F(StringAction)' // F(M); Diagnostic(ErrorCode.ERR_AmbigCall, "F").WithArguments("Program.F(System.Action<string>)", "Program.F(StringAction)").WithLocation(10, 9), // (11,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.F(Action<string>)' and 'Program.F(StringAction)' // F((string s) => { }); Diagnostic(ErrorCode.ERR_AmbigCall, "F").WithArguments("Program.F(System.Action<string>)", "Program.F(StringAction)").WithLocation(11, 9)); } [Fact] public void OverloadResolution_21() { var source = @"using System; class C<T> { public void F(Delegate d) => Report(""F(Delegate d)"", d); public void F(T t) => Report(""F(T t)"", t); public void F(Func<T> f) => Report(""F(Func<T> f)"", f); static void Report(string method, object arg) => Console.WriteLine(""{0}, {1}"", method, arg.GetType()); } class Program { static void Main() { var c = new C<Delegate>(); c.F(() => (Action)null); } }"; string expectedOutput = "F(Func<T> f), System.Func`1[System.Delegate]"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [WorkItem(1361172, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1361172")] [Fact] public void OverloadResolution_22() { var source = @"using System; using System.Linq.Expressions; class C<T> { public void F(Delegate d) => Report(""F(Delegate d)"", d); public void F(T t) => Report(""F(T t)"", t); public void F(Func<T> f) => Report(""F(Func<T> f)"", f); static void Report(string method, object arg) => Console.WriteLine(""{0}, {1}"", method, arg.GetType()); } class Program { static void Main() { var c = new C<Expression>(); c.F(() => Expression.Constant(1)); } }"; string expectedOutput = "F(Func<T> f), System.Func`1[System.Linq.Expressions.Expression]"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void OverloadResolution_23() { var source = @"using System; class Program { static void F(Delegate d) => Console.WriteLine(""F(Delegate d)""); static void F(Func<object> f) => Console.WriteLine(""F(Func<int> f)""); static void Main() { F(() => 1); } }"; string expectedOutput = "F(Func<int> f)"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [WorkItem(1361172, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1361172")] [Fact] public void OverloadResolution_24() { var source = @"using System; using System.Linq.Expressions; class Program { static void F(Expression e) => Console.WriteLine(""F(Expression e)""); static void F(Func<Expression> f) => Console.WriteLine(""F(Func<Expression> f)""); static void Main() { F(() => Expression.Constant(1)); } }"; string expectedOutput = "F(Func<Expression> f)"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [WorkItem(56167, "https://github.com/dotnet/roslyn/issues/56167")] [Fact] public void OverloadResolution_25() { var source = @"using static System.Console; delegate void D(); class Program { static void F(D d) => WriteLine(""D""); static void F<T>(T t) => WriteLine(typeof(T).Name); static void Main() { F(() => { }); } }"; string expectedOutput = "D"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [WorkItem(56167, "https://github.com/dotnet/roslyn/issues/56167")] [Fact] public void OverloadResolution_26() { var source = @"using System; class Program { static void F(Action action) => Console.WriteLine(""Action""); static void F<T>(T t) => Console.WriteLine(typeof(T).Name); static void Main() { int i = 0; F(() => i++); } }"; string expectedOutput = "Action"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [WorkItem(56167, "https://github.com/dotnet/roslyn/issues/56167")] [Fact] public void OverloadResolution_27() { var source = @"using System; using System.Linq.Expressions; class Program { static void F(Action action) => Console.WriteLine(""Action""); static void F(Expression expression) => Console.WriteLine(""Expression""); static int GetValue() => 0; static void Main() { F(() => GetValue()); } }"; string expectedOutput = "Action"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [WorkItem(56319, "https://github.com/dotnet/roslyn/issues/56319")] [Fact] public void OverloadResolution_28() { var source = @"using System; var source = new C<int>(); source.Aggregate(() => 0, (i, j) => i, (i, j) => i, i => i); class C<T> { } static class Extensions { public static TResult Aggregate<TSource, TAccumulate, TResult>( this C<TSource> source, Func<TAccumulate> seedFactory, Func<TAccumulate, TSource, TAccumulate> updateAccumulatorFunc, Func<TAccumulate, TAccumulate, TAccumulate> combineAccumulatorsFunc, Func<TAccumulate, TResult> resultSelector) { Console.WriteLine((typeof(TSource).FullName, typeof(TAccumulate).FullName, typeof(TResult).FullName)); return default; } public static TResult Aggregate<TSource, TAccumulate, TResult>( this C<TSource> source, TAccumulate seed, Func<TAccumulate, TSource, TAccumulate> updateAccumulatorFunc, Func<TAccumulate, TAccumulate, TAccumulate> combineAccumulatorsFunc, Func<TAccumulate, TResult> resultSelector) { Console.WriteLine((typeof(TSource).FullName, typeof(TAccumulate).FullName, typeof(TResult).FullName)); return default; } }"; string expectedOutput = "(System.Int32, System.Int32, System.Int32)"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void OverloadResolution_29() { var source = @"using System; class A { } class B : A { } class Program { static void M<T>(T x, T y) { Console.WriteLine(""M<T>(T x, T y)""); } static void M(Func<object> x, Func<object> y) { Console.WriteLine(""M(Func<object> x, Func<object> y)""); } static void Main() { Func<object> fo = () => new A(); Func<A> fa = () => new A(); M(() => new A(), () => new B()); M(fo, () => new B()); M(fa, () => new B()); } }"; var expectedOutput = @"M(Func<object> x, Func<object> y) M(Func<object> x, Func<object> y) M<T>(T x, T y) "; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void OverloadResolution_30() { var source = @"using System; class Program { static void M<T>(T t, Func<object> f) { Console.WriteLine(""M<T>(T t, Func<object> f)""); } static void M<T>(Func<object> f, T t) { Console.WriteLine(""M<T>(Func<object> f, T t)""); } static object F() => null; static void Main() { M(F, F); M(() => 1, () => 2); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,9): error CS0411: The type arguments for method 'Program.M<T>(T, Func<object>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // M(F, F); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T>(T, System.Func<object>)").WithLocation(9, 9), // (10,9): error CS0411: The type arguments for method 'Program.M<T>(T, Func<object>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // M(() => 1, () => 2); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T>(T, System.Func<object>)").WithLocation(10, 9)); var expectedDiagnostics = new[] { // (9,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M<T>(T, Func<object>)' and 'Program.M<T>(Func<object>, T)' // M(F, F); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M<T>(T, System.Func<object>)", "Program.M<T>(System.Func<object>, T)").WithLocation(9, 9), // (10,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M<T>(T, Func<object>)' and 'Program.M<T>(Func<object>, T)' // M(() => 1, () => 2); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M<T>(T, System.Func<object>)", "Program.M<T>(System.Func<object>, T)").WithLocation(10, 9) }; comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void OverloadResolution_31() { var source = @"using System; using System.Linq.Expressions; class Program { static void M<T>(T t) { Console.WriteLine(""M<T>(T t)""); } static void M(Expression<Func<object>> e) { Console.WriteLine(""M(Expression<Func<object>> e)""); } static void Main() { M(() => string.Empty); } }"; var expectedOutput = "M(Expression<Func<object>> e)"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void OverloadResolution_32() { var source = @"using System; using System.Linq.Expressions; class A { } class B : A { } class Program { static void M<T>(T x, T y) { Console.WriteLine(""M<T>(T x, T y)""); } static void M(Expression<Func<object>> x, Expression<Func<object>> y) { Console.WriteLine(""M(Expression<Func<object>> x, Expression<Func<object>> y)""); } static void Main() { Expression<Func<object>> fo = () => new A(); Expression<Func<A>> fa = () => new A(); M(() => new A(), () => new B()); M(fo, () => new B()); M(fa, () => new B()); } }"; var expectedOutput = @"M(Expression<Func<object>> x, Expression<Func<object>> y) M(Expression<Func<object>> x, Expression<Func<object>> y) M<T>(T x, T y) "; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void OverloadResolution_33() { var source = @"using System; class Program { static void M<T>(object x, T y) { Console.WriteLine(""M<T>(object x, T y)""); } static void M<T, U>(T x, U y) { Console.WriteLine(""M<T, U>(T x, U y)""); } static void Main() { Func<int> f = () => 0; M(() => 1, () => 2); M(() => 1, f); M(f, () => 2); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,9): error CS0411: The type arguments for method 'Program.M<T>(object, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // M(() => 1, () => 2); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T>(object, T)").WithLocation(9, 9), // (10,11): error CS1660: Cannot convert lambda expression to type 'object' because it is not a delegate type // M(() => 1, f); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "object").WithLocation(10, 11), // (11,9): error CS0411: The type arguments for method 'Program.M<T>(object, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // M(f, () => 2); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T>(object, T)").WithLocation(11, 9)); var expectedOutput = @"M<T, U>(T x, U y) M<T, U>(T x, U y) M<T, U>(T x, U y) "; CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void OverloadResolution_34() { var source = @"using System; class Program { static void M<T, U>(Func<T> x, U y) { Console.WriteLine(""M<T, U>(Func<T> x, U y)""); } static void M<T, U>(T x, U y) { Console.WriteLine(""M<T, U>(T x, U y)""); } static void Main() { Func<int> f = () => 0; M(() => 1, () => 2); M(() => 1, f); M(f, () => 2); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,9): error CS0411: The type arguments for method 'Program.M<T, U>(Func<T>, U)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // M(() => 1, () => 2); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T, U>(System.Func<T>, U)").WithLocation(9, 9), // (11,9): error CS0411: The type arguments for method 'Program.M<T, U>(Func<T>, U)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // M(f, () => 2); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T, U>(System.Func<T>, U)").WithLocation(11, 9)); var expectedOutput = @"M<T, U>(Func<T> x, U y) M<T, U>(Func<T> x, U y) M<T, U>(Func<T> x, U y) "; CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void OverloadResolution_35() { var source = @"using System; class Program { static void M(Delegate x, Func<int> y) { Console.WriteLine(""M(Delegate x, Func<int> y)""); } static void M<T, U>(T x, U y) { Console.WriteLine(""M<T, U>(T x, U y)""); } static void Main() { Func<int> f = () => 0; M(() => 1, () => 2); M(() => 1, f); M(f, () => 2); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,11): error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type // M(() => 1, () => 2); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Delegate").WithLocation(9, 11), // (10,11): error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type // M(() => 1, f); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Delegate").WithLocation(10, 11)); var expectedOutput = @"M<T, U>(T x, U y) M<T, U>(T x, U y) M(Delegate x, Func<int> y) "; CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void OverloadResolution_36() { var source = @"using System; class Program { static void F<T>(T t) { Console.WriteLine(""F<{0}>({0} t)"", typeof(T).Name); } static void F(Delegate d) { Console.WriteLine(""F(Delegate d)""); } static void Main() { F(Main); F(() => 1); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,11): error CS1503: Argument 1: cannot convert from 'method group' to 'Delegate' // F(Main); Diagnostic(ErrorCode.ERR_BadArgType, "Main").WithArguments("1", "method group", "System.Delegate").WithLocation(8, 11), // (9,11): error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type // F(() => 1); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Delegate").WithLocation(9, 11)); var expectedOutput = @"F<Action>(Action t) F<Func`1>(Func`1 t)"; CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void OverloadResolution_37() { var source = @"using System; class Program { static void F(object o) { Console.WriteLine(""F(object o)""); } static void F(Delegate d) { Console.WriteLine(""F(Delegate d)""); } static void Main() { F(Main); F(() => 1); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,11): error CS1503: Argument 1: cannot convert from 'method group' to 'object' // F(Main); Diagnostic(ErrorCode.ERR_BadArgType, "Main").WithArguments("1", "method group", "object").WithLocation(8, 11), // (9,11): error CS1660: Cannot convert lambda expression to type 'object' because it is not a delegate type // F(() => 1); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "object").WithLocation(9, 11)); var expectedOutput = @"F(Delegate d) F(Delegate d)"; CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void OverloadResolution_38() { var source = @"using System; class MyString { public static implicit operator MyString(string s) => new MyString(); } class Program { static void F(Delegate d1, Delegate d2, string s) { Console.WriteLine(""F(Delegate d1, Delegate d2, string s)""); } static void F(Func<int> f, Delegate d, MyString s) { Console.WriteLine(""F(Func<int> f, Delegate d, MyString s)""); } static void Main() { F(() => 1, () => 2, string.Empty); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (12,11): error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type // F(() => 1, () => 2, string.Empty); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Delegate").WithLocation(12, 11), // (12,20): error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type // F(() => 1, () => 2, string.Empty); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 2").WithArguments("lambda expression", "System.Delegate").WithLocation(12, 20)); var expectedDiagnostics = new[] { // (12,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.F(Delegate, Delegate, string)' and 'Program.F(Func<int>, Delegate, MyString)' // F(() => 1, () => 2, string.Empty); Diagnostic(ErrorCode.ERR_AmbigCall, "F").WithArguments("Program.F(System.Delegate, System.Delegate, string)", "Program.F(System.Func<int>, System.Delegate, MyString)").WithLocation(12, 9) }; comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void OverloadResolution_39() { var source = @"using System; using System.Linq.Expressions; class C { static void M(Expression e) { Console.WriteLine(""M(Expression e)""); } static void M(object o) { Console.WriteLine(""M(object o)""); } static int F() => 0; static void Main() { M(F); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (10,11): error CS1503: Argument 1: cannot convert from 'method group' to 'Expression' // M(F); Diagnostic(ErrorCode.ERR_BadArgType, "F").WithArguments("1", "method group", "System.Linq.Expressions.Expression").WithLocation(10, 11)); var expectedDiagnostics = new[] { // (10,11): error CS0428: Cannot convert method group 'F' to non-delegate type 'Expression'. Did you intend to invoke the method? // M(F); Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "System.Linq.Expressions.Expression").WithLocation(10, 11) }; comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void OverloadResolution_40() { var source = @"using System; using System.Linq.Expressions; class C { static void M(Expression e) { Console.WriteLine(""M(Expression e)""); } static void M(object o) { Console.WriteLine(""M(object o)""); } static void Main() { M(() => 1); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,11): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // M(() => 1); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(9, 11)); var expectedOutput = @"M(Expression e)"; CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void OverloadResolution_41() { var source = @"using System; using System.Linq.Expressions; class C { static void M(Expression e) { Console.WriteLine(""M(Expression e)""); } static void M(Delegate d) { Console.WriteLine(""M(Delegate d)""); } static int F() => 0; static void Main() { M(F); M(() => 1); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (10,11): error CS1503: Argument 1: cannot convert from 'method group' to 'Expression' // M(F); Diagnostic(ErrorCode.ERR_BadArgType, "F").WithArguments("1", "method group", "System.Linq.Expressions.Expression").WithLocation(10, 11), // (11,11): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // M(() => 1); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(11, 11)); var expectedDiagnostics = new[] { // (10,9): error CS0121: The call is ambiguous between the following methods or properties: 'C.M(Expression)' and 'C.M(Delegate)' // M(F); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C.M(System.Linq.Expressions.Expression)", "C.M(System.Delegate)").WithLocation(10, 9), // (11,9): error CS0121: The call is ambiguous between the following methods or properties: 'C.M(Expression)' and 'C.M(Delegate)' // M(() => 1); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C.M(System.Linq.Expressions.Expression)", "C.M(System.Delegate)").WithLocation(11, 9) }; comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void OverloadResolution_42() { var source = @"using System; using System.Runtime.InteropServices; [ComImport] [Guid(""96A2DE64-6D44-4DA5-BBA4-25F5F07E0E6B"")] interface I { void F(Delegate d, short s); void F(Action a, ref int i); } class C : I { void I.F(Delegate d, short s) => Console.WriteLine(""I.F(Delegate d, short s)""); void I.F(Action a, ref int i) => Console.WriteLine(""I.F(Action a, ref int i)""); } class Program { static void M(I i) { i.F(() => { }, 1); } static void Main() { M(new C()); } }"; var expectedOutput = @"I.F(Action a, ref int i)"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [WorkItem(4674, "https://github.com/dotnet/csharplang/issues/4674")] [Fact] public void OverloadResolution_43() { var source = @"using System; using System.Linq.Expressions; class Program { static int F() => 0; static void Main() { var c = new C(); c.M(F); } } class C { public void M(Expression e) { Console.WriteLine(""C.M""); } } static class E { public static void M(this object o, Func<int> a) { Console.WriteLine(""E.M""); } }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: @"E.M"); var expectedDiagnostics = new[] { // (9,13): error CS0428: Cannot convert method group 'F' to non-delegate type 'Expression'. Did you intend to invoke the method? // c.M(F); Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "System.Linq.Expressions.Expression").WithLocation(9, 13) }; // Breaking change from C#9 which binds to E.M. var comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void OverloadResolution_44() { var source = @"using System; using System.Linq.Expressions; class A { public static void F1(Func<int> f) { Console.WriteLine(""A.F1(Func<int> f)""); } public void F2(Func<int> f) { Console.WriteLine(""A.F2(Func<int> f)""); } } class B : A { public static void F1(Delegate d) { Console.WriteLine(""B.F1(Delegate d)""); } public void F2(Expression e) { Console.WriteLine(""B.F2(Expression e)""); } } class Program { static void Main() { B.F1(() => 1); var b = new B(); b.F2(() => 2); } }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: @"A.F1(Func<int> f) A.F2(Func<int> f)"); // Breaking change from C#9 which binds to methods from A. var expectedOutput = @"B.F1(Delegate d) B.F2(Expression e)"; CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void OverloadResolution_45() { var source = @"using System; using System.Linq.Expressions; class A { public object this[Func<int> f] => Report(""A.this[Func<int> f]""); public static object Report(string message) { Console.WriteLine(message); return null; } } class B1 : A { public object this[Delegate d] => Report(""B1.this[Delegate d]""); } class B2 : A { public object this[Expression e] => Report(""B2.this[Expression e]""); } class Program { static void Main() { var b1 = new B1(); _ = b1[() => 1]; var b2 = new B2(); _ = b2[() => 2]; } }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: @"A.this[Func<int> f] A.this[Func<int> f]"); // Breaking change from C#9 which binds to methods from A. var expectedOutput = @"B1.this[Delegate d] B2.this[Expression e]"; CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void BestCommonType_01() { var source = @"using System; delegate int StringIntDelegate(string s); class Program { static int M(string s) => s.Length; static void Main() { StringIntDelegate d = M; var a1 = new[] { d, (string s) => int.Parse(s) }; var a2 = new[] { (string s) => int.Parse(s), d }; Report(a1[1]); Report(a2[0]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; string expectedOutput = @"StringIntDelegate StringIntDelegate"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); } [Fact] public void BestCommonType_02() { var source = @"using System; delegate int StringIntDelegate(string s); class Program { static int M(string s) => s.Length; static void F(bool b) { StringIntDelegate d = M; var c1 = b ? d : ((string s) => int.Parse(s)); var c2 = b ? ((string s) => int.Parse(s)) : d; Report(c1); Report(c2); } static void Main() { F(false); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; string expectedOutput = @"StringIntDelegate StringIntDelegate"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); } [Fact] public void BestCommonType_03() { var source = @"using System; delegate int StringIntDelegate(string s); class Program { static int M(string s) => s.Length; static void Main() { var f1 = (bool b) => { if (b) return (StringIntDelegate)M; return ((string s) => int.Parse(s)); }; var f2 = (bool b) => { if (b) return ((string s) => int.Parse(s)); return (StringIntDelegate)M; }; Report(f1(true)); Report(f2(true)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"StringIntDelegate StringIntDelegate"); } [Fact] public void BestCommonType_04() { var source = @"using System; delegate int StringIntDelegate(string s); class Program { static int M(string s) => s.Length; static void Main() { var f1 = (bool b) => { if (b) return M; return ((string s) => int.Parse(s)); }; var f2 = (bool b) => { if (b) return ((string s) => int.Parse(s)); return M; }; Report(f1(true)); Report(f2(true)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Func`2[System.String,System.Int32] System.Func`2[System.String,System.Int32]"); } [Fact] public void BestCommonType_05() { var source = @"using System; class Program { static int M1(string s) => s.Length; static int M2(string s) => int.Parse(s); static void Main() { var a1 = new[] { M1, (string s) => int.Parse(s) }; var a2 = new[] { (string s) => s.Length, M2 }; Report(a1[1]); Report(a2[1]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { M1, (string s) => int.Parse(s) }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { M1, (string s) => int.Parse(s) }").WithLocation(8, 18), // (9,18): error CS0826: No best type found for implicitly-typed array // var a2 = new[] { (string s) => s.Length, M2 }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { (string s) => s.Length, M2 }").WithLocation(9, 18)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Func`2[System.String,System.Int32] System.Func`2[System.String,System.Int32]"); } [Fact] public void BestCommonType_06() { var source = @"using System; class Program { static void F1<T>(T t) { } static T F2<T>() => default; static void Main() { var a1 = new[] { F1<object>, F1<string> }; var a2 = new[] { F2<object>, F2<string> }; Report(a1[0]); Report(a2[0]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { F1<object>, F1<string> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F1<object>, F1<string> }").WithLocation(8, 18), // (9,18): error CS0826: No best type found for implicitly-typed array // var a2 = new[] { F2<object>, F2<string> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F2<object>, F2<string> }").WithLocation(9, 18)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Action`1[System.String] System.Func`1[System.Object]"); } [Fact] public void BestCommonType_07() { var source = @"class Program { static void F1<T>(T t) { } static T F2<T>() => default; static T F3<T>(T t) => t; static void Main() { var a1 = new[] { F1<int>, F1<object> }; var a2 = new[] { F2<nint>, F2<System.IntPtr> }; var a3 = new[] { F3<string>, F3<object> }; } }"; var expectedDiagnostics = new[] { // (8,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { F1<int>, F1<object> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F1<int>, F1<object> }").WithLocation(8, 18), // (9,18): error CS0826: No best type found for implicitly-typed array // var a2 = new[] { F2<nint>, F2<System.IntPtr> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F2<nint>, F2<System.IntPtr> }").WithLocation(9, 18), // (10,18): error CS0826: No best type found for implicitly-typed array // var a3 = new[] { F3<string>, F3<object> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F3<string>, F3<object> }").WithLocation(10, 18) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void BestCommonType_08() { var source = @"#nullable enable using System; class Program { static void F<T>(T t) { } static void Main() { var a1 = new[] { F<string?>, F<string> }; var a2 = new[] { F<(int X, object Y)>, F<(int, dynamic)> }; Report(a1[0]); Report(a2[0]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { F<string?>, F<string> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F<string?>, F<string> }").WithLocation(8, 18), // (9,18): error CS0826: No best type found for implicitly-typed array // var a2 = new[] { F<(int X, object Y)>, F<(int, dynamic)> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F<(int X, object Y)>, F<(int, dynamic)> }").WithLocation(9, 18)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Action`1[System.String] System.Action`1[System.ValueTuple`2[System.Int32,System.Object]]"); } [Fact] public void BestCommonType_09() { var source = @"using System; class Program { static void Main() { var a1 = new[] { (object o) => { }, (string s) => { } }; var a2 = new[] { () => (object)null, () => (string)null }; Report(a1[0]); Report(a2[0]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { (object o) => { }, (string s) => { } }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { (object o) => { }, (string s) => { } }").WithLocation(6, 18), // (7,18): error CS0826: No best type found for implicitly-typed array // var a2 = new[] { () => (object)null, () => (string)null }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { () => (object)null, () => (string)null }").WithLocation(7, 18)); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,26): error CS1661: Cannot convert lambda expression to type 'Action<string>' because the parameter types do not match the delegate parameter types // var a1 = new[] { (object o) => { }, (string s) => { } }; Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "(object o) => { }").WithArguments("lambda expression", "System.Action<string>").WithLocation(6, 26), // (6,34): error CS1678: Parameter 1 is declared as type 'object' but should be 'string' // var a1 = new[] { (object o) => { }, (string s) => { } }; Diagnostic(ErrorCode.ERR_BadParamType, "o").WithArguments("1", "", "object", "", "string").WithLocation(6, 34)); } [Fact] public void BestCommonType_10() { var source = @"using System; class Program { static void F1<T>(T t, ref object o) { } static void F2<T, U>(ref T t, U u) { } static void Main() { var a1 = new[] { F1<string>, F1<string> }; var a2 = new[] { F2<object, string>, F2<object, string> }; Report(a1[0]); Report(a2[0]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { F1<string>, F1<string> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F1<string>, F1<string> }").WithLocation(8, 18), // (9,18): error CS0826: No best type found for implicitly-typed array // var a2 = new[] { F2<object, string>, F2<object, string> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F2<object, string>, F2<object, string> }").WithLocation(9, 18)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"<>A{00000004}`2[System.String,System.Object] <>A{00000001}`2[System.Object,System.String]"); } [Fact] [WorkItem(55909, "https://github.com/dotnet/roslyn/issues/55909")] public void BestCommonType_11() { var source = @"using System; class Program { static void F1<T>(T t, ref object o) { } static void F2<T, U>(ref T t, U u) { } static void Main() { var a1 = new[] { F1<object>, F1<string> }; var a2 = new[] { F2<object, string>, F2<object, object> }; Report(a1[0]); Report(a2[0]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var expectedDiagnostics = new[] { // (8,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { F1<object>, F1<string> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F1<object>, F1<string> }").WithLocation(8, 18), // (9,18): error CS0826: No best type found for implicitly-typed array // var a2 = new[] { F2<object, string>, F2<object, object> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F2<object, string>, F2<object, object> }").WithLocation(9, 18) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); // https://github.com/dotnet/roslyn/issues/55909: ConversionsBase.HasImplicitSignatureConversion() // relies on the variance of FunctionTypeSymbol.GetInternalDelegateType() which fails for synthesized // delegate types where the type parameters are invariant. comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void BestCommonType_12() { var source = @"class Program { static void F<T>(ref T t) { } static void Main() { var a1 = new[] { F<object>, F<string> }; var a2 = new[] { (object x, ref object y) => { }, (string x, ref object y) => { } }; var a3 = new[] { (object x, ref object y) => { }, (object x, ref string y) => { } }; } }"; var expectedDiagnostics = new[] { // (6,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { F<object>, F<string> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F<object>, F<string> }").WithLocation(6, 18), // (7,18): error CS0826: No best type found for implicitly-typed array // var a2 = new[] { (object x, ref object y) => { }, (string x, ref object y) => { } }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { (object x, ref object y) => { }, (string x, ref object y) => { } }").WithLocation(7, 18), // (8,18): error CS0826: No best type found for implicitly-typed array // var a3 = new[] { (object x, ref object y) => { }, (object x, ref string y) => { } }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { (object x, ref object y) => { }, (object x, ref string y) => { } }").WithLocation(8, 18) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void BestCommonType_13() { var source = @"using System; class Program { static void F<T>(ref T t) { } static void Main() { var a1 = new[] { F<object>, null }; var a2 = new[] { default, F<string> }; var a3 = new[] { null, default, (object x, ref string y) => { } }; Report(a1[0]); Report(a2[1]); Report(a3[2]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { F<object>, null }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F<object>, null }").WithLocation(7, 18), // (8,18): error CS0826: No best type found for implicitly-typed array // var a2 = new[] { default, F<string> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { default, F<string> }").WithLocation(8, 18), // (9,18): error CS0826: No best type found for implicitly-typed array // var a3 = new[] { null, default, (object x, ref string y) => { } }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { null, default, (object x, ref string y) => { } }").WithLocation(9, 18)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"<>A{00000001}`1[System.Object] <>A{00000001}`1[System.String] <>A{00000004}`2[System.Object,System.String] "); } /// <summary> /// Best common type inference with delegate signatures that cannot be inferred. /// </summary> [Fact] public void BestCommonType_NoInferredSignature() { var source = @"class Program { static void F1() { } static int F1(int i) => i; static void F2() { } static void Main() { var a1 = new[] { F1 }; var a2 = new[] { F1, F2 }; var a3 = new[] { F2, F1 }; var a4 = new[] { x => x }; var a5 = new[] { x => x, (int y) => y }; var a6 = new[] { (int y) => y, static x => x }; var a7 = new[] { x => x, F1 }; var a8 = new[] { F1, (int y) => y }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { F1 }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F1 }").WithLocation(8, 18), // (9,18): error CS0826: No best type found for implicitly-typed array // var a2 = new[] { F1, F2 }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F1, F2 }").WithLocation(9, 18), // (10,18): error CS0826: No best type found for implicitly-typed array // var a3 = new[] { F2, F1 }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F2, F1 }").WithLocation(10, 18), // (11,18): error CS0826: No best type found for implicitly-typed array // var a4 = new[] { x => x }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { x => x }").WithLocation(11, 18), // (12,18): error CS0826: No best type found for implicitly-typed array // var a5 = new[] { x => x, (int y) => y }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { x => x, (int y) => y }").WithLocation(12, 18), // (13,18): error CS0826: No best type found for implicitly-typed array // var a6 = new[] { (int y) => y, static x => x }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { (int y) => y, static x => x }").WithLocation(13, 18), // (14,18): error CS0826: No best type found for implicitly-typed array // var a7 = new[] { x => x, F1 }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { x => x, F1 }").WithLocation(14, 18), // (15,18): error CS0826: No best type found for implicitly-typed array // var a8 = new[] { F1, (int y) => y }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F1, (int y) => y }").WithLocation(15, 18)); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { F1 }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F1 }").WithLocation(8, 18), // (11,18): error CS0826: No best type found for implicitly-typed array // var a4 = new[] { x => x }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { x => x }").WithLocation(11, 18), // (14,18): error CS0826: No best type found for implicitly-typed array // var a7 = new[] { x => x, F1 }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { x => x, F1 }").WithLocation(14, 18)); } [Fact] public void ArrayInitializer_01() { var source = @"using System; using System.Linq.Expressions; class Program { static void Main() { var a1 = new Func<int>[] { () => 1 }; var a2 = new Expression<Func<int>>[] { () => 2 }; Report(a1[0]); Report(a2[0]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; string expectedOutput = $@"System.Func`1[System.Int32] {s_expressionOfTDelegate0ArgTypeName}[System.Func`1[System.Int32]]"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); } [Fact] public void ArrayInitializer_02() { var source = @"using System; using System.Linq.Expressions; class Program { static void Main() { var a1 = new Delegate[] { () => 1 }; var a2 = new Expression[] { () => 2 }; Report(a1[0]); Report(a2[0]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,35): error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type // var a1 = new Delegate[] { () => 1 }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Delegate").WithLocation(7, 35), // (8,37): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // var a2 = new Expression[] { () => 2 }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 2").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(8, 37)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: $@"System.Func`1[System.Int32] {s_expressionOfTDelegate0ArgTypeName}[System.Func`1[System.Int32]]"); } [Fact] public void ArrayInitializer_03() { var source = @"using System; class Program { static void Main() { var a1 = new[] { () => 1 }; Report(a1[0]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { () => 1 }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { () => 1 }").WithLocation(6, 18)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Func`1[System.Int32]"); } [Fact] public void ConditionalOperator_01() { var source = @"class Program { static void F<T>(T t) { } static void Main() { var c1 = F<object> ?? F<string>; var c2 = ((object o) => { }) ?? ((string s) => { }); var c3 = F<string> ?? ((object o) => { }); } }"; var expectedDiagnostics = new[] { // (6,18): error CS0019: Operator '??' cannot be applied to operands of type 'method group' and 'method group' // var c1 = F<object> ?? F<string>; Diagnostic(ErrorCode.ERR_BadBinaryOps, "F<object> ?? F<string>").WithArguments("??", "method group", "method group").WithLocation(6, 18), // (7,18): error CS0019: Operator '??' cannot be applied to operands of type 'lambda expression' and 'lambda expression' // var c2 = ((object o) => { }) ?? ((string s) => { }); Diagnostic(ErrorCode.ERR_BadBinaryOps, "((object o) => { }) ?? ((string s) => { })").WithArguments("??", "lambda expression", "lambda expression").WithLocation(7, 18), // (8,18): error CS0019: Operator '??' cannot be applied to operands of type 'method group' and 'lambda expression' // var c3 = F<string> ?? ((object o) => { }); Diagnostic(ErrorCode.ERR_BadBinaryOps, "F<string> ?? ((object o) => { })").WithArguments("??", "method group", "lambda expression").WithLocation(8, 18) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void LambdaReturn_01() { var source = @"using System; class Program { static void Main() { var a1 = () => () => 1; var a2 = () => Main; Report(a1()); Report(a2()); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Func`1[System.Int32] System.Action"); } [Fact] public void InferredType_MethodGroup() { var source = @"class Program { static void Main() { System.Delegate d = Main; System.Console.Write(d.GetDelegateTypeName()); } }"; var comp = CreateCompilation(new[] { source, s_utils }, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "System.Action"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value; var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); } [Fact] public void InferredType_LambdaExpression() { var source = @"class Program { static void Main() { System.Delegate d = () => { }; System.Console.Write(d.GetDelegateTypeName()); } }"; var comp = CreateCompilation(new[] { source, s_utils }, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "System.Action"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<AnonymousFunctionExpressionSyntax>().Single(); var typeInfo = model.GetTypeInfo(expr); Assert.Equal("System.Action", typeInfo.Type.ToTestDisplayString()); Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); var symbolInfo = model.GetSymbolInfo(expr); var method = (IMethodSymbol)symbolInfo.Symbol!; Assert.Equal(MethodKind.LambdaMethod, method.MethodKind); Assert.True(HaveMatchingSignatures(((INamedTypeSymbol)typeInfo.Type!).DelegateInvokeMethod!, method)); } [WorkItem(55320, "https://github.com/dotnet/roslyn/issues/55320")] [Fact] public void InferredReturnType_01() { var source = @"using System; class Program { static void Main() { Report(() => { return; }); Report((bool b) => { if (b) return; }); Report((bool b) => { if (b) return; else return; }); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Action System.Action`1[System.Boolean] System.Action`1[System.Boolean] "); } [Fact] public void InferredReturnType_02() { var source = @"using System; class Program { static void Main() { Report(async () => { return; }); Report(async (bool b) => { if (b) return; }); Report(async (bool b) => { if (b) return; else return; }); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Func`1[System.Threading.Tasks.Task] System.Func`2[System.Boolean,System.Threading.Tasks.Task] System.Func`2[System.Boolean,System.Threading.Tasks.Task] "); } [WorkItem(55320, "https://github.com/dotnet/roslyn/issues/55320")] [Fact] public void InferredReturnType_03() { var source = @"using System; class Program { static void Main() { Report((bool b) => { if (b) return null; }); Report((bool b) => { if (b) return; else return null; }); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics( // (6,16): error CS8917: The delegate type could not be inferred. // Report((bool b) => { if (b) return null; }); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(bool b) => { if (b) return null; }").WithLocation(6, 16), // (7,16): error CS8917: The delegate type could not be inferred. // Report((bool b) => { if (b) return; else return null; }); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(bool b) => { if (b) return; else return null; }").WithLocation(7, 16), // (7,50): error CS8030: Anonymous function converted to a void returning delegate cannot return a value // Report((bool b) => { if (b) return; else return null; }); Diagnostic(ErrorCode.ERR_RetNoObjectRequiredLambda, "return").WithLocation(7, 50)); } [WorkItem(55320, "https://github.com/dotnet/roslyn/issues/55320")] [Fact] public void InferredReturnType_04() { var source = @"using System; class Program { static void Main() { Report((bool b) => { if (b) return default; }); Report((bool b) => { if (b) return; else return default; }); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics( // (6,16): error CS8917: The delegate type could not be inferred. // Report((bool b) => { if (b) return default; }); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(bool b) => { if (b) return default; }").WithLocation(6, 16), // (7,16): error CS8917: The delegate type could not be inferred. // Report((bool b) => { if (b) return; else return default; }); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(bool b) => { if (b) return; else return default; }").WithLocation(7, 16), // (7,50): error CS8030: Anonymous function converted to a void returning delegate cannot return a value // Report((bool b) => { if (b) return; else return default; }); Diagnostic(ErrorCode.ERR_RetNoObjectRequiredLambda, "return").WithLocation(7, 50)); } [Fact] public void ExplicitReturnType_01() { var source = @"using System; class Program { static void Main() { Report(object () => { return; }); Report(object (bool b) => { if (b) return null; }); Report(object (bool b) => { if (b) return; else return default; }); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics( // (6,31): error CS0126: An object of a type convertible to 'object' is required // Report(object () => { return; }); Diagnostic(ErrorCode.ERR_RetObjectRequired, "return").WithArguments("object").WithLocation(6, 31), // (7,32): error CS1643: Not all code paths return a value in lambda expression of type 'Func<bool, object>' // Report(object (bool b) => { if (b) return null; }); Diagnostic(ErrorCode.ERR_AnonymousReturnExpected, "=>").WithArguments("lambda expression", "System.Func<bool, object>").WithLocation(7, 32), // (8,44): error CS0126: An object of a type convertible to 'object' is required // Report(object (bool b) => { if (b) return; else return default; }); Diagnostic(ErrorCode.ERR_RetObjectRequired, "return").WithArguments("object").WithLocation(8, 44)); } [Fact] public void TypeInference_Constraints_01() { var source = @"using System; using System.Linq.Expressions; class Program { static T F1<T>(T t) where T : Delegate => t; static T F2<T>(T t) where T : Expression => t; static void Main() { Report(F1((int i) => { })); Report(F2(() => 1)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,16): error CS0411: The type arguments for method 'Program.F1<T>(T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F1((int i) => { })); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F1").WithArguments("Program.F1<T>(T)").WithLocation(9, 16), // (10,16): error CS0411: The type arguments for method 'Program.F2<T>(T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F2(() => 1)); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F2").WithArguments("Program.F2<T>(T)").WithLocation(10, 16)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: $@"System.Action`1[System.Int32] {s_expressionOfTDelegate0ArgTypeName}[System.Func`1[System.Int32]] "); } [Fact] public void TypeInference_Constraints_02() { var source = @"using System; using System.Linq.Expressions; class A<T> { public static U F<U>(U u) where U : T => u; } class B { static void Main() { Report(A<object>.F(() => 1)); Report(A<ICloneable>.F(() => 1)); Report(A<Delegate>.F(() => 1)); Report(A<MulticastDelegate>.F(() => 1)); Report(A<Func<int>>.F(() => 1)); Report(A<Expression>.F(() => 1)); Report(A<LambdaExpression>.F(() => 1)); Report(A<Expression<Func<int>>>.F(() => 1)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: $@"System.Func`1[System.Int32] System.Func`1[System.Int32] System.Func`1[System.Int32] System.Func`1[System.Int32] System.Func`1[System.Int32] {s_expressionOfTDelegate0ArgTypeName}[System.Func`1[System.Int32]] {s_expressionOfTDelegate0ArgTypeName}[System.Func`1[System.Int32]] {s_expressionOfTDelegate0ArgTypeName}[System.Func`1[System.Int32]] "); } [Fact] public void TypeInference_Constraints_03() { var source = @"using System; using System.Linq.Expressions; class A<T, U> where U : T { public static V F<V>(V v) where V : U => v; } class B { static void Main() { Report(A<object, object>.F(() => 1)); Report(A<object, Delegate>.F(() => 1)); Report(A<object, Func<int>>.F(() => 1)); Report(A<Delegate, Func<int>>.F(() => 1)); Report(A<object, Expression>.F(() => 1)); Report(A<object, Expression<Func<int>>>.F(() => 1)); Report(A<Expression, LambdaExpression>.F(() => 1)); Report(A<Expression, Expression<Func<int>>>.F(() => 1)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: $@"System.Func`1[System.Int32] System.Func`1[System.Int32] System.Func`1[System.Int32] System.Func`1[System.Int32] {s_expressionOfTDelegate0ArgTypeName}[System.Func`1[System.Int32]] {s_expressionOfTDelegate0ArgTypeName}[System.Func`1[System.Int32]] {s_expressionOfTDelegate0ArgTypeName}[System.Func`1[System.Int32]] {s_expressionOfTDelegate0ArgTypeName}[System.Func`1[System.Int32]] "); } [Fact] public void TypeInference_MatchingSignatures() { var source = @"using System; class Program { static T F<T>(T x, T y) => x; static int F1(string s) => s.Length; static void F2(string s) { } static void Main() { Report(F(F1, (string s) => int.Parse(s))); Report(F((string s) => { }, F2)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,16): error CS0411: The type arguments for method 'Program.F<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F(F1, (string s) => int.Parse(s))); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("Program.F<T>(T, T)").WithLocation(9, 16), // (10,16): error CS0411: The type arguments for method 'Program.F<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F((string s) => { }, F2)); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("Program.F<T>(T, T)").WithLocation(10, 16)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Func`2[System.String,System.Int32] System.Action`1[System.String] "); } [Fact] public void TypeInference_DistinctSignatures() { var source = @"using System; class Program { static T F<T>(T x, T y) => x; static int F1(object o) => o.GetHashCode(); static void F2(object o) { } static void Main() { Report(F(F1, (string s) => int.Parse(s))); Report(F((string s) => { }, F2)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,16): error CS0411: The type arguments for method 'Program.F<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F(F1, (string s) => int.Parse(s))); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("Program.F<T>(T, T)").WithLocation(9, 16), // (10,16): error CS0411: The type arguments for method 'Program.F<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F((string s) => { }, F2)); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("Program.F<T>(T, T)").WithLocation(10, 16)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Func`2[System.String,System.Int32] System.Action`1[System.String] "); } [Fact] public void TypeInference_01() { var source = @"using System; class Program { static T M<T>(T x, T y) => x; static int F1(int i) => i; static void F1() { } static T F2<T>(T t) => t; static void Main() { var f1 = M(x => x, (int y) => y); var f2 = M(F1, F2<int>); var f3 = M(F2<object>, z => z); Report(f1); Report(f2); Report(f3); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (10,18): error CS0411: The type arguments for method 'Program.M<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var f1 = M(x => x, (int y) => y); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T>(T, T)").WithLocation(10, 18), // (11,18): error CS0411: The type arguments for method 'Program.M<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var f2 = M(F1, F2<int>); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T>(T, T)").WithLocation(11, 18), // (12,18): error CS0411: The type arguments for method 'Program.M<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var f3 = M(F2<object>, z => z); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T>(T, T)").WithLocation(12, 18)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Func`2[System.Int32,System.Int32] System.Func`2[System.Int32,System.Int32] System.Func`2[System.Object,System.Object] "); } [Fact] public void TypeInference_02() { var source = @"using System; class Program { static T M<T>(T x, T y) where T : class => x ?? y; static T F<T>() => default; static void Main() { var f1 = M(F<object>, null); var f2 = M(default, F<string>); var f3 = M((object x, ref string y) => { }, default); var f4 = M(null, (ref object x, string y) => { }); Report(f1); Report(f2); Report(f3); Report(f4); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,18): error CS0411: The type arguments for method 'Program.M<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var f1 = M(F<object>, null); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T>(T, T)").WithLocation(8, 18), // (9,18): error CS0411: The type arguments for method 'Program.M<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var f2 = M(default, F<string>); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T>(T, T)").WithLocation(9, 18), // (10,18): error CS0411: The type arguments for method 'Program.M<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var f3 = M((object x, ref string y) => { }, default); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T>(T, T)").WithLocation(10, 18), // (11,18): error CS0411: The type arguments for method 'Program.M<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var f4 = M(null, (ref object x, string y) => { }); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T>(T, T)").WithLocation(11, 18)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Func`1[System.Object] System.Func`1[System.String] <>A{00000004}`2[System.Object,System.String] <>A{00000001}`2[System.Object,System.String] "); } [Fact] public void TypeInference_LowerBoundsMatchingSignature() { var source = @"using System; delegate void D1<T>(T t); delegate T D2<T>(); class Program { static T F<T>(T x, T y) => y; static void Main() { D1<string> d1 = (string s) => { }; D2<int> d2 = () => 1; Report(F(d1, (string s) => { })); Report(F(() => 2, d2)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var expectedOutput = @"D1`1[System.String] D2`1[System.Int32] "; CompileAndVerify(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); } [Fact] public void TypeInference_LowerBoundsDistinctSignature_01() { var source = @"using System; delegate void D1<T>(T t); delegate T D2<T>(); class Program { static T F<T>(T x, T y) => y; static void Main() { D1<string> d1 = (string s) => { }; D2<int> d2 = () => 1; Report(F(d1, (object o) => { })); Report(F(() => 1.0, d2)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var expectedDiagnostics = new[] { // (11,22): error CS1661: Cannot convert lambda expression to type 'D1<string>' because the parameter types do not match the delegate parameter types // Report(F(d1, (object o) => { })); Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "(object o) => { }").WithArguments("lambda expression", "D1<string>").WithLocation(11, 22), // (11,30): error CS1678: Parameter 1 is declared as type 'object' but should be 'string' // Report(F(d1, (object o) => { })); Diagnostic(ErrorCode.ERR_BadParamType, "o").WithArguments("1", "", "object", "", "string").WithLocation(11, 30), // (12,24): error CS0266: Cannot implicitly convert type 'double' to 'int'. An explicit conversion exists (are you missing a cast?) // Report(F(() => 1.0, d2)); Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "1.0").WithArguments("double", "int").WithLocation(12, 24), // (12,24): error CS1662: Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type // Report(F(() => 1.0, d2)); Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, "1.0").WithArguments("lambda expression").WithLocation(12, 24) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void TypeInference_LowerBoundsDistinctSignature_02() { var source = @"using System; class Program { static T F<T>(T x, T y) => y; static void Main() { Report(F((string s) => { }, (object o) => { })); Report(F(() => string.Empty, () => new object())); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,16): error CS0411: The type arguments for method 'Program.F<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F((string s) => { }, (object o) => { })); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("Program.F<T>(T, T)").WithLocation(7, 16), // (8,16): error CS0411: The type arguments for method 'Program.F<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F(() => string.Empty, () => new object())); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("Program.F<T>(T, T)").WithLocation(8, 16)); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,37): error CS1661: Cannot convert lambda expression to type 'Action<string>' because the parameter types do not match the delegate parameter types // Report(F((string s) => { }, (object o) => { })); Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "(object o) => { }").WithArguments("lambda expression", "System.Action<string>").WithLocation(7, 37), // (7,45): error CS1678: Parameter 1 is declared as type 'object' but should be 'string' // Report(F((string s) => { }, (object o) => { })); Diagnostic(ErrorCode.ERR_BadParamType, "o").WithArguments("1", "", "object", "", "string").WithLocation(7, 45)); } [Fact] public void TypeInference_UpperAndLowerBoundsMatchingSignature() { var source = @"using System; delegate void D1<T>(T t); delegate T D2<T>(); class Program { static T F1<T>(Action<T> x, T y) => y; static T F2<T>(T x, Action<T> y) => x; static void Main() { Action<D1<string>> a1 = null; Action<D2<int>> a2 = null; Report(F1(a1, (string s) => { })); Report(F2(() => 2, a2)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var expectedOutput = @"D1`1[System.String] D2`1[System.Int32] "; CompileAndVerify(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); } [Fact] public void TypeInference_UpperAndLowerBoundsDistinctSignature_01() { var source = @"using System; delegate void D1<T>(T t); delegate T D2<T>(); class Program { static T F1<T>(Action<T> x, T y) => y; static T F2<T>(T x, Action<T> y) => x; static void Main() { Action<D1<string>> a1 = null; Action<D2<object>> a2 = null; Report(F1(a1, (object o) => { })); Report(F2(() => string.Empty, a2)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var expectedDiagnostics = new[] { // (12,23): error CS1661: Cannot convert lambda expression to type 'D1<string>' because the parameter types do not match the delegate parameter types // Report(F1(a1, (object o) => { })); Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "(object o) => { }").WithArguments("lambda expression", "D1<string>").WithLocation(12, 23), // (12,31): error CS1678: Parameter 1 is declared as type 'object' but should be 'string' // Report(F1(a1, (object o) => { })); Diagnostic(ErrorCode.ERR_BadParamType, "o").WithArguments("1", "", "object", "", "string").WithLocation(12, 31) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void TypeInference_UpperAndLowerBoundsDistinctSignature_02() { var source = @"using System; delegate void D1<T>(T t); delegate T D2<T>(); class Program { static T F1<T>(Action<T> x, T y) => y; static T F2<T>(T x, Action<T> y) => x; static void Main() { Report(F1((D1<string> d) => { }, (object o) => { })); Report(F2(() => string.Empty, (D2<object> d) => { })); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var expectedDiagnostics = new[] { // (10,42): error CS1661: Cannot convert lambda expression to type 'D1<string>' because the parameter types do not match the delegate parameter types // Report(F1((D1<string> d) => { }, (object o) => { })); Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "(object o) => { }").WithArguments("lambda expression", "D1<string>").WithLocation(10, 42), // (10,50): error CS1678: Parameter 1 is declared as type 'object' but should be 'string' // Report(F1((D1<string> d) => { }, (object o) => { })); Diagnostic(ErrorCode.ERR_BadParamType, "o").WithArguments("1", "", "object", "", "string").WithLocation(10, 50) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void TypeInference_ExactAndLowerBoundsMatchingSignature() { var source = @"using System; delegate void D1<T>(T t); delegate T D2<T>(); class Program { static T F1<T>(ref T x, T y) => y; static T F2<T>(T x, ref T y) => y; static void Main() { D1<string> d1 = (string s) => { }; D2<int> d2 = () => 1; Report(F1(ref d1, (string s) => { })); Report(F2(() => 2, ref d2)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var expectedOutput = @"D1`1[System.String] D2`1[System.Int32] "; CompileAndVerify(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); } [Fact] public void TypeInference_ExactAndLowerBoundsDistinctSignature_01() { var source = @"using System; delegate void D1<T>(T t); delegate T D2<T>(); class Program { static T F1<T>(ref T x, T y) => y; static T F2<T>(T x, ref T y) => y; static void Main() { D1<string> d1 = (string s) => { }; D2<object> d2 = () => new object(); Report(F1(ref d1, (object o) => { })); Report(F2(() => string.Empty, ref d2)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var expectedDiagnostics = new[] { // (12,27): error CS1661: Cannot convert lambda expression to type 'D1<string>' because the parameter types do not match the delegate parameter types // Report(F1(ref d1, (object o) => { })); Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "(object o) => { }").WithArguments("lambda expression", "D1<string>").WithLocation(12, 27), // (12,35): error CS1678: Parameter 1 is declared as type 'object' but should be 'string' // Report(F1(ref d1, (object o) => { })); Diagnostic(ErrorCode.ERR_BadParamType, "o").WithArguments("1", "", "object", "", "string").WithLocation(12, 35) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void TypeInference_ExactAndLowerBoundsDistinctSignature_02() { var source = @"using System; delegate void D1<T>(T t); delegate T D2<T>(); class Program { static T F1<T>(in T x, T y) => y; static T F2<T>(T x, in T y) => y; static void Main() { Report(F1((D1<string> d) => { }, (object o) => { })); Report(F2(() => string.Empty, (D2<object> d) => { })); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var expectedDiagnostics = new[] { // (10,16): error CS0411: The type arguments for method 'Program.F1<T>(in T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F1((D1<string> d) => { }, (object o) => { })); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F1").WithArguments("Program.F1<T>(in T, T)").WithLocation(10, 16), // (11,16): error CS0411: The type arguments for method 'Program.F2<T>(T, in T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F2(() => 1.0, (D2<int> d) => { })); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F2").WithArguments("Program.F2<T>(T, in T)").WithLocation(11, 16) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,42): error CS1661: Cannot convert lambda expression to type 'Action<D1<string>>' because the parameter types do not match the delegate parameter types // Report(F1((D1<string> d) => { }, (object o) => { })); Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "(object o) => { }").WithArguments("lambda expression", "System.Action<D1<string>>").WithLocation(10, 42), // (10,50): error CS1678: Parameter 1 is declared as type 'object' but should be 'D1<string>' // Report(F1((D1<string> d) => { }, (object o) => { })); Diagnostic(ErrorCode.ERR_BadParamType, "o").WithArguments("1", "", "object", "", "D1<string>").WithLocation(10, 50), // (11,16): error CS0411: The type arguments for method 'Program.F2<T>(T, in T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F2(() => 1.0, (D2<int> d) => { })); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F2").WithArguments("Program.F2<T>(T, in T)").WithLocation(11, 16)); } [Fact] public void TypeInference_Nested_01() { var source = @"delegate void D<T>(T t); class Program { static T F1<T>(T t) => t; static D<T> F2<T>(D<T> d) => d; static void Main() { F2(F1((string s) => { })); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,12): error CS0411: The type arguments for method 'Program.F1<T>(T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F2(F1((string s) => { })); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F1").WithArguments("Program.F1<T>(T)").WithLocation(8, 12)); // Reports error on F1() in C#9, and reports error on F2() in C#10. comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,9): error CS0411: The type arguments for method 'Program.F2<T>(D<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F2(F1((string s) => { })); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F2").WithArguments("Program.F2<T>(D<T>)").WithLocation(8, 9)); } [Fact] public void TypeInference_Nested_02() { var source = @"using System.Linq.Expressions; class Program { static T F1<T>(T x) => throw null; static Expression<T> F2<T>(Expression<T> e) => e; static void Main() { F2(F1((object x1) => 1)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,12): error CS0411: The type arguments for method 'Program.F1<T>(T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F2(F1((string s) => { })); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F1").WithArguments("Program.F1<T>(T)").WithLocation(8, 12)); // Reports error on F1() in C#9, and reports error on F2() in C#10. comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,9): error CS0411: The type arguments for method 'Program.F2<T>(Expression<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F2(F1((object x1) => 1)); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F2").WithArguments("Program.F2<T>(System.Linq.Expressions.Expression<T>)").WithLocation(8, 9)); } /// <summary> /// Method type inference with delegate signatures that cannot be inferred. /// </summary> [Fact] public void TypeInference_NoInferredSignature() { var source = @"class Program { static void F1() { } static void F1(int i) { } static void F2() { } static T M1<T>(T t) => t; static T M2<T>(T x, T y) => x; static void Main() { var a1 = M1(F1); var a2 = M2(F1, F2); var a3 = M2(F2, F1); var a4 = M1(x => x); var a5 = M2(x => x, (int y) => y); var a6 = M2((int y) => y, x => x); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (10,18): error CS0411: The type arguments for method 'Program.M1<T>(T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var a1 = M1(F1); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M1").WithArguments("Program.M1<T>(T)").WithLocation(10, 18), // (11,18): error CS0411: The type arguments for method 'Program.M2<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var a2 = M2(F1, F2); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M2").WithArguments("Program.M2<T>(T, T)").WithLocation(11, 18), // (12,18): error CS0411: The type arguments for method 'Program.M2<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var a3 = M2(F2, F1); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M2").WithArguments("Program.M2<T>(T, T)").WithLocation(12, 18), // (13,18): error CS0411: The type arguments for method 'Program.M1<T>(T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var a4 = M1(x => x); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M1").WithArguments("Program.M1<T>(T)").WithLocation(13, 18), // (14,18): error CS0411: The type arguments for method 'Program.M2<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var a5 = M2(x => x, (int y) => y); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M2").WithArguments("Program.M2<T>(T, T)").WithLocation(14, 18), // (15,18): error CS0411: The type arguments for method 'Program.M2<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var a6 = M2((int y) => y, x => x); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M2").WithArguments("Program.M2<T>(T, T)").WithLocation(15, 18)); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,18): error CS0411: The type arguments for method 'Program.M1<T>(T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var a1 = M1(F1); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M1").WithArguments("Program.M1<T>(T)").WithLocation(10, 18), // (13,18): error CS0411: The type arguments for method 'Program.M1<T>(T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var a4 = M1(x => x); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M1").WithArguments("Program.M1<T>(T)").WithLocation(13, 18)); } [Fact] public void TypeInference_ExplicitReturnType_01() { var source = @"using System; using System.Linq.Expressions; class Program { static void F1<T>(Func<T> f) { Console.WriteLine(f.GetType()); } static void F2<T>(Expression<Func<T>> e) { Console.WriteLine(e.GetType()); } static void Main() { F1(int () => throw new Exception()); F2(int () => default); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,12): error CS8773: Feature 'lambda return type' is not available in C# 9.0. Please use language version 10.0 or greater. // F1(int () => throw new Exception()); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "int").WithArguments("lambda return type", "10.0").WithLocation(9, 12), // (10,12): error CS8773: Feature 'lambda return type' is not available in C# 9.0. Please use language version 10.0 or greater. // F2(int () => default); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "int").WithArguments("lambda return type", "10.0").WithLocation(10, 12)); var expectedOutput = $@"System.Func`1[System.Int32] {s_expressionOfTDelegate0ArgTypeName}[System.Func`1[System.Int32]] "; CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [WorkItem(54257, "https://github.com/dotnet/roslyn/issues/54257")] [Fact] public void TypeInference_ExplicitReturnType_02() { var source = @"using System; using System.Linq.Expressions; class Program { static void F1<T>(Func<T, T> f) { Console.WriteLine(f.GetType()); } static void F2<T>(Expression<Func<T, T>> e) { Console.WriteLine(e.GetType()); } static void Main() { F1(int (i) => i); F2(string (s) => s); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,12): error CS8773: Feature 'lambda return type' is not available in C# 9.0. Please use language version 10.0 or greater. // F1(int (i) => i); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "int").WithArguments("lambda return type", "10.0").WithLocation(9, 12), // (10,12): error CS8773: Feature 'lambda return type' is not available in C# 9.0. Please use language version 10.0 or greater. // F2(string (s) => s); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "string").WithArguments("lambda return type", "10.0").WithLocation(10, 12)); var expectedOutput = $@"System.Func`2[System.Int32,System.Int32] {s_expressionOfTDelegate1ArgTypeName}[System.Func`2[System.String,System.String]] "; CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [WorkItem(54257, "https://github.com/dotnet/roslyn/issues/54257")] [Fact] public void TypeInference_ExplicitReturnType_03() { var source = @"using System; delegate ref T D1<T>(T t); delegate ref readonly T D2<T>(T t); class Program { static void F1<T>(D1<T> d) { Console.WriteLine(d.GetType()); } static void F2<T>(D2<T> d) { Console.WriteLine(d.GetType()); } static void Main() { F1((ref int (i) => ref i)); F2((ref readonly string (s) => ref s)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (10,13): error CS8773: Feature 'lambda return type' is not available in C# 9.0. Please use language version 10.0 or greater. // F1((ref int (i) => ref i)); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "ref int").WithArguments("lambda return type", "10.0").WithLocation(10, 13), // (10,32): error CS8166: Cannot return a parameter by reference 'i' because it is not a ref or out parameter // F1((ref int (i) => ref i)); Diagnostic(ErrorCode.ERR_RefReturnParameter, "i").WithArguments("i").WithLocation(10, 32), // (11,13): error CS8773: Feature 'lambda return type' is not available in C# 9.0. Please use language version 10.0 or greater. // F2((ref readonly string (s) => ref s)); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "ref readonly string").WithArguments("lambda return type", "10.0").WithLocation(11, 13), // (11,44): error CS8166: Cannot return a parameter by reference 's' because it is not a ref or out parameter // F2((ref readonly string (s) => ref s)); Diagnostic(ErrorCode.ERR_RefReturnParameter, "s").WithArguments("s").WithLocation(11, 44)); var expectedDiagnostics = new[] { // (10,32): error CS8166: Cannot return a parameter by reference 'i' because it is not a ref or out parameter // F1((ref int (i) => ref i)); Diagnostic(ErrorCode.ERR_RefReturnParameter, "i").WithArguments("i").WithLocation(10, 32), // (11,44): error CS8166: Cannot return a parameter by reference 's' because it is not a ref or out parameter // F2((ref readonly string (s) => ref s)); Diagnostic(ErrorCode.ERR_RefReturnParameter, "s").WithArguments("s").WithLocation(11, 44) }; comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [WorkItem(54257, "https://github.com/dotnet/roslyn/issues/54257")] [Fact] public void TypeInference_ExplicitReturnType_04() { var source = @"using System; using System.Linq.Expressions; class Program { static void F1<T>(Func<T, T> x, T y) { Console.WriteLine(x.GetType()); } static void F2<T>(Expression<Func<T, T>> x, T y) { Console.WriteLine(x.GetType()); } static void Main() { F1(object (o) => o, 1); F1(int (i) => i, 2); F2(object (o) => o, string.Empty); F2(string (s) => s, string.Empty); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,12): error CS8773: Feature 'lambda return type' is not available in C# 9.0. Please use language version 10.0 or greater. // F1(object (o) => o, 1); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "object").WithArguments("lambda return type", "10.0").WithLocation(9, 12), // (10,12): error CS8773: Feature 'lambda return type' is not available in C# 9.0. Please use language version 10.0 or greater. // F1(int (i) => i, 2); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "int").WithArguments("lambda return type", "10.0").WithLocation(10, 12), // (11,12): error CS8773: Feature 'lambda return type' is not available in C# 9.0. Please use language version 10.0 or greater. // F2(object (o) => o, string.Empty); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "object").WithArguments("lambda return type", "10.0").WithLocation(11, 12), // (12,12): error CS8773: Feature 'lambda return type' is not available in C# 9.0. Please use language version 10.0 or greater. // F2(string (s) => s, string.Empty); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "string").WithArguments("lambda return type", "10.0").WithLocation(12, 12)); var expectedOutput = $@"System.Func`2[System.Object,System.Object] System.Func`2[System.Int32,System.Int32] {s_expressionOfTDelegate1ArgTypeName}[System.Func`2[System.Object,System.Object]] {s_expressionOfTDelegate1ArgTypeName}[System.Func`2[System.String,System.String]] "; CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [WorkItem(54257, "https://github.com/dotnet/roslyn/issues/54257")] [Fact] public void TypeInference_ExplicitReturnType_05() { var source = @"using System; using System.Linq.Expressions; class Program { static void F1<T>(Func<T, T> x, T y) { Console.WriteLine(x.GetType()); } static void F2<T>(Expression<Func<T, T>> x, T y) { Console.WriteLine(x.GetType()); } static void Main() { F1(int (i) => i, (object)1); F2(string (s) => s, (object)2); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,9): error CS0411: The type arguments for method 'Program.F1<T>(Func<T, T>, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F1(int (i) => i, (object)1); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F1").WithArguments("Program.F1<T>(System.Func<T, T>, T)").WithLocation(9, 9), // (9,12): error CS8773: Feature 'lambda return type' is not available in C# 9.0. Please use language version 10.0 or greater. // F1(int (i) => i, (object)1); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "int").WithArguments("lambda return type", "10.0").WithLocation(9, 12), // (10,9): error CS0411: The type arguments for method 'Program.F2<T>(Expression<Func<T, T>>, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F2(string (s) => s, (object)2); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F2").WithArguments("Program.F2<T>(System.Linq.Expressions.Expression<System.Func<T, T>>, T)").WithLocation(10, 9), // (10,12): error CS8773: Feature 'lambda return type' is not available in C# 9.0. Please use language version 10.0 or greater. // F2(string (s) => s, (object)2); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "string").WithArguments("lambda return type", "10.0").WithLocation(10, 12)); var expectedDiagnostics = new[] { // (9,9): error CS0411: The type arguments for method 'Program.F1<T>(Func<T, T>, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F1(int (i) => i, (object)1); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F1").WithArguments("Program.F1<T>(System.Func<T, T>, T)").WithLocation(9, 9), // (10,9): error CS0411: The type arguments for method 'Program.F2<T>(Expression<Func<T, T>>, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F2(string (s) => s, (object)2); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F2").WithArguments("Program.F2<T>(System.Linq.Expressions.Expression<System.Func<T, T>>, T)").WithLocation(10, 9) }; comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [WorkItem(54257, "https://github.com/dotnet/roslyn/issues/54257")] [Fact] public void TypeInference_ExplicitReturnType_06() { var source = @"using System; using System.Linq.Expressions; interface I<T> { } class Program { static void F1<T>(Func<T, T> f) { } static void F2<T>(Func<T, I<T>> f) { } static void F3<T>(Func<I<T>, T> f) { } static void F4<T>(Func<I<T>, I<T>> f) { } static void F5<T>(Expression<Func<T, T>> e) { } static void F6<T>(Expression<Func<T, I<T>>> e) { } static void F7<T>(Expression<Func<I<T>, T>> e) { } static void F8<T>(Expression<Func<I<T>, I<T>>> e) { } static void Main() { F1(int (int i) => default); F2(I<int> (int i) => default); F3(int (I<int> i) => default); F4(I<int> (I<int> i) => default); F5(int (int i) => default); F6(I<int> (int i) => default); F7(int (I<int> i) => default); F8(I<int> (I<int> i) => default); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [WorkItem(54257, "https://github.com/dotnet/roslyn/issues/54257")] [Fact] public void TypeInference_ExplicitReturnType_07() { var source = @"using System; using System.Linq.Expressions; interface I<T> { } class Program { static void F1<T>(Func<T, T> f) { } static void F2<T>(Func<T, I<T>> f) { } static void F3<T>(Func<I<T>, T> f) { } static void F4<T>(Func<I<T>, I<T>> f) { } static void F5<T>(Expression<Func<T, T>> e) { } static void F6<T>(Expression<Func<T, I<T>>> e) { } static void F7<T>(Expression<Func<I<T>, T>> e) { } static void F8<T>(Expression<Func<I<T>, I<T>>> e) { } static void Main() { F1(int (object i) => default); F2(I<int> (object i) => default); F3(object (I<int> i) => default); F4(I<object> (I<int> i) => default); F5(object (int i) => default); F6(I<object> (int i) => default); F7(int (I<object> i) => default); F8(I<int> (I<object> i) => default); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (16,9): error CS0411: The type arguments for method 'Program.F1<T>(Func<T, T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F1(int (object i) => default); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F1").WithArguments("Program.F1<T>(System.Func<T, T>)").WithLocation(16, 9), // (17,9): error CS0411: The type arguments for method 'Program.F2<T>(Func<T, I<T>>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F2(I<int> (object i) => default); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F2").WithArguments("Program.F2<T>(System.Func<T, I<T>>)").WithLocation(17, 9), // (18,9): error CS0411: The type arguments for method 'Program.F3<T>(Func<I<T>, T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F3(object (I<int> i) => default); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F3").WithArguments("Program.F3<T>(System.Func<I<T>, T>)").WithLocation(18, 9), // (19,9): error CS0411: The type arguments for method 'Program.F4<T>(Func<I<T>, I<T>>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F4(I<object> (I<int> i) => default); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F4").WithArguments("Program.F4<T>(System.Func<I<T>, I<T>>)").WithLocation(19, 9), // (20,9): error CS0411: The type arguments for method 'Program.F5<T>(Expression<Func<T, T>>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F5(object (int i) => default); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F5").WithArguments("Program.F5<T>(System.Linq.Expressions.Expression<System.Func<T, T>>)").WithLocation(20, 9), // (21,9): error CS0411: The type arguments for method 'Program.F6<T>(Expression<Func<T, I<T>>>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F6(I<object> (int i) => default); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F6").WithArguments("Program.F6<T>(System.Linq.Expressions.Expression<System.Func<T, I<T>>>)").WithLocation(21, 9), // (22,9): error CS0411: The type arguments for method 'Program.F7<T>(Expression<Func<I<T>, T>>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F7(int (I<object> i) => default); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F7").WithArguments("Program.F7<T>(System.Linq.Expressions.Expression<System.Func<I<T>, T>>)").WithLocation(22, 9), // (23,9): error CS0411: The type arguments for method 'Program.F8<T>(Expression<Func<I<T>, I<T>>>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F8(I<int> (I<object> i) => default); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F8").WithArguments("Program.F8<T>(System.Linq.Expressions.Expression<System.Func<I<T>, I<T>>>)").WithLocation(23, 9)); } // Variance in inference from explicit return type is disallowed // (see https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md). [WorkItem(54257, "https://github.com/dotnet/roslyn/issues/54257")] [Fact] public void TypeInference_ExplicitReturnType_08() { var source = @"using System; using System.Linq.Expressions; class Program { static void F1<T>(Func<T, T> x, Func<T, T> y) { Console.WriteLine(x.GetType()); } static void F2<T>(Expression<Func<T, T>> x, Expression<Func<T, T>> y) { Console.WriteLine(x.GetType()); } static void Main() { F1(int (x) => x, int (y) => y); F1(object (x) => x, int (y) => y); F2(string (x) => x, string (y) => y); F2(string (x) => x, object (y) => y); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,12): error CS8773: Feature 'lambda return type' is not available in C# 9.0. Please use language version 10.0 or greater. // F1(int (x) => x, int (y) => y); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "int").WithArguments("lambda return type", "10.0").WithLocation(9, 12), // (9,26): error CS8773: Feature 'lambda return type' is not available in C# 9.0. Please use language version 10.0 or greater. // F1(int (x) => x, int (y) => y); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "int").WithArguments("lambda return type", "10.0").WithLocation(9, 26), // (10,9): error CS0411: The type arguments for method 'Program.F1<T>(Func<T, T>, Func<T, T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F1(object (x) => x, int (y) => y); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F1").WithArguments("Program.F1<T>(System.Func<T, T>, System.Func<T, T>)").WithLocation(10, 9), // (10,12): error CS8773: Feature 'lambda return type' is not available in C# 9.0. Please use language version 10.0 or greater. // F1(object (x) => x, int (y) => y); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "object").WithArguments("lambda return type", "10.0").WithLocation(10, 12), // (10,29): error CS8773: Feature 'lambda return type' is not available in C# 9.0. Please use language version 10.0 or greater. // F1(object (x) => x, int (y) => y); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "int").WithArguments("lambda return type", "10.0").WithLocation(10, 29), // (11,12): error CS8773: Feature 'lambda return type' is not available in C# 9.0. Please use language version 10.0 or greater. // F2(string (x) => x, string (y) => y); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "string").WithArguments("lambda return type", "10.0").WithLocation(11, 12), // (11,29): error CS8773: Feature 'lambda return type' is not available in C# 9.0. Please use language version 10.0 or greater. // F2(string (x) => x, string (y) => y); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "string").WithArguments("lambda return type", "10.0").WithLocation(11, 29), // (12,9): error CS0411: The type arguments for method 'Program.F2<T>(Expression<Func<T, T>>, Expression<Func<T, T>>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F2(string (x) => x, object (y) => y); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F2").WithArguments("Program.F2<T>(System.Linq.Expressions.Expression<System.Func<T, T>>, System.Linq.Expressions.Expression<System.Func<T, T>>)").WithLocation(12, 9), // (12,12): error CS8773: Feature 'lambda return type' is not available in C# 9.0. Please use language version 10.0 or greater. // F2(string (x) => x, object (y) => y); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "string").WithArguments("lambda return type", "10.0").WithLocation(12, 12), // (12,29): error CS8773: Feature 'lambda return type' is not available in C# 9.0. Please use language version 10.0 or greater. // F2(string (x) => x, object (y) => y); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "object").WithArguments("lambda return type", "10.0").WithLocation(12, 29)); var expectedDiagnostics = new[] { // (10,9): error CS0411: The type arguments for method 'Program.F1<T>(Func<T, T>, Func<T, T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F1(object (x) => x, int (y) => y); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F1").WithArguments("Program.F1<T>(System.Func<T, T>, System.Func<T, T>)").WithLocation(10, 9), // (12,9): error CS0411: The type arguments for method 'Program.F2<T>(Expression<Func<T, T>>, Expression<Func<T, T>>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F2(string (x) => x, object (y) => y); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F2").WithArguments("Program.F2<T>(System.Linq.Expressions.Expression<System.Func<T, T>>, System.Linq.Expressions.Expression<System.Func<T, T>>)").WithLocation(12, 9) }; comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [WorkItem(54257, "https://github.com/dotnet/roslyn/issues/54257")] [Fact] public void TypeInference_ExplicitReturnType_09() { var source = @"#nullable enable using System; using System.Linq.Expressions; class Program { static T F1<T>(Func<T, T> f) => default!; static T F2<T>(Expression<Func<T, T>> e) => default!; static void Main() { F1(object (x1) => x1).ToString(); F2(object (x2) => x2).ToString(); F1(object? (y1) => y1).ToString(); F2(object? (y2) => y2).ToString(); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (12,9): warning CS8602: Dereference of a possibly null reference. // F1(object? (y1) => y1).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(object? (y1) => y1)").WithLocation(12, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // F2(object? (y2) => y2).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(object? (y2) => y2)").WithLocation(13, 9)); } [WorkItem(54257, "https://github.com/dotnet/roslyn/issues/54257")] [Fact] public void TypeInference_ExplicitReturnType_10() { var source = @"#nullable enable using System; using System.Linq.Expressions; class Program { static T F1<T>(Func<T, T> f) => default!; static T F2<T>(Expression<Func<T, T>> e) => default!; static void Main() { F1( #nullable disable object (x1) => #nullable enable x1).ToString(); F2( #nullable disable object (x2) => #nullable enable x2).ToString(); F1( #nullable disable object #nullable enable (y1) => y1).ToString(); F2( #nullable disable object #nullable enable (y2) => y2).ToString(); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [WorkItem(54257, "https://github.com/dotnet/roslyn/issues/54257")] [Fact] public void TypeInference_ExplicitReturnType_11() { var source = @"#nullable enable using System; using System.Linq.Expressions; class Program { static T F1<T>(Func<T, T> f) => default!; static T F2<T>(Expression<Func<T, T>> e) => default!; static void Main() { var x1 = F1( #nullable enable object? #nullable disable (x1) => #nullable enable x1); var x2 = F2( #nullable enable object? #nullable disable (x2) => #nullable enable x2); var y1 = F1( #nullable enable object #nullable disable (y1) => #nullable enable y1); var y2 = F2( #nullable enable object #nullable disable (y2) => #nullable enable y2); x1.ToString(); x2.ToString(); y1.ToString(); y2.ToString(); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (38,9): warning CS8602: Dereference of a possibly null reference. // x1.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1").WithLocation(38, 9), // (39,9): warning CS8602: Dereference of a possibly null reference. // x2.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x2").WithLocation(39, 9)); } [WorkItem(54257, "https://github.com/dotnet/roslyn/issues/54257")] [Fact] public void TypeInference_ExplicitReturnType_12() { var source = @"#nullable enable using System; using System.Linq.Expressions; class Program { static T F1<T>(Func<T, T> f) => default!; static T F2<T>(Expression<Func<T, T>> e) => default!; static void Main() { var x1 = F1(object (object x1) => x1); var x2 = F1(object (object? x2) => x2); var x3 = F1(object? (object x3) => x3); var x4 = F1(object? (object? x4) => x4); var y1 = F2(object (object y1) => y1); var y2 = F2(object (object? y2) => y2); var y3 = F2(object? (object y3) => y3); var y4 = F2(object? (object? y4) => y4); x1.ToString(); x2.ToString(); x3.ToString(); x4.ToString(); y1.ToString(); y2.ToString(); y3.ToString(); y4.ToString(); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,21): warning CS8622: Nullability of reference types in type of parameter 'x2' of 'lambda expression' doesn't match the target delegate 'Func<object, object>' (possibly because of nullability attributes). // var x2 = F1(object (object? x2) => x2); Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "object (object? x2) => x2").WithArguments("x2", "lambda expression", "System.Func<object, object>").WithLocation(11, 21), // (11,44): warning CS8603: Possible null reference return. // var x2 = F1(object (object? x2) => x2); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "x2").WithLocation(11, 44), // (12,21): warning CS8621: Nullability of reference types in return type of 'lambda expression' doesn't match the target delegate 'Func<object, object>' (possibly because of nullability attributes). // var x3 = F1(object? (object x3) => x3); Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "object? (object x3) => x3").WithArguments("lambda expression", "System.Func<object, object>").WithLocation(12, 21), // (15,21): warning CS8622: Nullability of reference types in type of parameter 'y2' of 'lambda expression' doesn't match the target delegate 'Func<object, object>' (possibly because of nullability attributes). // var y2 = F2(object (object? y2) => y2); Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "object (object? y2) => y2").WithArguments("y2", "lambda expression", "System.Func<object, object>").WithLocation(15, 21), // (15,44): warning CS8603: Possible null reference return. // var y2 = F2(object (object? y2) => y2); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "y2").WithLocation(15, 44), // (16,21): warning CS8621: Nullability of reference types in return type of 'lambda expression' doesn't match the target delegate 'Func<object, object>' (possibly because of nullability attributes). // var y3 = F2(object? (object y3) => y3); Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "object? (object y3) => y3").WithArguments("lambda expression", "System.Func<object, object>").WithLocation(16, 21), // (21,9): warning CS8602: Dereference of a possibly null reference. // x4.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x4").WithLocation(21, 9), // (25,9): warning CS8602: Dereference of a possibly null reference. // y4.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y4").WithLocation(25, 9)); } [Fact] public void Variance_01() { var source = @"using System; class Program { static void Main() { Action<string> a1 = s => { }; Action<string> a2 = (string s) => { }; Action<string> a3 = (object o) => { }; Action<string> a4 = (Action<object>)((object o) => { }); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,29): error CS1661: Cannot convert lambda expression to type 'Action<string>' because the parameter types do not match the delegate parameter types // Action<string> a3 = (object o) => { }; Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "(object o) => { }").WithArguments("lambda expression", "System.Action<string>").WithLocation(8, 29), // (8,37): error CS1678: Parameter 1 is declared as type 'object' but should be 'string' // Action<string> a3 = (object o) => { }; Diagnostic(ErrorCode.ERR_BadParamType, "o").WithArguments("1", "", "object", "", "string").WithLocation(8, 37)); } [Fact] public void Variance_02() { var source = @"using System; class Program { static void Main() { Func<object> f1 = () => string.Empty; Func<object> f2 = string () => string.Empty; Func<object> f3 = (Func<string>)(() => string.Empty); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,27): error CS8934: Cannot convert lambda expression to type 'Func<object>' because the return type does not match the delegate return type // Func<object> f2 = string () => string.Empty; Diagnostic(ErrorCode.ERR_CantConvAnonMethReturnType, "string () => string.Empty").WithArguments("lambda expression", "System.Func<object>").WithLocation(7, 27)); } [Fact] public void ImplicitlyTypedVariables_01() { var source = @"using System; class Program { static void Main() { var d1 = Main; Report(d1); var d2 = () => { }; Report(d2); var d3 = delegate () { }; Report(d3); } static void Report(Delegate d) => Console.WriteLine(d.GetDelegateTypeName()); }"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (6,18): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // var d1 = Main; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "Main").WithArguments("inferred delegate type", "10.0").WithLocation(6, 18), // (8,18): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // var d2 = () => { }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "() => { }").WithArguments("inferred delegate type", "10.0").WithLocation(8, 18), // (10,18): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // var d3 = delegate () { }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "delegate () { }").WithArguments("inferred delegate type", "10.0").WithLocation(10, 18)); comp = CreateCompilation(new[] { source, s_utils }, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: @"System.Action System.Action System.Action"); verifier.VerifyIL("Program.Main", @"{ // Code size 100 (0x64) .maxstack 2 .locals init (System.Action V_0, //d1 System.Action V_1, //d2 System.Action V_2) //d3 IL_0000: nop IL_0001: ldnull IL_0002: ldftn ""void Program.Main()"" IL_0008: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_000d: stloc.0 IL_000e: ldloc.0 IL_000f: call ""void Program.Report(System.Delegate)"" IL_0014: nop IL_0015: ldsfld ""System.Action Program.<>c.<>9__0_0"" IL_001a: dup IL_001b: brtrue.s IL_0034 IL_001d: pop IL_001e: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0023: ldftn ""void Program.<>c.<Main>b__0_0()"" IL_0029: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_002e: dup IL_002f: stsfld ""System.Action Program.<>c.<>9__0_0"" IL_0034: stloc.1 IL_0035: ldloc.1 IL_0036: call ""void Program.Report(System.Delegate)"" IL_003b: nop IL_003c: ldsfld ""System.Action Program.<>c.<>9__0_1"" IL_0041: dup IL_0042: brtrue.s IL_005b IL_0044: pop IL_0045: ldsfld ""Program.<>c Program.<>c.<>9"" IL_004a: ldftn ""void Program.<>c.<Main>b__0_1()"" IL_0050: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_0055: dup IL_0056: stsfld ""System.Action Program.<>c.<>9__0_1"" IL_005b: stloc.2 IL_005c: ldloc.2 IL_005d: call ""void Program.Report(System.Delegate)"" IL_0062: nop IL_0063: ret }"); } [Fact] public void ImplicitlyTypedVariables_02() { var source = @"var d1 = object.ReferenceEquals; var d2 = () => { }; var d3 = delegate () { }; "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9.WithKind(SourceCodeKind.Script)); comp.VerifyDiagnostics( // (1,10): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // var d1 = object.ReferenceEquals; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "object.ReferenceEquals").WithArguments("inferred delegate type", "10.0").WithLocation(1, 10), // (2,10): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // var d2 = () => { }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "() => { }").WithArguments("inferred delegate type", "10.0").WithLocation(2, 10), // (3,10): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // var d3 = delegate () { }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "delegate () { }").WithArguments("inferred delegate type", "10.0").WithLocation(3, 10)); comp = CreateCompilation(source, parseOptions: TestOptions.Regular10.WithKind(SourceCodeKind.Script)); comp.VerifyDiagnostics(); } [Fact] public void ImplicitlyTypedVariables_03() { var source = @"class Program { static void Main() { ref var d1 = Main; ref var d2 = () => { }; ref var d3 = delegate () { }; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,17): error CS8172: Cannot initialize a by-reference variable with a value // ref var d1 = Main; Diagnostic(ErrorCode.ERR_InitializeByReferenceVariableWithValue, "d1 = Main").WithLocation(5, 17), // (5,22): error CS1657: Cannot use 'Main' as a ref or out value because it is a 'method group' // ref var d1 = Main; Diagnostic(ErrorCode.ERR_RefReadonlyLocalCause, "Main").WithArguments("Main", "method group").WithLocation(5, 22), // (6,17): error CS8172: Cannot initialize a by-reference variable with a value // ref var d2 = () => { }; Diagnostic(ErrorCode.ERR_InitializeByReferenceVariableWithValue, "d2 = () => { }").WithLocation(6, 17), // (6,22): error CS1510: A ref or out value must be an assignable variable // ref var d2 = () => { }; Diagnostic(ErrorCode.ERR_RefLvalueExpected, "() => { }").WithLocation(6, 22), // (7,17): error CS8172: Cannot initialize a by-reference variable with a value // ref var d3 = delegate () { }; Diagnostic(ErrorCode.ERR_InitializeByReferenceVariableWithValue, "d3 = delegate () { }").WithLocation(7, 17), // (7,22): error CS1510: A ref or out value must be an assignable variable // ref var d3 = delegate () { }; Diagnostic(ErrorCode.ERR_RefLvalueExpected, "delegate () { }").WithLocation(7, 22)); } [Fact] public void ImplicitlyTypedVariables_04() { var source = @"class Program { static void Main() { using var d1 = Main; using var d2 = () => { }; using var d3 = delegate () { }; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,9): error CS1674: 'Action': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using var d1 = Main; Diagnostic(ErrorCode.ERR_NoConvToIDisp, "using var d1 = Main;").WithArguments("System.Action").WithLocation(5, 9), // (6,9): error CS1674: 'Action': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using var d2 = () => { }; Diagnostic(ErrorCode.ERR_NoConvToIDisp, "using var d2 = () => { };").WithArguments("System.Action").WithLocation(6, 9), // (7,9): error CS1674: 'Action': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using var d3 = delegate () { }; Diagnostic(ErrorCode.ERR_NoConvToIDisp, "using var d3 = delegate () { };").WithArguments("System.Action").WithLocation(7, 9)); } [Fact] public void ImplicitlyTypedVariables_05() { var source = @"class Program { static void Main() { foreach (var d1 in Main) { } foreach (var d2 in () => { }) { } foreach (var d3 in delegate () { }) { } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,28): error CS0446: Foreach cannot operate on a 'method group'. Did you intend to invoke the 'method group'? // foreach (var d1 in Main) { } Diagnostic(ErrorCode.ERR_AnonMethGrpInForEach, "Main").WithArguments("method group").WithLocation(5, 28), // (6,28): error CS0446: Foreach cannot operate on a 'lambda expression'. Did you intend to invoke the 'lambda expression'? // foreach (var d2 in () => { }) { } Diagnostic(ErrorCode.ERR_AnonMethGrpInForEach, "() => { }").WithArguments("lambda expression").WithLocation(6, 28), // (7,28): error CS0446: Foreach cannot operate on a 'anonymous method'. Did you intend to invoke the 'anonymous method'? // foreach (var d3 in delegate () { }) { } Diagnostic(ErrorCode.ERR_AnonMethGrpInForEach, "delegate () { }").WithArguments("anonymous method").WithLocation(7, 28)); } [Fact] public void ImplicitlyTypedVariables_06() { var source = @"using System; class Program { static void Main() { Func<int> f; var d1 = Main; f = d1; var d2 = object (int x) => x; f = d2; var d3 = delegate () { return string.Empty; }; f = d3; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,13): error CS0029: Cannot implicitly convert type 'System.Action' to 'System.Func<int>' // f = d1; Diagnostic(ErrorCode.ERR_NoImplicitConv, "d1").WithArguments("System.Action", "System.Func<int>").WithLocation(8, 13), // (10,13): error CS0029: Cannot implicitly convert type 'System.Func<int, object>' to 'System.Func<int>' // f = d2; Diagnostic(ErrorCode.ERR_NoImplicitConv, "d2").WithArguments("System.Func<int, object>", "System.Func<int>").WithLocation(10, 13), // (12,13): error CS0029: Cannot implicitly convert type 'System.Func<string>' to 'System.Func<int>' // f = d3; Diagnostic(ErrorCode.ERR_NoImplicitConv, "d3").WithArguments("System.Func<string>", "System.Func<int>").WithLocation(12, 13)); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var variables = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(v => v.Initializer != null); var expectedInfo = new (string?, string?, string?)[] { ("System.Action d1", null, "System.Action"), ("System.Func<System.Int32, System.Object> d2", null, "System.Func<System.Int32, System.Object>"), ("System.Func<System.String> d3", null, "System.Func<System.String>"), }; AssertEx.Equal(expectedInfo, variables.Select(v => getVariableInfo(model, v))); static (string?, string?, string?) getVariableInfo(SemanticModel model, VariableDeclaratorSyntax variable) { var symbol = model.GetDeclaredSymbol(variable); var typeInfo = model.GetTypeInfo(variable.Initializer!.Value); return (symbol?.ToTestDisplayString(), typeInfo.Type?.ToTestDisplayString(), typeInfo.ConvertedType?.ToTestDisplayString()); } } [Fact] public void ImplicitlyTypedVariables_07() { var source = @"class Program { static void Main() { var t = (Main, () => { }); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,13): error CS0815: Cannot assign (method group, lambda expression) to an implicitly-typed variable // var t = (Main, () => { }); Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, "t = (Main, () => { })").WithArguments("(method group, lambda expression)").WithLocation(5, 13)); } [Fact] public void ImplicitlyTypedVariables_08() { var source = @"class Program { static void Main() { (var x1, var y1) = Main; var (x2, y2) = () => { }; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,14): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x1'. // (var x1, var y1) = Main; Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x1").WithArguments("x1").WithLocation(5, 14), // (5,22): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y1'. // (var x1, var y1) = Main; Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y1").WithArguments("y1").WithLocation(5, 22), // (5,28): error CS8131: Deconstruct assignment requires an expression with a type on the right-hand-side. // (var x1, var y1) = Main; Diagnostic(ErrorCode.ERR_DeconstructRequiresExpression, "Main").WithLocation(5, 28), // (6,14): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x2'. // var (x2, y2) = () => { }; Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x2").WithArguments("x2").WithLocation(6, 14), // (6,18): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y2'. // var (x2, y2) = () => { }; Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y2").WithArguments("y2").WithLocation(6, 18), // (6,24): error CS8131: Deconstruct assignment requires an expression with a type on the right-hand-side. // var (x2, y2) = () => { }; Diagnostic(ErrorCode.ERR_DeconstructRequiresExpression, "() => { }").WithLocation(6, 24)); } [Fact] public void ImplicitlyTypedVariables_09() { var source = @"class Program { static void Main() { var (x, y) = (Main, () => { }); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,14): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x'. // var (x, y) = (Main, () => { }); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x").WithArguments("x").WithLocation(5, 14), // (5,17): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y'. // var (x, y) = (Main, () => { }); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y").WithArguments("y").WithLocation(5, 17)); } [Fact] public void ImplicitlyTypedVariables_10() { var source = @"using System; class Program { static void Main() { (var x1, Action y1) = (Main, null); (Action x2, var y2) = (null, () => { }); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,14): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x1'. // (var x1, Action y1) = (Main, null); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x1").WithArguments("x1").WithLocation(6, 14), // (7,25): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y2'. // (Action x2, var y2) = (null, () => { }); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y2").WithArguments("y2").WithLocation(7, 25)); } [Fact] public void ImplicitlyTypedVariables_11() { var source = @"class Program { static void F(object o) { } static void F(int i) { } static void Main() { var d1 = F; var d2 = x => x; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,18): error CS8917: The delegate type could not be inferred. // var d1 = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F").WithLocation(7, 18), // (8,18): error CS8917: The delegate type could not be inferred. // var d2 = x => x; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(8, 18)); } [Fact] public void ImplicitlyTypedVariables_12() { var source = @"class Program { static void F(ref int i) { } static void Main() { var d1 = F; var d2 = (ref int x) => x; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void ImplicitlyTypedVariables_13() { var source = @"using System; class Program { static int F() => 0; static void Main() { var d1 = (F); Report(d1); var d2 = (object (int x) => x); Report(d2); var d3 = (delegate () { return string.Empty; }); Report(d3); } static void Report(Delegate d) => Console.WriteLine(d.GetDelegateTypeName()); }"; CompileAndVerify(new[] { source, s_utils }, options: TestOptions.DebugExe, expectedOutput: @"System.Func<System.Int32> System.Func<System.Int32, System.Object> System.Func<System.String>"); } [Fact] public void ImplicitlyTypedVariables_14() { var source = @"delegate void D(string s); class Program { static void Main() { (D x, var y) = (() => string.Empty, () => string.Empty); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,19): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y'. // (D x, var y) = (() => string.Empty, () => string.Empty); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y").WithArguments("y").WithLocation(6, 19)); } [Fact] public void ImplicitlyTypedVariables_UseSiteErrors() { var source = @"class Program { static void F(object o) { } static void Main() { var d1 = F; var d2 = () => 1; } }"; var comp = CreateEmptyCompilation(source, new[] { GetCorlibWithInvalidActionAndFuncOfT() }); comp.VerifyDiagnostics( // (6,18): error CS0648: 'Action<T>' is a type not supported by the language // var d1 = F; Diagnostic(ErrorCode.ERR_BogusType, "F").WithArguments("System.Action<T>").WithLocation(6, 18), // (7,18): error CS0648: 'Func<T>' is a type not supported by the language // var d2 = () => 1; Diagnostic(ErrorCode.ERR_BogusType, "() => 1").WithArguments("System.Func<T>").WithLocation(7, 18)); } [Fact] public void BinaryOperator_01() { var source = @"using System; class Program { static void Main() { var b1 = (() => { }) == null; var b2 = null == Main; var b3 = Main == (() => { }); Console.WriteLine((b1, b2, b3)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,18): error CS0019: Operator '==' cannot be applied to operands of type 'lambda expression' and '<null>' // var b1 = (() => { }) == null; Diagnostic(ErrorCode.ERR_BadBinaryOps, "(() => { }) == null").WithArguments("==", "lambda expression", "<null>").WithLocation(6, 18), // (7,18): error CS0019: Operator '==' cannot be applied to operands of type '<null>' and 'method group' // var b2 = null == Main; Diagnostic(ErrorCode.ERR_BadBinaryOps, "null == Main").WithArguments("==", "<null>", "method group").WithLocation(7, 18), // (8,18): error CS0019: Operator '==' cannot be applied to operands of type 'method group' and 'lambda expression' // var b3 = Main == (() => { }); Diagnostic(ErrorCode.ERR_BadBinaryOps, "Main == (() => { })").WithArguments("==", "method group", "lambda expression").WithLocation(8, 18)); var expectedOutput = @"(False, False, False)"; CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void BinaryOperator_02() { var source = @"using System; using System.Linq.Expressions; class C { public static C operator+(C c, Delegate d) { Console.WriteLine(""operator+(C c, Delegate d)""); return c; } public static C operator+(C c, Expression e) { Console.WriteLine(""operator=(C c, Expression e)""); return c; } static void Main() { var c = new C(); _ = c + Main; _ = c + (() => 1); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (10,13): error CS0019: Operator '+' cannot be applied to operands of type 'C' and 'method group' // _ = c + Main; Diagnostic(ErrorCode.ERR_BadBinaryOps, "c + Main").WithArguments("+", "C", "method group").WithLocation(10, 13), // (11,13): error CS0019: Operator '+' cannot be applied to operands of type 'C' and 'lambda expression' // _ = c + (() => 1); Diagnostic(ErrorCode.ERR_BadBinaryOps, "c + (() => 1)").WithArguments("+", "C", "lambda expression").WithLocation(11, 13)); var expectedDiagnostics = new[] { // (10,13): error CS0034: Operator '+' is ambiguous on operands of type 'C' and 'method group' // _ = c + Main; Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "c + Main").WithArguments("+", "C", "method group").WithLocation(10, 13), // (11,13): error CS0034: Operator '+' is ambiguous on operands of type 'C' and 'lambda expression' // _ = c + (() => 1); Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "c + (() => 1)").WithArguments("+", "C", "lambda expression").WithLocation(11, 13) }; comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void BinaryOperator_03() { var source = @"using System; class C { public static C operator+(C c, Delegate d) { Console.WriteLine(""operator+(C c, Delegate d)""); return c; } public static C operator+(C c, object o) { Console.WriteLine(""operator+(C c, object o)""); return c; } static int F() => 0; static void Main() { var c = new C(); _ = c + F; _ = c + (() => 1); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (10,13): error CS0019: Operator '+' cannot be applied to operands of type 'C' and 'method group' // _ = c + F; Diagnostic(ErrorCode.ERR_BadBinaryOps, "c + F").WithArguments("+", "C", "method group").WithLocation(10, 13), // (11,13): error CS0019: Operator '+' cannot be applied to operands of type 'C' and 'lambda expression' // _ = c + (() => 1); Diagnostic(ErrorCode.ERR_BadBinaryOps, "c + (() => 1)").WithArguments("+", "C", "lambda expression").WithLocation(11, 13)); var expectedOutput = @"operator+(C c, Delegate d) operator+(C c, Delegate d) "; CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void BinaryOperator_04() { var source = @"using System; using System.Linq.Expressions; class C { public static C operator+(C c, Expression e) { Console.WriteLine(""operator+(C c, Expression e)""); return c; } public static C operator+(C c, object o) { Console.WriteLine(""operator+(C c, object o)""); return c; } static int F() => 0; static void Main() { var c = new C(); _ = c + F; _ = c + (() => 1); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (11,13): error CS0019: Operator '+' cannot be applied to operands of type 'C' and 'method group' // _ = c + F; Diagnostic(ErrorCode.ERR_BadBinaryOps, "c + F").WithArguments("+", "C", "method group").WithLocation(11, 13), // (12,13): error CS0019: Operator '+' cannot be applied to operands of type 'C' and 'lambda expression' // _ = c + (() => 1); Diagnostic(ErrorCode.ERR_BadBinaryOps, "c + (() => 1)").WithArguments("+", "C", "lambda expression").WithLocation(12, 13)); var expectedDiagnostics = new[] { // (11,17): error CS0428: Cannot convert method group 'F' to non-delegate type 'Expression'. Did you intend to invoke the method? // _ = c + F; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "System.Linq.Expressions.Expression").WithLocation(11, 17) }; comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void BinaryOperator_05() { var source = @"using System; class C { public static C operator+(C c, Delegate d) { Console.WriteLine(""operator+(C c, Delegate d)""); return c; } public static C operator+(C c, Func<object> f) { Console.WriteLine(""operator+(C c, Func<object> f)""); return c; } static int F() => 0; static void Main() { var c = new C(); _ = c + F; _ = c + (() => 1); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (10,13): error CS0019: Operator '+' cannot be applied to operands of type 'C' and 'method group' // _ = c + F; Diagnostic(ErrorCode.ERR_BadBinaryOps, "c + F").WithArguments("+", "C", "method group").WithLocation(10, 13)); var expectedOutput = @"operator+(C c, Delegate d) operator+(C c, Func<object> f) "; CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void BinaryOperator_06() { var source = @"using System; using System.Linq.Expressions; class C { public static C operator+(C c, Expression e) { Console.WriteLine(""operator+(C c, Expression e)""); return c; } public static C operator+(C c, Func<object> f) { Console.WriteLine(""operator+(C c, Func<object> f)""); return c; } static void Main() { var c = new C(); _ = c + (() => new object()); _ = c + (() => 1); } }"; var expectedOutput = @"operator+(C c, Func<object> f) operator+(C c, Func<object> f) "; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void BinaryOperator_07() { var source = @"using System; using System.Linq.Expressions; class C { public static C operator+(C c, Expression e) { Console.WriteLine(""operator+(C c, Expression e)""); return c; } public static C operator+(C c, Func<object> f) { Console.WriteLine(""operator+(C c, Func<object> f)""); return c; } static int F() => 0; static void Main() { var c = new C(); _ = c + F; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (11,13): error CS0019: Operator '+' cannot be applied to operands of type 'C' and 'method group' // _ = c + F; Diagnostic(ErrorCode.ERR_BadBinaryOps, "c + F").WithArguments("+", "C", "method group").WithLocation(11, 13)); var expectedDiagnostics = new[] { // (11,17): error CS0428: Cannot convert method group 'F' to non-delegate type 'Expression'. Did you intend to invoke the method? // _ = c + F; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "System.Linq.Expressions.Expression").WithLocation(11, 17) }; comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void BinaryOperator_08() { var source = @"using System; class A { public static A operator+(A a, Func<int> f) { Console.WriteLine(""operator+(A a, Func<int> f)""); return a; } } class B : A { public static B operator+(B b, Delegate d) { Console.WriteLine(""operator+(B b, Delegate d)""); return b; } static int F() => 1; static void Main() { var b = new B(); _ = b + F; _ = b + (() => 2); } }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: @"operator+(A a, Func<int> f) operator+(A a, Func<int> f) "); // Breaking change from C#9. string expectedOutput = @"operator+(B b, Delegate d) operator+(B b, Delegate d) "; CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } /// <summary> /// Ensure the conversion group containing the implicit /// conversion is handled correctly in NullableWalker. /// </summary> [Fact] public void NullableAnalysis_01() { var source = @"#nullable enable class Program { static void Main() { System.Delegate d; d = Main; d = () => { }; d = delegate () { }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics(); } /// <summary> /// Ensure the conversion group containing the explicit /// conversion is handled correctly in NullableWalker. /// </summary> [Fact] public void NullableAnalysis_02() { var source = @"#nullable enable class Program { static void Main() { object o; o = (System.Delegate)Main; o = (System.Delegate)(() => { }); o = (System.Delegate)(delegate () { }); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics(); } [Fact] public void SynthesizedDelegateTypes_01() { var source = @"using System; class Program { static void M1<T>(T t) { var d = (ref T t) => t; Report(d); Console.WriteLine(d(ref t)); } static void M2<U>(U u) where U : struct { var d = (ref U u) => u; Report(d); Console.WriteLine(d(ref u)); } static void M3(double value) { var d = (ref double d) => d; Report(d); Console.WriteLine(d(ref value)); } static void Main() { M1(41); M2(42f); M2(43d); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: @"<>F{00000001}`2[System.Int32,System.Int32] 41 <>F{00000001}`2[System.Single,System.Single] 42 <>F{00000001}`2[System.Double,System.Double] 43 "); verifier.VerifyIL("Program.M1<T>", @"{ // Code size 55 (0x37) .maxstack 2 IL_0000: ldsfld ""<>F{00000001}<T, T> Program.<>c__0<T>.<>9__0_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""Program.<>c__0<T> Program.<>c__0<T>.<>9"" IL_000e: ldftn ""T Program.<>c__0<T>.<M1>b__0_0(ref T)"" IL_0014: newobj ""<>F{00000001}<T, T>..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""<>F{00000001}<T, T> Program.<>c__0<T>.<>9__0_0"" IL_001f: dup IL_0020: call ""void Program.Report(System.Delegate)"" IL_0025: ldarga.s V_0 IL_0027: callvirt ""T <>F{00000001}<T, T>.Invoke(ref T)"" IL_002c: box ""T"" IL_0031: call ""void System.Console.WriteLine(object)"" IL_0036: ret }"); verifier.VerifyIL("Program.M2<U>", @"{ // Code size 55 (0x37) .maxstack 2 IL_0000: ldsfld ""<>F{00000001}<U, U> Program.<>c__1<U>.<>9__1_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""Program.<>c__1<U> Program.<>c__1<U>.<>9"" IL_000e: ldftn ""U Program.<>c__1<U>.<M2>b__1_0(ref U)"" IL_0014: newobj ""<>F{00000001}<U, U>..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""<>F{00000001}<U, U> Program.<>c__1<U>.<>9__1_0"" IL_001f: dup IL_0020: call ""void Program.Report(System.Delegate)"" IL_0025: ldarga.s V_0 IL_0027: callvirt ""U <>F{00000001}<U, U>.Invoke(ref U)"" IL_002c: box ""U"" IL_0031: call ""void System.Console.WriteLine(object)"" IL_0036: ret }"); verifier.VerifyIL("Program.M3", @"{ // Code size 50 (0x32) .maxstack 2 IL_0000: ldsfld ""<>F{00000001}<double, double> Program.<>c.<>9__2_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""Program.<>c Program.<>c.<>9"" IL_000e: ldftn ""double Program.<>c.<M3>b__2_0(ref double)"" IL_0014: newobj ""<>F{00000001}<double, double>..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""<>F{00000001}<double, double> Program.<>c.<>9__2_0"" IL_001f: dup IL_0020: call ""void Program.Report(System.Delegate)"" IL_0025: ldarga.s V_0 IL_0027: callvirt ""double <>F{00000001}<double, double>.Invoke(ref double)"" IL_002c: call ""void System.Console.WriteLine(double)"" IL_0031: ret }"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var nodes = tree.GetRoot().DescendantNodes(); var variables = nodes.OfType<VariableDeclaratorSyntax>().Where(v => v.Identifier.Text == "d").ToArray(); Assert.Equal(3, variables.Length); VerifyLocalDelegateType(model, variables[0], "<>F{00000001}<T, T> d", "T <>F{00000001}<T, T>.Invoke(ref T)"); VerifyLocalDelegateType(model, variables[1], "<>F{00000001}<U, U> d", "U <>F{00000001}<U, U>.Invoke(ref U)"); VerifyLocalDelegateType(model, variables[2], "<>F{00000001}<System.Double, System.Double> d", "System.Double <>F{00000001}<System.Double, System.Double>.Invoke(ref System.Double)"); var identifiers = nodes.OfType<InvocationExpressionSyntax>().Where(i => i.Expression is IdentifierNameSyntax id && id.Identifier.Text == "Report").Select(i => i.ArgumentList.Arguments[0].Expression).ToArray(); Assert.Equal(3, identifiers.Length); VerifyExpressionType(model, identifiers[0], "<>F{00000001}<T, T> d", "<>F{00000001}<T, T>"); VerifyExpressionType(model, identifiers[1], "<>F{00000001}<U, U> d", "<>F{00000001}<U, U>"); VerifyExpressionType(model, identifiers[2], "<>F{00000001}<System.Double, System.Double> d", "<>F{00000001}<System.Double, System.Double>"); } [Fact] public void SynthesizedDelegateTypes_02() { var source = @"using System; class Program { static void M1(A a, int value) { var d = a.F1; d() = value; } static void M2(B b, float value) { var d = b.F2; d() = value; } static void Main() { var a = new A(); M1(a, 41); var b = new B(); M2(b, 42f); Console.WriteLine((a._f, b._f)); } } class A { public int _f; public ref int F1() => ref _f; } class B { public float _f; } static class E { public static ref float F2(this B b) => ref b._f; }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: @"(41, 42)"); verifier.VerifyIL("Program.M1", @"{ // Code size 20 (0x14) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldftn ""ref int A.F1()"" IL_0007: newobj ""<>F{00000001}<int>..ctor(object, System.IntPtr)"" IL_000c: callvirt ""ref int <>F{00000001}<int>.Invoke()"" IL_0011: ldarg.1 IL_0012: stind.i4 IL_0013: ret }"); verifier.VerifyIL("Program.M2", @"{ // Code size 20 (0x14) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldftn ""ref float E.F2(B)"" IL_0007: newobj ""<>F{00000001}<float>..ctor(object, System.IntPtr)"" IL_000c: callvirt ""ref float <>F{00000001}<float>.Invoke()"" IL_0011: ldarg.1 IL_0012: stind.r4 IL_0013: ret }"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var variables = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(v => v.Identifier.Text == "d").ToArray(); Assert.Equal(2, variables.Length); VerifyLocalDelegateType(model, variables[0], "<>F{00000001}<System.Int32> d", "ref System.Int32 <>F{00000001}<System.Int32>.Invoke()"); VerifyLocalDelegateType(model, variables[1], "<>F{00000001}<System.Single> d", "ref System.Single <>F{00000001}<System.Single>.Invoke()"); } [Fact] public void SynthesizedDelegateTypes_03() { var source = @"using System; class Program { static void Main() { Report((ref int x, int y) => { }); Report((int x, ref int y) => { }); Report((ref float x, int y) => { }); Report((float x, ref int y) => { }); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: @"<>A{00000001}`2[System.Int32,System.Int32] <>A{00000004}`2[System.Int32,System.Int32] <>A{00000001}`2[System.Single,System.Int32] <>A{00000004}`2[System.Single,System.Int32] "); verifier.VerifyIL("Program.Main", @"{ // Code size 145 (0x91) .maxstack 2 IL_0000: ldsfld ""<>A{00000001}<int, int> Program.<>c.<>9__0_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""Program.<>c Program.<>c.<>9"" IL_000e: ldftn ""void Program.<>c.<Main>b__0_0(ref int, int)"" IL_0014: newobj ""<>A{00000001}<int, int>..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""<>A{00000001}<int, int> Program.<>c.<>9__0_0"" IL_001f: call ""void Program.Report(System.Delegate)"" IL_0024: ldsfld ""<>A{00000004}<int, int> Program.<>c.<>9__0_1"" IL_0029: dup IL_002a: brtrue.s IL_0043 IL_002c: pop IL_002d: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0032: ldftn ""void Program.<>c.<Main>b__0_1(int, ref int)"" IL_0038: newobj ""<>A{00000004}<int, int>..ctor(object, System.IntPtr)"" IL_003d: dup IL_003e: stsfld ""<>A{00000004}<int, int> Program.<>c.<>9__0_1"" IL_0043: call ""void Program.Report(System.Delegate)"" IL_0048: ldsfld ""<>A{00000001}<float, int> Program.<>c.<>9__0_2"" IL_004d: dup IL_004e: brtrue.s IL_0067 IL_0050: pop IL_0051: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0056: ldftn ""void Program.<>c.<Main>b__0_2(ref float, int)"" IL_005c: newobj ""<>A{00000001}<float, int>..ctor(object, System.IntPtr)"" IL_0061: dup IL_0062: stsfld ""<>A{00000001}<float, int> Program.<>c.<>9__0_2"" IL_0067: call ""void Program.Report(System.Delegate)"" IL_006c: ldsfld ""<>A{00000004}<float, int> Program.<>c.<>9__0_3"" IL_0071: dup IL_0072: brtrue.s IL_008b IL_0074: pop IL_0075: ldsfld ""Program.<>c Program.<>c.<>9"" IL_007a: ldftn ""void Program.<>c.<Main>b__0_3(float, ref int)"" IL_0080: newobj ""<>A{00000004}<float, int>..ctor(object, System.IntPtr)"" IL_0085: dup IL_0086: stsfld ""<>A{00000004}<float, int> Program.<>c.<>9__0_3"" IL_008b: call ""void Program.Report(System.Delegate)"" IL_0090: ret }"); } [Fact] public void SynthesizedDelegateTypes_04() { var source = @"using System; class Program { static int i = 0; static void Main() { Report(int () => i); Report((ref int () => ref i)); Report((ref readonly int () => ref i)); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: @"System.Func`1[System.Int32] <>F{00000001}`1[System.Int32] <>F{00000003}`1[System.Int32] "); verifier.VerifyIL("Program.Main", @"{ // Code size 109 (0x6d) .maxstack 2 IL_0000: ldsfld ""System.Func<int> Program.<>c.<>9__1_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""Program.<>c Program.<>c.<>9"" IL_000e: ldftn ""int Program.<>c.<Main>b__1_0()"" IL_0014: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""System.Func<int> Program.<>c.<>9__1_0"" IL_001f: call ""void Program.Report(System.Delegate)"" IL_0024: ldsfld ""<>F{00000001}<int> Program.<>c.<>9__1_1"" IL_0029: dup IL_002a: brtrue.s IL_0043 IL_002c: pop IL_002d: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0032: ldftn ""ref int Program.<>c.<Main>b__1_1()"" IL_0038: newobj ""<>F{00000001}<int>..ctor(object, System.IntPtr)"" IL_003d: dup IL_003e: stsfld ""<>F{00000001}<int> Program.<>c.<>9__1_1"" IL_0043: call ""void Program.Report(System.Delegate)"" IL_0048: ldsfld ""<>F{00000003}<int> Program.<>c.<>9__1_2"" IL_004d: dup IL_004e: brtrue.s IL_0067 IL_0050: pop IL_0051: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0056: ldftn ""ref readonly int Program.<>c.<Main>b__1_2()"" IL_005c: newobj ""<>F{00000003}<int>..ctor(object, System.IntPtr)"" IL_0061: dup IL_0062: stsfld ""<>F{00000003}<int> Program.<>c.<>9__1_2"" IL_0067: call ""void Program.Report(System.Delegate)"" IL_006c: ret }"); } [Fact] public void SynthesizedDelegateTypes_05() { var source = @"using System; class Program { static int i = 0; static int F1() => i; static ref int F2() => ref i; static ref readonly int F3() => ref i; static void Main() { Report(F1); Report(F2); Report(F3); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: @"System.Func`1[System.Int32] <>F{00000001}`1[System.Int32] <>F{00000003}`1[System.Int32] "); verifier.VerifyIL("Program.Main", @"{ // Code size 52 (0x34) .maxstack 2 IL_0000: ldnull IL_0001: ldftn ""int Program.F1()"" IL_0007: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_000c: call ""void Program.Report(System.Delegate)"" IL_0011: ldnull IL_0012: ldftn ""ref int Program.F2()"" IL_0018: newobj ""<>F{00000001}<int>..ctor(object, System.IntPtr)"" IL_001d: call ""void Program.Report(System.Delegate)"" IL_0022: ldnull IL_0023: ldftn ""ref readonly int Program.F3()"" IL_0029: newobj ""<>F{00000003}<int>..ctor(object, System.IntPtr)"" IL_002e: call ""void Program.Report(System.Delegate)"" IL_0033: ret }"); } [Fact] public void SynthesizedDelegateTypes_06() { var source = @"using System; class Program { static int i = 0; static int F1() => i; static ref int F2() => ref i; static ref readonly int F3() => ref i; static void Main() { var d1 = F1; var d2 = F2; var d3 = F3; Report(d1); Report(d2); Report(d3); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"System.Func`1[System.Int32] <>F{00000001}`1[System.Int32] <>F{00000003}`1[System.Int32] "); } [Fact] public void SynthesizedDelegateTypes_07() { var source = @"using System; class Program { static void Main() { Report(int (ref int i) => i); Report((ref int (ref int i) => ref i)); Report((ref readonly int (ref int i) => ref i)); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput: @"<>F{00000001}`2[System.Int32,System.Int32] <>F{00000005}`2[System.Int32,System.Int32] <>F{0000000d}`2[System.Int32,System.Int32] "); verifier.VerifyIL("Program.Main", @"{ // Code size 109 (0x6d) .maxstack 2 IL_0000: ldsfld ""<>F{00000001}<int, int> Program.<>c.<>9__0_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""Program.<>c Program.<>c.<>9"" IL_000e: ldftn ""int Program.<>c.<Main>b__0_0(ref int)"" IL_0014: newobj ""<>F{00000001}<int, int>..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""<>F{00000001}<int, int> Program.<>c.<>9__0_0"" IL_001f: call ""void Program.Report(System.Delegate)"" IL_0024: ldsfld ""<>F{00000005}<int, int> Program.<>c.<>9__0_1"" IL_0029: dup IL_002a: brtrue.s IL_0043 IL_002c: pop IL_002d: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0032: ldftn ""ref int Program.<>c.<Main>b__0_1(ref int)"" IL_0038: newobj ""<>F{00000005}<int, int>..ctor(object, System.IntPtr)"" IL_003d: dup IL_003e: stsfld ""<>F{00000005}<int, int> Program.<>c.<>9__0_1"" IL_0043: call ""void Program.Report(System.Delegate)"" IL_0048: ldsfld ""<>F{0000000d}<int, int> Program.<>c.<>9__0_2"" IL_004d: dup IL_004e: brtrue.s IL_0067 IL_0050: pop IL_0051: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0056: ldftn ""ref readonly int Program.<>c.<Main>b__0_2(ref int)"" IL_005c: newobj ""<>F{0000000d}<int, int>..ctor(object, System.IntPtr)"" IL_0061: dup IL_0062: stsfld ""<>F{0000000d}<int, int> Program.<>c.<>9__0_2"" IL_0067: call ""void Program.Report(System.Delegate)"" IL_006c: ret }"); } [Fact] public void SynthesizedDelegateTypes_08() { var source = @"#pragma warning disable 414 using System; class Program { static int i = 0; static void Main() { Report((int i) => { }); Report((out int i) => { i = 0; }); Report((ref int i) => { }); Report((in int i) => { }); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: @"System.Action`1[System.Int32] <>A{00000002}`1[System.Int32] <>A{00000001}`1[System.Int32] <>A{00000003}`1[System.Int32] "); verifier.VerifyIL("Program.Main", @"{ // Code size 145 (0x91) .maxstack 2 IL_0000: ldsfld ""System.Action<int> Program.<>c.<>9__1_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""Program.<>c Program.<>c.<>9"" IL_000e: ldftn ""void Program.<>c.<Main>b__1_0(int)"" IL_0014: newobj ""System.Action<int>..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""System.Action<int> Program.<>c.<>9__1_0"" IL_001f: call ""void Program.Report(System.Delegate)"" IL_0024: ldsfld ""<>A{00000002}<int> Program.<>c.<>9__1_1"" IL_0029: dup IL_002a: brtrue.s IL_0043 IL_002c: pop IL_002d: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0032: ldftn ""void Program.<>c.<Main>b__1_1(out int)"" IL_0038: newobj ""<>A{00000002}<int>..ctor(object, System.IntPtr)"" IL_003d: dup IL_003e: stsfld ""<>A{00000002}<int> Program.<>c.<>9__1_1"" IL_0043: call ""void Program.Report(System.Delegate)"" IL_0048: ldsfld ""<>A{00000001}<int> Program.<>c.<>9__1_2"" IL_004d: dup IL_004e: brtrue.s IL_0067 IL_0050: pop IL_0051: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0056: ldftn ""void Program.<>c.<Main>b__1_2(ref int)"" IL_005c: newobj ""<>A{00000001}<int>..ctor(object, System.IntPtr)"" IL_0061: dup IL_0062: stsfld ""<>A{00000001}<int> Program.<>c.<>9__1_2"" IL_0067: call ""void Program.Report(System.Delegate)"" IL_006c: ldsfld ""<>A{00000003}<int> Program.<>c.<>9__1_3"" IL_0071: dup IL_0072: brtrue.s IL_008b IL_0074: pop IL_0075: ldsfld ""Program.<>c Program.<>c.<>9"" IL_007a: ldftn ""void Program.<>c.<Main>b__1_3(in int)"" IL_0080: newobj ""<>A{00000003}<int>..ctor(object, System.IntPtr)"" IL_0085: dup IL_0086: stsfld ""<>A{00000003}<int> Program.<>c.<>9__1_3"" IL_008b: call ""void Program.Report(System.Delegate)"" IL_0090: ret }"); } [Fact] public void SynthesizedDelegateTypes_09() { var source = @"#pragma warning disable 414 using System; class Program { static void M1(int i) { } static void M2(out int i) { i = 0; } static void M3(ref int i) { } static void M4(in int i) { } static void Main() { Report(M1); Report(M2); Report(M3); Report(M4); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: @"System.Action`1[System.Int32] <>A{00000002}`1[System.Int32] <>A{00000001}`1[System.Int32] <>A{00000003}`1[System.Int32] "); verifier.VerifyIL("Program.Main", @"{ // Code size 69 (0x45) .maxstack 2 IL_0000: ldnull IL_0001: ldftn ""void Program.M1(int)"" IL_0007: newobj ""System.Action<int>..ctor(object, System.IntPtr)"" IL_000c: call ""void Program.Report(System.Delegate)"" IL_0011: ldnull IL_0012: ldftn ""void Program.M2(out int)"" IL_0018: newobj ""<>A{00000002}<int>..ctor(object, System.IntPtr)"" IL_001d: call ""void Program.Report(System.Delegate)"" IL_0022: ldnull IL_0023: ldftn ""void Program.M3(ref int)"" IL_0029: newobj ""<>A{00000001}<int>..ctor(object, System.IntPtr)"" IL_002e: call ""void Program.Report(System.Delegate)"" IL_0033: ldnull IL_0034: ldftn ""void Program.M4(in int)"" IL_003a: newobj ""<>A{00000003}<int>..ctor(object, System.IntPtr)"" IL_003f: call ""void Program.Report(System.Delegate)"" IL_0044: ret }"); } [Fact] public void SynthesizedDelegateTypes_10() { var source = @"#pragma warning disable 414 using System; class Program { static void M1(int i) { } static void M2(out int i) { i = 0; } static void M3(ref int i) { } static void M4(in int i) { } static void Main() { var d1 = M1; var d2 = M2; var d3 = M3; var d4 = M4; Report(d1); Report(d2); Report(d3); Report(d4); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"System.Action`1[System.Int32] <>A{00000002}`1[System.Int32] <>A{00000001}`1[System.Int32] <>A{00000003}`1[System.Int32] "); } [WorkItem(55217, "https://github.com/dotnet/roslyn/issues/55217")] [Fact] public void SynthesizedDelegateTypes_11() { var source = @"class Program { unsafe static void Main() { var d1 = int* () => (int*)42; var d2 = (int* p) => { }; var d3 = delegate*<void> () => default; var d4 = (delegate*<void> d) => { }; } }"; var comp = CreateCompilation(source, options: TestOptions.UnsafeReleaseExe); comp.VerifyDiagnostics( // (5,18): error CS8917: The delegate type could not be inferred. // var d1 = int* () => (int*)42; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "int* () => (int*)42").WithLocation(5, 18), // (6,18): error CS8917: The delegate type could not be inferred. // var d2 = (int* p) => { }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(int* p) => { }").WithLocation(6, 18), // (7,18): error CS8917: The delegate type could not be inferred. // var d3 = delegate*<void> () => default; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "delegate*<void> () => default").WithLocation(7, 18), // (8,18): error CS8917: The delegate type could not be inferred. // var d4 = (delegate*<void> d) => { }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(delegate*<void> d) => { }").WithLocation(8, 18)); } [WorkItem(55217, "https://github.com/dotnet/roslyn/issues/55217")] [ConditionalFact(typeof(DesktopOnly))] public void SynthesizedDelegateTypes_12() { var source = @"using System; class Program { static void Main() { var d1 = (TypedReference x) => { }; var d2 = (int x, RuntimeArgumentHandle y) => { }; var d3 = (ArgIterator x) => { }; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,18): error CS8917: The delegate type could not be inferred. // var d1 = (TypedReference x) => { }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(TypedReference x) => { }").WithLocation(6, 18), // (7,18): error CS8917: The delegate type could not be inferred. // var d2 = (int x, RuntimeArgumentHandle y) => { }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(int x, RuntimeArgumentHandle y) => { }").WithLocation(7, 18), // (8,18): error CS8917: The delegate type could not be inferred. // var d3 = (ArgIterator x) => { }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(ArgIterator x) => { }").WithLocation(8, 18)); } [WorkItem(55217, "https://github.com/dotnet/roslyn/issues/55217")] [Fact] public void SynthesizedDelegateTypes_13() { var source = @"ref struct S<T> { } class Program { static void F1(int x, S<int> y) { } static S<T> F2<T>() => throw null; static void Main() { var d1 = F1; var d2 = F2<object>; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,18): error CS8917: The delegate type could not be inferred. // var d1 = F1; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F1").WithLocation(8, 18), // (9,18): error CS8917: The delegate type could not be inferred. // var d2 = F2<object>; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F2<object>").WithLocation(9, 18)); } [Fact] public void SynthesizedDelegateTypes_14() { var source = @"class Program { static ref void F() { } static void Main() { var d1 = F; var d2 = (ref void () => { }); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (3,16): error CS1547: Keyword 'void' cannot be used in this context // static ref void F() { } Diagnostic(ErrorCode.ERR_NoVoidHere, "void").WithLocation(3, 16), // (6,18): error CS8917: The delegate type could not be inferred. // var d1 = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F").WithLocation(6, 18), // (7,19): error CS8917: The delegate type could not be inferred. // var d2 = (ref void () => { }); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "ref void () => { }").WithLocation(7, 19), // (7,23): error CS1547: Keyword 'void' cannot be used in this context // var d2 = (ref void () => { }); Diagnostic(ErrorCode.ERR_NoVoidHere, "void").WithLocation(7, 23)); } [Fact] public void SynthesizedDelegateTypes_15() { var source = @"using System; unsafe class Program { static byte*[] F1() => null; static void F2(byte*[] a) { } static byte*[] F3(ref int i) => null; static void F4(ref byte*[] a) { } static void Main() { Report(int*[] () => null); Report((int*[] a) => { }); Report(int*[] (ref int i) => null); Report((ref int*[] a) => { }); Report(F1); Report(F2); Report(F3); Report(F4); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.UnsafeReleaseExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"System.Func`1[System.Int32*[]] System.Action`1[System.Int32*[]] <>F{00000001}`2[System.Int32,System.Int32*[]] <>A{00000001}`1[System.Int32*[]] System.Func`1[System.Byte*[]] System.Action`1[System.Byte*[]] <>F{00000001}`2[System.Int32,System.Byte*[]] <>A{00000001}`1[System.Byte*[]] "); } [Fact] public void SynthesizedDelegateTypes_16() { var source = @"using System; unsafe class Program { static delegate*<ref int>[] F1() => null; static void F2(delegate*<ref int, void>[] a) { } static delegate*<ref int>[] F3(ref int i) => null; static void F4(ref delegate*<ref int, void>[] a) { } static void Main() { Report(delegate*<int, ref int>[] () => null); Report((delegate*<int, ref int, void>[] a) => { }); Report(delegate*<int, ref int>[] (ref int i) => null); Report((ref delegate*<int, ref int, void>[] a) => { }); Report(F1); Report(F2); Report(F3); Report(F4); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.UnsafeReleaseExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"System.Func`1[(fnptr)[]] System.Action`1[(fnptr)[]] <>F{00000001}`2[System.Int32,(fnptr)[]] <>A{00000001}`1[(fnptr)[]] System.Func`1[(fnptr)[]] System.Action`1[(fnptr)[]] <>F{00000001}`2[System.Int32,(fnptr)[]] <>A{00000001}`1[(fnptr)[]] "); } [Fact] public void SynthesizedDelegateTypes_17() { var source = @"#nullable enable using System; class Program { static void F1(object x, dynamic y) { } static void F2(IntPtr x, nint y) { } static void F3((int x, int y) t) { } static void F4(object? x, object?[] y) { } static void F5(ref object x, dynamic y) { } static void F6(IntPtr x, ref nint y) { } static void F7(ref (int x, int y) t) { } static void F8(object? x, ref object?[] y) { } static void Main() { Report(F1); Report(F2); Report(F3); Report(F4); Report(F5); Report(F6); Report(F7); Report(F8); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"System.Action`2[System.Object,System.Object] System.Action`2[System.IntPtr,System.IntPtr] System.Action`1[System.ValueTuple`2[System.Int32,System.Int32]] System.Action`2[System.Object,System.Object[]] <>A{00000001}`2[System.Object,System.Object] <>A{00000004}`2[System.IntPtr,System.IntPtr] <>A{00000001}`1[System.ValueTuple`2[System.Int32,System.Int32]] <>A{00000004}`2[System.Object,System.Object[]] "); } [Fact] [WorkItem(55570, "https://github.com/dotnet/roslyn/issues/55570")] public void SynthesizedDelegateTypes_18() { var source = @"using System; class Program { static void Main() { Report((int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) => { return 1; }); Report((int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, out int _17) => { _17 = 0; return 2; }); Report((int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, ref int _17) => { return 3; }); Report((int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, in int _17) => { return 4; }); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"<>F`18[System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Int32] <>F{200000000}`18[System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Int32] <>F{100000000}`18[System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Int32] <>F{300000000}`18[System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Int32] "); } [Fact] [WorkItem(55570, "https://github.com/dotnet/roslyn/issues/55570")] public void SynthesizedDelegateTypes_19() { var source = @"using System; class Program { static void F1(ref int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17, object _18) { } static void F2(ref int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17, out object _18) { _18 = null; } static void F3(ref int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17, ref object _18) { } static void F4(ref int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17, in object _18) { } static void Main() { Report(F1); Report(F2); Report(F3); Report(F4); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"<>A{00000001}`18[System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object] <>A{800000001}`18[System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object] <>A{400000001}`18[System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object] <>A{c00000001}`18[System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object] "); } [Fact] [WorkItem(55570, "https://github.com/dotnet/roslyn/issues/55570")] public void SynthesizedDelegateTypes_20() { var source = @"using System; class Program { static void F1( int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17, object _18, int _19, object _20, int _21, object _22, int _23, object _24, int _25, object _26, int _27, object _28, int _29, object _30, int _31, ref object _32, int _33) { } static void F2( int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17, object _18, int _19, object _20, int _21, object _22, int _23, object _24, int _25, object _26, int _27, object _28, int _29, object _30, int _31, ref object _32, out int _33) { _33 = 0; } static void F3( int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17, object _18, int _19, object _20, int _21, object _22, int _23, object _24, int _25, object _26, int _27, object _28, int _29, object _30, int _31, ref object _32, ref int _33) { } static void F4( int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17, object _18, int _19, object _20, int _21, object _22, int _23, object _24, int _25, object _26, int _27, object _28, int _29, object _30, int _31, ref object _32, in int _33) { } static void Main() { Report(F1); Report(F2); Report(F3); Report(F4); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"<>A{4000000000000000\,00000000}`33[System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32] <>A{4000000000000000\,00000002}`33[System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32] <>A{4000000000000000\,00000001}`33[System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32] <>A{4000000000000000\,00000003}`33[System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32] "); } /// <summary> /// Synthesized delegate types should only be emitted if used. /// </summary> [Fact] [WorkItem(55896, "https://github.com/dotnet/roslyn/issues/55896")] public void SynthesizedDelegateTypes_21() { var source = @"using System; delegate void D2(object x, ref object y); delegate void D4(out object x, ref object y); class Program { static void F1(ref object x, object y) { } static void F2(object x, ref object y) { } static void Main() { var d1 = F1; D2 d2 = F2; var d3 = (ref object x, out object y) => { y = null; }; D4 d4 = (out object x, ref object y) => { x = null; }; Report(d1); Report(d2); Report(d3); Report(d4); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(comp, validator: validator, expectedOutput: @"<>A{00000001}`2[System.Object,System.Object] D2 <>A{00000009}`2[System.Object,System.Object] D4"); static void validator(PEAssembly assembly) { var reader = assembly.GetMetadataReader(); var actualTypes = reader.GetTypeDefNames().Select(h => reader.GetString(h)).ToArray(); // https://github.com/dotnet/roslyn/issues/55896: Should not include <>A{00000004}`2 or <>A{00000006}`2. string[] expectedTypes = new[] { "<Module>", "<>A{00000001}`2", "<>A{00000004}`2", "<>A{00000006}`2", "<>A{00000009}`2", "D2", "D4", "Program", "<>c", }; AssertEx.Equal(expectedTypes, actualTypes); } } private static void VerifyLocalDelegateType(SemanticModel model, VariableDeclaratorSyntax variable, string expectedLocal, string expectedInvokeMethod) { var local = (ILocalSymbol)model.GetDeclaredSymbol(variable)!; Assert.Equal(expectedLocal, local.ToTestDisplayString()); var delegateType = ((INamedTypeSymbol)local.Type); Assert.Equal(Accessibility.Internal, delegateType.DeclaredAccessibility); Assert.Equal(expectedInvokeMethod, delegateType.DelegateInvokeMethod.ToTestDisplayString()); } private static void VerifyExpressionType(SemanticModel model, ExpressionSyntax variable, string expectedSymbol, string expectedType) { var symbol = model.GetSymbolInfo(variable).Symbol; Assert.Equal(expectedSymbol, symbol.ToTestDisplayString()); var type = model.GetTypeInfo(variable).Type; Assert.Equal(expectedType, type.ToTestDisplayString()); } [Fact] public void TaskRunArgument() { var source = @"using System.Threading.Tasks; class Program { static async Task F() { await Task.Run(() => { }); } }"; var verifier = CompileAndVerify(source, parseOptions: TestOptions.RegularPreview); var method = (MethodSymbol)verifier.TestData.GetMethodsByName()["Program.<>c.<F>b__0_0()"].Method; Assert.Equal("void Program.<>c.<F>b__0_0()", method.ToTestDisplayString()); verifier.VerifyIL("Program.<>c.<F>b__0_0()", @"{ // Code size 1 (0x1) .maxstack 0 IL_0000: ret }"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class DelegateTypeTests : CSharpTestBase { private const string s_utils = @"using System; using System.Linq; static class Utils { internal static string GetDelegateMethodName(this Delegate d) { var method = d.Method; return Concat(GetTypeName(method.DeclaringType), method.Name); } internal static string GetDelegateTypeName(this Delegate d) { return d.GetType().GetTypeName(); } internal static string GetTypeName(this Type type) { if (type.IsArray) { return GetTypeName(type.GetElementType()) + ""[]""; } string typeName = type.Name; int index = typeName.LastIndexOf('`'); if (index >= 0) { typeName = typeName.Substring(0, index); } typeName = Concat(type.Namespace, typeName); if (!type.IsGenericType) { return typeName; } return $""{typeName}<{string.Join("", "", type.GetGenericArguments().Select(GetTypeName))}>""; } private static string Concat(string container, string name) { return string.IsNullOrEmpty(container) ? name : container + ""."" + name; } }"; private static readonly string s_expressionOfTDelegate0ArgTypeName = ExecutionConditionUtil.IsDesktop ? "System.Linq.Expressions.Expression`1" : "System.Linq.Expressions.Expression0`1"; private static readonly string s_expressionOfTDelegate1ArgTypeName = ExecutionConditionUtil.IsDesktop ? "System.Linq.Expressions.Expression`1" : "System.Linq.Expressions.Expression1`1"; [Fact] public void LanguageVersion() { var source = @"class Program { static void Main() { System.Delegate d; d = Main; d = () => { }; d = delegate () { }; System.Linq.Expressions.Expression e = () => 1; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,13): error CS0428: Cannot convert method group 'Main' to non-delegate type 'Delegate'. Did you intend to invoke the method? // d = Main; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "Main").WithArguments("Main", "System.Delegate").WithLocation(6, 13), // (7,13): error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type // d = () => { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "System.Delegate").WithLocation(7, 13), // (8,13): error CS1660: Cannot convert anonymous method to type 'Delegate' because it is not a delegate type // d = delegate () { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate () { }").WithArguments("anonymous method", "System.Delegate").WithLocation(8, 13), // (9,48): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // System.Linq.Expressions.Expression e = () => 1; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(9, 48)); comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(); } [Fact] public void MethodGroupConversions_01() { var source = @"using System; class Program { static void Main() { object o = Main; ICloneable c = Main; Delegate d = Main; MulticastDelegate m = Main; Report(o); Report(c); Report(d); Report(m); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,20): error CS0428: Cannot convert method group 'Main' to non-delegate type 'object'. Did you intend to invoke the method? // object o = Main; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "Main").WithArguments("Main", "object").WithLocation(6, 20), // (7,24): error CS0428: Cannot convert method group 'Main' to non-delegate type 'ICloneable'. Did you intend to invoke the method? // ICloneable c = Main; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "Main").WithArguments("Main", "System.ICloneable").WithLocation(7, 24), // (8,22): error CS0428: Cannot convert method group 'Main' to non-delegate type 'Delegate'. Did you intend to invoke the method? // Delegate d = Main; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "Main").WithArguments("Main", "System.Delegate").WithLocation(8, 22), // (9,31): error CS0428: Cannot convert method group 'Main' to non-delegate type 'MulticastDelegate'. Did you intend to invoke the method? // MulticastDelegate m = Main; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "Main").WithArguments("Main", "System.MulticastDelegate").WithLocation(9, 31)); comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics( // (6,20): warning CS8974: Converting method group 'Main' to non-delegate type 'object'. Did you intend to invoke the method? // object o = Main; Diagnostic(ErrorCode.WRN_MethGrpToNonDel, "Main").WithArguments("Main", "object").WithLocation(6, 20)); CompileAndVerify(comp, expectedOutput: @"System.Action System.Action System.Action System.Action "); } [Fact] public void MethodGroupConversions_02() { var source = @"using System; class Program { static void Main() { var o = (object)Main; var c = (ICloneable)Main; var d = (Delegate)Main; var m = (MulticastDelegate)Main; Report(o); Report(c); Report(d); Report(m); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,17): error CS0030: Cannot convert type 'method' to 'object' // var o = (object)Main; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(object)Main").WithArguments("method", "object").WithLocation(6, 17), // (7,17): error CS0030: Cannot convert type 'method' to 'ICloneable' // var c = (ICloneable)Main; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(ICloneable)Main").WithArguments("method", "System.ICloneable").WithLocation(7, 17), // (8,17): error CS0030: Cannot convert type 'method' to 'Delegate' // var d = (Delegate)Main; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(Delegate)Main").WithArguments("method", "System.Delegate").WithLocation(8, 17), // (9,17): error CS0030: Cannot convert type 'method' to 'MulticastDelegate' // var m = (MulticastDelegate)Main; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(MulticastDelegate)Main").WithArguments("method", "System.MulticastDelegate").WithLocation(9, 17)); comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"System.Action System.Action System.Action System.Action "); } [Fact] public void MethodGroupConversions_03() { var source = @"class Program { static void Main() { System.Linq.Expressions.Expression e = F; e = (System.Linq.Expressions.Expression)F; System.Linq.Expressions.LambdaExpression l = F; l = (System.Linq.Expressions.LambdaExpression)F; } static int F() => 1; }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (5,48): error CS0428: Cannot convert method group 'F' to non-delegate type 'Expression'. Did you intend to invoke the method? // System.Linq.Expressions.Expression e = F; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "System.Linq.Expressions.Expression").WithLocation(5, 48), // (6,13): error CS0030: Cannot convert type 'method' to 'Expression' // e = (System.Linq.Expressions.Expression)F; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(System.Linq.Expressions.Expression)F").WithArguments("method", "System.Linq.Expressions.Expression").WithLocation(6, 13), // (7,54): error CS0428: Cannot convert method group 'F' to non-delegate type 'LambdaExpression'. Did you intend to invoke the method? // System.Linq.Expressions.LambdaExpression l = F; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "System.Linq.Expressions.LambdaExpression").WithLocation(7, 54), // (8,13): error CS0030: Cannot convert type 'method' to 'LambdaExpression' // l = (System.Linq.Expressions.LambdaExpression)F; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(System.Linq.Expressions.LambdaExpression)F").WithArguments("method", "System.Linq.Expressions.LambdaExpression").WithLocation(8, 13)); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,48): error CS0428: Cannot convert method group 'F' to non-delegate type 'Expression'. Did you intend to invoke the method? // System.Linq.Expressions.Expression e = F; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "System.Linq.Expressions.Expression").WithLocation(5, 48), // (6,13): error CS0428: Cannot convert method group 'F' to non-delegate type 'Expression'. Did you intend to invoke the method? // e = (System.Linq.Expressions.Expression)F; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "(System.Linq.Expressions.Expression)F").WithArguments("F", "System.Linq.Expressions.Expression").WithLocation(6, 13), // (7,54): error CS0428: Cannot convert method group 'F' to non-delegate type 'LambdaExpression'. Did you intend to invoke the method? // System.Linq.Expressions.LambdaExpression l = F; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "System.Linq.Expressions.LambdaExpression").WithLocation(7, 54), // (8,13): error CS0428: Cannot convert method group 'F' to non-delegate type 'LambdaExpression'. Did you intend to invoke the method? // l = (System.Linq.Expressions.LambdaExpression)F; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "(System.Linq.Expressions.LambdaExpression)F").WithArguments("F", "System.Linq.Expressions.LambdaExpression").WithLocation(8, 13)); } [Fact] public void MethodGroupConversions_04() { var source = @"using System; using System.Linq.Expressions; class Program { static void F() { } static void F(object o) { } static void Main() { object o = F; ICloneable c = F; Delegate d = F; MulticastDelegate m = F; Expression e = F; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,20): error CS8917: The delegate type could not be inferred. // object o = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F").WithLocation(9, 20), // (10,24): error CS8917: The delegate type could not be inferred. // ICloneable c = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F").WithLocation(10, 24), // (11,22): error CS8917: The delegate type could not be inferred. // Delegate d = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F").WithLocation(11, 22), // (12,31): error CS8917: The delegate type could not be inferred. // MulticastDelegate m = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F").WithLocation(12, 31), // (13,24): error CS0428: Cannot convert method group 'F' to non-delegate type 'Expression'. Did you intend to invoke the method? // Expression e = F; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "System.Linq.Expressions.Expression").WithLocation(13, 24)); } [Fact] public void LambdaConversions_01() { var source = @"using System; class Program { static void Main() { object o = () => { }; ICloneable c = () => { }; Delegate d = () => { }; MulticastDelegate m = () => { }; Report(o); Report(c); Report(d); Report(m); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,20): error CS1660: Cannot convert lambda expression to type 'object' because it is not a delegate type // object o = () => { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "object").WithLocation(6, 20), // (7,24): error CS1660: Cannot convert lambda expression to type 'ICloneable' because it is not a delegate type // ICloneable c = () => { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "System.ICloneable").WithLocation(7, 24), // (8,22): error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type // Delegate d = () => { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "System.Delegate").WithLocation(8, 22), // (9,31): error CS1660: Cannot convert lambda expression to type 'MulticastDelegate' because it is not a delegate type // MulticastDelegate m = () => { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "System.MulticastDelegate").WithLocation(9, 31)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Action System.Action System.Action System.Action "); } [Fact] public void LambdaConversions_02() { var source = @"using System; class Program { static void Main() { var o = (object)(() => { }); var c = (ICloneable)(() => { }); var d = (Delegate)(() => { }); var m = (MulticastDelegate)(() => { }); Report(o); Report(c); Report(d); Report(m); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,26): error CS1660: Cannot convert lambda expression to type 'object' because it is not a delegate type // var o = (object)(() => { }); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "object").WithLocation(6, 26), // (7,30): error CS1660: Cannot convert lambda expression to type 'ICloneable' because it is not a delegate type // var c = (ICloneable)(() => { }); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "System.ICloneable").WithLocation(7, 30), // (8,28): error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type // var d = (Delegate)(() => { }); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "System.Delegate").WithLocation(8, 28), // (9,37): error CS1660: Cannot convert lambda expression to type 'MulticastDelegate' because it is not a delegate type // var m = (MulticastDelegate)(() => { }); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "System.MulticastDelegate").WithLocation(9, 37)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Action System.Action System.Action System.Action "); } [Fact] public void LambdaConversions_03() { var source = @"using System; using System.Linq.Expressions; class Program { static void Main() { Expression e = () => 1; Report(e); e = (Expression)(() => 2); Report(e); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,24): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // Expression e = () => 1; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(7, 24), // (9,26): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // e = (Expression)(() => 2); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 2").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(9, 26)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: $@"{s_expressionOfTDelegate0ArgTypeName}[System.Func`1[System.Int32]] {s_expressionOfTDelegate0ArgTypeName}[System.Func`1[System.Int32]] "); } [Fact] public void LambdaConversions_04() { var source = @"using System; using System.Linq.Expressions; class Program { static void Main() { LambdaExpression e = () => 1; Report(e); e = (LambdaExpression)(() => 2); Report(e); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,30): error CS1660: Cannot convert lambda expression to type 'LambdaExpression' because it is not a delegate type // LambdaExpression e = () => 1; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Linq.Expressions.LambdaExpression").WithLocation(7, 30), // (9,32): error CS1660: Cannot convert lambda expression to type 'LambdaExpression' because it is not a delegate type // e = (LambdaExpression)(() => 2); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 2").WithArguments("lambda expression", "System.Linq.Expressions.LambdaExpression").WithLocation(9, 32)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: $@"{s_expressionOfTDelegate0ArgTypeName}[System.Func`1[System.Int32]] {s_expressionOfTDelegate0ArgTypeName}[System.Func`1[System.Int32]] "); } [Fact] public void LambdaConversions_05() { var source = @"using System; using System.Linq.Expressions; class Program { static void Main() { Delegate d = x => x; object o = (object)(x => x); Expression e = x => x; e = (Expression)(x => x); LambdaExpression l = x => x; l = (LambdaExpression)(x => x); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,22): error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type // Delegate d = x => x; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "x => x").WithArguments("lambda expression", "System.Delegate").WithLocation(7, 22), // (8,29): error CS1660: Cannot convert lambda expression to type 'object' because it is not a delegate type // object o = (object)(x => x); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "x => x").WithArguments("lambda expression", "object").WithLocation(8, 29), // (9,24): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // Expression e = x => x; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "x => x").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(9, 24), // (10,26): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // e = (Expression)(x => x); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "x => x").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(10, 26), // (11,30): error CS1660: Cannot convert lambda expression to type 'LambdaExpression' because it is not a delegate type // LambdaExpression l = x => x; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "x => x").WithArguments("lambda expression", "System.Linq.Expressions.LambdaExpression").WithLocation(11, 30), // (12,32): error CS1660: Cannot convert lambda expression to type 'LambdaExpression' because it is not a delegate type // l = (LambdaExpression)(x => x); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "x => x").WithArguments("lambda expression", "System.Linq.Expressions.LambdaExpression").WithLocation(12, 32)); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,22): error CS8917: The delegate type could not be inferred. // Delegate d = x => x; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(7, 22), // (8,29): error CS8917: The delegate type could not be inferred. // object o = (object)(x => x); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(8, 29), // (9,24): error CS8917: The delegate type could not be inferred. // Expression e = x => x; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(9, 24), // (10,26): error CS8917: The delegate type could not be inferred. // e = (Expression)(x => x); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(10, 26), // (11,30): error CS8917: The delegate type could not be inferred. // LambdaExpression l = x => x; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(11, 30), // (12,32): error CS8917: The delegate type could not be inferred. // l = (LambdaExpression)(x => x); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(12, 32)); } [Fact] public void LambdaConversions_06() { var sourceA = @"namespace System.Linq.Expressions { public class LambdaExpression<T> { } }"; var sourceB = @"using System; using System.Linq.Expressions; class Program { static void Main() { LambdaExpression<Func<int>> l = () => 1; l = (LambdaExpression<Func<int>>)(() => 2); } }"; var expectedDiagnostics = new[] { // (7,41): error CS1660: Cannot convert lambda expression to type 'LambdaExpression<Func<int>>' because it is not a delegate type // LambdaExpression<Func<int>> l = () => 1; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Linq.Expressions.LambdaExpression<System.Func<int>>").WithLocation(7, 41), // (8,43): error CS1660: Cannot convert lambda expression to type 'LambdaExpression<Func<int>>' because it is not a delegate type // l = (LambdaExpression<Func<int>>)(() => 2); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 2").WithArguments("lambda expression", "System.Linq.Expressions.LambdaExpression<System.Func<int>>").WithLocation(8, 43) }; var comp = CreateCompilation(new[] { sourceA, sourceB }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(new[] { sourceA, sourceB }); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void LambdaConversions_07() { var source = @"using System; class Program { static void Main() { System.Delegate d = () => Main; System.Linq.Expressions.Expression e = () => Main; Report(d); Report(e); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: $@"System.Func`1[System.Action] {s_expressionOfTDelegate0ArgTypeName}[System.Func`1[System.Action]] "); } [Fact] public void AnonymousMethod_01() { var source = @"using System; class Program { static void Main() { object o = delegate () { }; ICloneable c = delegate () { }; Delegate d = delegate () { }; MulticastDelegate m = delegate () { }; Report(o); Report(c); Report(d); Report(m); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,20): error CS1660: Cannot convert anonymous method to type 'object' because it is not a delegate type // object o = delegate () { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate () { }").WithArguments("anonymous method", "object").WithLocation(6, 20), // (7,24): error CS1660: Cannot convert anonymous method to type 'ICloneable' because it is not a delegate type // ICloneable c = delegate () { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate () { }").WithArguments("anonymous method", "System.ICloneable").WithLocation(7, 24), // (8,22): error CS1660: Cannot convert anonymous method to type 'Delegate' because it is not a delegate type // Delegate d = delegate () { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate () { }").WithArguments("anonymous method", "System.Delegate").WithLocation(8, 22), // (9,31): error CS1660: Cannot convert anonymous method to type 'MulticastDelegate' because it is not a delegate type // MulticastDelegate m = delegate () { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate () { }").WithArguments("anonymous method", "System.MulticastDelegate").WithLocation(9, 31)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Action System.Action System.Action System.Action "); } [Fact] public void AnonymousMethod_02() { var source = @"using System.Linq.Expressions; class Program { static void Main() { System.Linq.Expressions.Expression e = delegate () { return 1; }; e = (Expression)delegate () { return 2; }; LambdaExpression l = delegate () { return 3; }; l = (LambdaExpression)delegate () { return 4; }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,48): error CS1660: Cannot convert anonymous method to type 'Expression' because it is not a delegate type // System.Linq.Expressions.Expression e = delegate () { return 1; }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate () { return 1; }").WithArguments("anonymous method", "System.Linq.Expressions.Expression").WithLocation(6, 48), // (7,25): error CS1660: Cannot convert anonymous method to type 'Expression' because it is not a delegate type // e = (Expression)delegate () { return 2; }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate () { return 2; }").WithArguments("anonymous method", "System.Linq.Expressions.Expression").WithLocation(7, 25), // (8,30): error CS1660: Cannot convert anonymous method to type 'LambdaExpression' because it is not a delegate type // LambdaExpression l = delegate () { return 3; }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate () { return 3; }").WithArguments("anonymous method", "System.Linq.Expressions.LambdaExpression").WithLocation(8, 30), // (9,31): error CS1660: Cannot convert anonymous method to type 'LambdaExpression' because it is not a delegate type // l = (LambdaExpression)delegate () { return 4; }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate () { return 4; }").WithArguments("anonymous method", "System.Linq.Expressions.LambdaExpression").WithLocation(9, 31)); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,48): error CS1946: An anonymous method expression cannot be converted to an expression tree // System.Linq.Expressions.Expression e = delegate () { return 1; }; Diagnostic(ErrorCode.ERR_AnonymousMethodToExpressionTree, "delegate () { return 1; }").WithLocation(6, 48), // (7,13): error CS1946: An anonymous method expression cannot be converted to an expression tree // e = (Expression)delegate () { return 2; }; Diagnostic(ErrorCode.ERR_AnonymousMethodToExpressionTree, "(Expression)delegate () { return 2; }").WithLocation(7, 13), // (8,30): error CS1946: An anonymous method expression cannot be converted to an expression tree // LambdaExpression l = delegate () { return 3; }; Diagnostic(ErrorCode.ERR_AnonymousMethodToExpressionTree, "delegate () { return 3; }").WithLocation(8, 30), // (9,13): error CS1946: An anonymous method expression cannot be converted to an expression tree // l = (LambdaExpression)delegate () { return 4; }; Diagnostic(ErrorCode.ERR_AnonymousMethodToExpressionTree, "(LambdaExpression)delegate () { return 4; }").WithLocation(9, 13)); } [Fact] public void DynamicConversion() { var source = @"using System; class Program { static void Main() { dynamic d; d = Main; d = () => 1; } static void Report(dynamic d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,13): error CS0428: Cannot convert method group 'Main' to non-delegate type 'dynamic'. Did you intend to invoke the method? // d = Main; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "Main").WithArguments("Main", "dynamic").WithLocation(7, 13), // (8,13): error CS1660: Cannot convert lambda expression to type 'dynamic' because it is not a delegate type // d = () => 1; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "dynamic").WithLocation(8, 13)); } private static IEnumerable<object?[]> GetMethodGroupData(Func<string, string, DiagnosticDescription[]> getExpectedDiagnostics) { yield return getData("static int F() => 0;", "Program.F", "F", "System.Func<System.Int32>"); yield return getData("static int F() => 0;", "F", "F", "System.Func<System.Int32>"); yield return getData("int F() => 0;", "(new Program()).F", "F", "System.Func<System.Int32>"); yield return getData("static T F<T>() => default;", "Program.F<int>", "F", "System.Func<System.Int32>"); yield return getData("static void F<T>() where T : class { }", "F<object>", "F", "System.Action"); yield return getData("static void F<T>() where T : struct { }", "F<int>", "F", "System.Action"); yield return getData("T F<T>() => default;", "(new Program()).F<int>", "F", "System.Func<System.Int32>"); yield return getData("T F<T>() => default;", "(new Program()).F", "F", null); yield return getData("void F<T>(T t) { }", "(new Program()).F<string>", "F", "System.Action<System.String>"); yield return getData("void F<T>(T t) { }", "(new Program()).F", "F", null); yield return getData("static ref int F() => throw null;", "F", "F", "<>F{00000001}<System.Int32>"); yield return getData("static ref readonly int F() => throw null;", "F", "F", "<>F{00000003}<System.Int32>"); yield return getData("static void F() { }", "F", "F", "System.Action"); yield return getData("static void F(int x, int y) { }", "F", "F", "System.Action<System.Int32, System.Int32>"); yield return getData("static void F(out int x, int y) { x = 0; }", "F", "F", "<>A{00000002}<System.Int32, System.Int32>"); yield return getData("static void F(int x, ref int y) { }", "F", "F", "<>A{00000004}<System.Int32, System.Int32>"); yield return getData("static void F(int x, in int y) { }", "F", "F", "<>A{0000000c}<System.Int32, System.Int32>"); yield return getData("static void F(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16) { }", "F", "F", "System.Action<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object>"); yield return getData("static void F(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) { }", "F", "F", "<>A<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32>"); yield return getData("static object F(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16) => null;", "F", "F", "System.Func<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Object>"); yield return getData("static object F(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) => null;", "F", "F", "<>F<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object>"); object?[] getData(string methodDeclaration, string methodGroupExpression, string methodGroupOnly, string? expectedType) => new object?[] { methodDeclaration, methodGroupExpression, expectedType is null ? getExpectedDiagnostics(methodGroupExpression, methodGroupOnly) : null, expectedType }; } public static IEnumerable<object?[]> GetMethodGroupImplicitConversionData() { return GetMethodGroupData((methodGroupExpression, methodGroupOnly) => { int offset = methodGroupExpression.Length - methodGroupOnly.Length; return new[] { // (6,29): error CS8917: The delegate type could not be inferred. // System.Delegate d = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, methodGroupOnly).WithLocation(6, 29 + offset) }; }); } [Theory] [MemberData(nameof(GetMethodGroupImplicitConversionData))] public void MethodGroup_ImplicitConversion(string methodDeclaration, string methodGroupExpression, DiagnosticDescription[]? expectedDiagnostics, string? expectedType) { var source = $@"class Program {{ {methodDeclaration} static void Main() {{ System.Delegate d = {methodGroupExpression}; System.Console.Write(d.GetDelegateTypeName()); }} }}"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); if (expectedDiagnostics is null) { CompileAndVerify(comp, expectedOutput: expectedType); } else { comp.VerifyDiagnostics(expectedDiagnostics); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value; var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); } public static IEnumerable<object?[]> GetMethodGroupExplicitConversionData() { return GetMethodGroupData((methodGroupExpression, methodGroupOnly) => { int offset = methodGroupExpression.Length - methodGroupOnly.Length; return new[] { // (6,20): error CS0030: Cannot convert type 'method' to 'Delegate' // object o = (System.Delegate)F; Diagnostic(ErrorCode.ERR_NoExplicitConv, $"(System.Delegate){methodGroupExpression}").WithArguments("method", "System.Delegate").WithLocation(6, 20) }; }); } [Theory] [MemberData(nameof(GetMethodGroupExplicitConversionData))] public void MethodGroup_ExplicitConversion(string methodDeclaration, string methodGroupExpression, DiagnosticDescription[]? expectedDiagnostics, string? expectedType) { var source = $@"class Program {{ {methodDeclaration} static void Main() {{ object o = (System.Delegate){methodGroupExpression}; System.Console.Write(o.GetType().GetTypeName()); }} }}"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); if (expectedDiagnostics is null) { CompileAndVerify(comp, expectedOutput: expectedType); } else { comp.VerifyDiagnostics(expectedDiagnostics); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = ((CastExpressionSyntax)tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value).Expression; var typeInfo = model.GetTypeInfo(expr); // https://github.com/dotnet/roslyn/issues/52874: GetTypeInfo() for method group should return inferred delegate type. Assert.Null(typeInfo.Type); Assert.Null(typeInfo.ConvertedType); } public static IEnumerable<object?[]> GetLambdaData() { yield return getData("x => x", null); yield return getData("x => { return x; }", null); yield return getData("x => ref args[0]", null); yield return getData("(x, y) => { }", null); yield return getData("() => 1", "System.Func<System.Int32>"); yield return getData("() => ref args[0]", "<>F{00000001}<System.String>"); yield return getData("() => { }", "System.Action"); yield return getData("(int x, int y) => { }", "System.Action<System.Int32, System.Int32>"); yield return getData("(out int x, int y) => { x = 0; }", "<>A{00000002}<System.Int32, System.Int32>"); yield return getData("(int x, ref int y) => { x = 0; }", "<>A{00000004}<System.Int32, System.Int32>"); yield return getData("(int x, in int y) => { x = 0; }", "<>A{0000000c}<System.Int32, System.Int32>"); yield return getData("(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16) => { }", "System.Action<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object>"); yield return getData("(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) => { }", "<>A<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32>"); yield return getData("(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16) => _1", "System.Func<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32>"); yield return getData("(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) => _1", "<>F<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Int32>"); yield return getData("static () => 1", "System.Func<System.Int32>"); yield return getData("async () => { await System.Threading.Tasks.Task.Delay(0); }", "System.Func<System.Threading.Tasks.Task>"); yield return getData("static async () => { await System.Threading.Tasks.Task.Delay(0); return 0; }", "System.Func<System.Threading.Tasks.Task<System.Int32>>"); yield return getData("() => Main", "System.Func<System.Action<System.String[]>>"); yield return getData("(int x) => x switch { _ => null }", null); yield return getData("_ => { }", null); yield return getData("_ => _", null); yield return getData("() => throw null", null); yield return getData("x => throw null", null); yield return getData("(int x) => throw null", null); yield return getData("() => { throw null; }", "System.Action"); yield return getData("(int x) => { throw null; }", "System.Action<System.Int32>"); yield return getData("(string s) => { if (s.Length > 0) return s; return null; }", "System.Func<System.String, System.String>"); yield return getData("(string s) => { if (s.Length > 0) return default; return s; }", "System.Func<System.String, System.String>"); yield return getData("(int i) => { if (i > 0) return i; return default; }", "System.Func<System.Int32, System.Int32>"); yield return getData("(int x, short y) => { if (x > 0) return x; return y; }", "System.Func<System.Int32, System.Int16, System.Int32>"); yield return getData("(int x, short y) => { if (x > 0) return y; return x; }", "System.Func<System.Int32, System.Int16, System.Int32>"); yield return getData("object () => default", "System.Func<System.Object>"); yield return getData("void () => { }", "System.Action"); // Distinct names for distinct signatures with > 16 parameters: https://github.com/dotnet/roslyn/issues/55570 yield return getData("(int _1, int _2, int _3, int _4, int _5, int _6, int _7, int _8, int _9, int _10, int _11, int _12, int _13, int _14, int _15, int _16, ref int _17) => { }", "<>A{100000000}<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32>"); yield return getData("(int _1, int _2, int _3, int _4, int _5, int _6, int _7, int _8, int _9, int _10, int _11, int _12, int _13, int _14, int _15, int _16, in int _17) => { }", "<>A{300000000}<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32>"); static object?[] getData(string expr, string? expectedType) => new object?[] { expr, expectedType }; } public static IEnumerable<object?[]> GetAnonymousMethodData() { yield return getData("delegate { }", null); yield return getData("delegate () { return 1; }", "System.Func<System.Int32>"); yield return getData("delegate () { return ref args[0]; }", "<>F{00000001}<System.String>"); yield return getData("delegate () { }", "System.Action"); yield return getData("delegate (int x, int y) { }", "System.Action<System.Int32, System.Int32>"); yield return getData("delegate (out int x, int y) { x = 0; }", "<>A{00000002}<System.Int32, System.Int32>"); yield return getData("delegate (int x, ref int y) { x = 0; }", "<>A{00000004}<System.Int32, System.Int32>"); yield return getData("delegate (int x, in int y) { x = 0; }", "<>A{0000000c}<System.Int32, System.Int32>"); yield return getData("delegate (int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16) { }", "System.Action<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object>"); yield return getData("delegate (int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) { }", "<>A<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32>"); yield return getData("delegate (int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16) { return _1; }", "System.Func<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32>"); yield return getData("delegate (int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) { return _1; }", "<>F<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Int32>"); static object?[] getData(string expr, string? expectedType) => new object?[] { expr, expectedType }; } [Theory] [MemberData(nameof(GetLambdaData))] [MemberData(nameof(GetAnonymousMethodData))] public void AnonymousFunction_ImplicitConversion(string anonymousFunction, string? expectedType) { var source = $@"class Program {{ static void Main(string[] args) {{ System.Delegate d = {anonymousFunction}; System.Console.Write(d.GetDelegateTypeName()); }} }}"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); if (expectedType is null) { comp.VerifyDiagnostics( // (5,29): error CS8917: The delegate type could not be inferred. // System.Delegate d = x => x; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, anonymousFunction).WithLocation(5, 29)); } else { CompileAndVerify(comp, expectedOutput: expectedType); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<AnonymousFunctionExpressionSyntax>().Single(); var typeInfo = model.GetTypeInfo(expr); if (expectedType == null) { Assert.Null(typeInfo.Type); } else { Assert.Equal(expectedType, typeInfo.Type.ToTestDisplayString()); } Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); var symbolInfo = model.GetSymbolInfo(expr); var method = (IMethodSymbol)symbolInfo.Symbol!; Assert.Equal(MethodKind.LambdaMethod, method.MethodKind); if (typeInfo.Type is { }) { Assert.True(HaveMatchingSignatures(((INamedTypeSymbol)typeInfo.Type!).DelegateInvokeMethod!, method)); } } [Theory] [MemberData(nameof(GetLambdaData))] [MemberData(nameof(GetAnonymousMethodData))] public void AnonymousFunction_ExplicitConversion(string anonymousFunction, string? expectedType) { var source = $@"class Program {{ static void Main(string[] args) {{ object o = (System.Delegate)({anonymousFunction}); System.Console.Write(o.GetType().GetTypeName()); }} }}"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); if (expectedType is null) { comp.VerifyDiagnostics( // (5,38): error CS8917: The delegate type could not be inferred. // object o = (System.Delegate)(x => x); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, anonymousFunction).WithLocation(5, 38)); } else { CompileAndVerify(comp, expectedOutput: expectedType); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = ((CastExpressionSyntax)tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value).Expression; var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); Assert.Equal(expectedType, typeInfo.ConvertedType?.ToTestDisplayString()); var symbolInfo = model.GetSymbolInfo(expr); var method = (IMethodSymbol)symbolInfo.Symbol!; Assert.Equal(MethodKind.LambdaMethod, method.MethodKind); if (typeInfo.Type is { }) { Assert.True(HaveMatchingSignatures(((INamedTypeSymbol)typeInfo.Type!).DelegateInvokeMethod!, method)); } } private static bool HaveMatchingSignatures(IMethodSymbol methodA, IMethodSymbol methodB) { return MemberSignatureComparer.MethodGroupSignatureComparer.Equals(methodA.GetSymbol<MethodSymbol>(), methodB.GetSymbol<MethodSymbol>()); } public static IEnumerable<object?[]> GetExpressionData() { yield return getData("x => x", null); yield return getData("() => 1", "System.Func<System.Int32>"); yield return getData("(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16) => _1", "System.Func<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32>"); yield return getData("(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) => _1", "<>F<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Int32>"); yield return getData("static () => 1", "System.Func<System.Int32>"); static object?[] getData(string expr, string? expectedType) => new object?[] { expr, expectedType }; } [Theory] [MemberData(nameof(GetExpressionData))] public void Expression_ImplicitConversion(string anonymousFunction, string? expectedType) { var source = $@"class Program {{ static void Main(string[] args) {{ System.Linq.Expressions.Expression e = {anonymousFunction}; }} }}"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); if (expectedType is null) { comp.VerifyDiagnostics( // (5,48): error CS8917: The delegate type could not be inferred. // System.Linq.Expressions.Expression e = x => x; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, anonymousFunction).WithLocation(5, 48)); } else { comp.VerifyDiagnostics(); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<AnonymousFunctionExpressionSyntax>().Single(); var typeInfo = model.GetTypeInfo(expr); if (expectedType == null) { Assert.Null(typeInfo.Type); } else { Assert.Equal($"System.Linq.Expressions.Expression<{expectedType}>", typeInfo.Type.ToTestDisplayString()); } Assert.Equal("System.Linq.Expressions.Expression", typeInfo.ConvertedType!.ToTestDisplayString()); } [Theory] [MemberData(nameof(GetExpressionData))] public void Expression_ExplicitConversion(string anonymousFunction, string? expectedType) { var source = $@"class Program {{ static void Main(string[] args) {{ object o = (System.Linq.Expressions.Expression)({anonymousFunction}); }} }}"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); if (expectedType is null) { comp.VerifyDiagnostics( // (5,57): error CS8917: The delegate type could not be inferred. // object o = (System.Linq.Expressions.Expression)(x => x); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, anonymousFunction).WithLocation(5, 57)); } else { comp.VerifyDiagnostics(); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = ((CastExpressionSyntax)tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value).Expression; var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); if (expectedType is null) { Assert.Null(typeInfo.ConvertedType); } else { Assert.Equal($"System.Linq.Expressions.Expression<{expectedType}>", typeInfo.ConvertedType.ToTestDisplayString()); } } /// <summary> /// Should bind and report diagnostics from anonymous method body /// regardless of whether the delegate type can be inferred. /// </summary> [Fact] public void AnonymousMethodBodyErrors() { var source = @"using System; class Program { static void Main() { Delegate d0 = x0 => { _ = x0.Length; object y0 = 0; _ = y0.Length; }; Delegate d1 = (object x1) => { _ = x1.Length; }; Delegate d2 = (ref object x2) => { _ = x2.Length; }; Delegate d3 = delegate (object x3) { _ = x3.Length; }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (6,23): error CS8917: The delegate type could not be inferred. // Delegate d0 = x0 => { _ = x0.Length; object y0 = 0; _ = y0.Length; }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x0 => { _ = x0.Length; object y0 = 0; _ = y0.Length; }").WithLocation(6, 23), // (6,68): error CS1061: 'object' does not contain a definition for 'Length' and no accessible extension method 'Length' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) // Delegate d0 = x0 => { _ = x0.Length; object y0 = 0; _ = y0.Length; }; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Length").WithArguments("object", "Length").WithLocation(6, 68), // (7,47): error CS1061: 'object' does not contain a definition for 'Length' and no accessible extension method 'Length' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) // Delegate d1 = (object x1) => { _ = x1.Length; }; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Length").WithArguments("object", "Length").WithLocation(7, 47), // (8,51): error CS1061: 'object' does not contain a definition for 'Length' and no accessible extension method 'Length' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) // Delegate d2 = (ref object x2) => { _ = x2.Length; }; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Length").WithArguments("object", "Length").WithLocation(8, 51), // (9,53): error CS1061: 'object' does not contain a definition for 'Length' and no accessible extension method 'Length' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) // Delegate d3 = delegate (object x3) { _ = x3.Length; }; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Length").WithArguments("object", "Length").WithLocation(9, 53)); } public static IEnumerable<object?[]> GetBaseAndDerivedTypesData() { yield return getData("internal void F(object x) { }", "internal static new void F(object x) { }", "F", "F", null, "System.Action<System.Object>"); // instance and static // https://github.com/dotnet/roslyn/issues/52701: Assert failure: Unexpected value 'LessDerived' of type 'Microsoft.CodeAnalysis.CSharp.MemberResolutionKind' #if !DEBUG yield return getData("internal void F(object x) { }", "internal static new void F(object x) { }", "this.F", "F", new[] { // (5,29): error CS0176: Member 'B.F(object)' cannot be accessed with an instance reference; qualify it with a type name instead // System.Delegate d = this.F; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.F").WithArguments("B.F(object)").WithLocation(5, 29) }); // instance and static #endif yield return getData("internal void F(object x) { }", "internal static new void F(object x) { }", "base.F", "F", null, "System.Action<System.Object>"); // instance and static yield return getData("internal static void F(object x) { }", "internal new void F(object x) { }", "F", "F", null, "System.Action<System.Object>"); // static and instance yield return getData("internal static void F(object x) { }", "internal new void F(object x) { }", "this.F", "F", null, "System.Action<System.Object>"); // static and instance yield return getData("internal static void F(object x) { }", "internal new void F(object x) { }", "base.F", "F"); // static and instance yield return getData("internal void F(object x) { }", "internal static void F() { }", "F", "F"); // instance and static, different number of parameters yield return getData("internal void F(object x) { }", "internal static void F() { }", "B.F", "F", null, "System.Action"); // instance and static, different number of parameters yield return getData("internal void F(object x) { }", "internal static void F() { }", "this.F", "F", null, "System.Action<System.Object>"); // instance and static, different number of parameters yield return getData("internal void F(object x) { }", "internal static void F() { }", "base.F", "F", null, "System.Action<System.Object>"); // instance and static, different number of parameters yield return getData("internal static void F() { }", "internal void F(object x) { }", "F", "F"); // static and instance, different number of parameters yield return getData("internal static void F() { }", "internal void F(object x) { }", "B.F", "F", null, "System.Action"); // static and instance, different number of parameters yield return getData("internal static void F() { }", "internal void F(object x) { }", "this.F", "F", null, "System.Action<System.Object>"); // static and instance, different number of parameters yield return getData("internal static void F() { }", "internal void F(object x) { }", "base.F", "F"); // static and instance, different number of parameters yield return getData("internal static void F(object x) { }", "private static void F() { }", "F", "F"); // internal and private yield return getData("private static void F(object x) { }", "internal static void F() { }", "F", "F", null, "System.Action"); // internal and private yield return getData("internal abstract void F(object x);", "internal override void F(object x) { }", "F", "F", null, "System.Action<System.Object>"); // override yield return getData("internal virtual void F(object x) { }", "internal override void F(object x) { }", "F", "F", null, "System.Action<System.Object>"); // override yield return getData("internal void F(object x) { }", "internal void F(object x) { }", "F", "F", null, "System.Action<System.Object>"); // hiding yield return getData("internal void F(object x) { }", "internal new void F(object x) { }", "F", "F", null, "System.Action<System.Object>"); // hiding yield return getData("internal void F(object x) { }", "internal new void F(object y) { }", "F", "F", null, "System.Action<System.Object>"); // different parameter name yield return getData("internal void F(object x) { }", "internal void F(string x) { }", "F", "F"); // different parameter type yield return getData("internal void F(object x) { }", "internal void F(object x, object y) { }", "F", "F"); // different number of parameters yield return getData("internal void F(object x) { }", "internal void F(ref object x) { }", "F", "F"); // different parameter ref kind yield return getData("internal void F(ref object x) { }", "internal void F(object x) { }", "F", "F"); // different parameter ref kind yield return getData("internal abstract object F();", "internal override object F() => throw null;", "F", "F", null, "System.Func<System.Object>"); // override yield return getData("internal virtual object F() => throw null;", "internal override object F() => throw null;", "F", "F", null, "System.Func<System.Object>"); // override yield return getData("internal object F() => throw null;", "internal object F() => throw null;", "F", "F", null, "System.Func<System.Object>"); // hiding yield return getData("internal object F() => throw null;", "internal new object F() => throw null;", "F", "F", null, "System.Func<System.Object>"); // hiding yield return getData("internal string F() => throw null;", "internal new object F() => throw null;", "F", "F"); // different return type yield return getData("internal object F() => throw null;", "internal new ref object F() => throw null;", "F", "F"); // different return ref kind yield return getData("internal ref object F() => throw null;", "internal new object F() => throw null;", "F", "F"); // different return ref kind yield return getData("internal void F(object x) { }", "internal new void F(dynamic x) { }", "F", "F", null, "System.Action<System.Object>"); // object/dynamic yield return getData("internal dynamic F() => throw null;", "internal new object F() => throw null;", "F", "F", null, "System.Func<System.Object>"); // object/dynamic yield return getData("internal void F((object, int) x) { }", "internal new void F((object a, int b) x) { }", "F", "F", null, "System.Action<System.ValueTuple<System.Object, System.Int32>>"); // tuple names yield return getData("internal (object a, int b) F() => throw null;", "internal new (object, int) F() => throw null;", "F", "F", null, "System.Func<System.ValueTuple<System.Object, System.Int32>>"); // tuple names yield return getData("internal void F(System.IntPtr x) { }", "internal new void F(nint x) { }", "F", "F", null, "System.Action<System.IntPtr>"); // System.IntPtr/nint yield return getData("internal nint F() => throw null;", "internal new System.IntPtr F() => throw null;", "F", "F", null, "System.Func<System.IntPtr>"); // System.IntPtr/nint yield return getData("internal void F(object x) { }", @"#nullable enable internal new void F(object? x) { } #nullable disable", "F", "F", null, "System.Action<System.Object>"); // different nullability yield return getData( @"#nullable enable internal object? F() => throw null!; #nullable disable", "internal new object F() => throw null;", "F", "F", null, "System.Func<System.Object>"); // different nullability yield return getData("internal void F() { }", "internal void F<T>() { }", "F", "F"); // different arity yield return getData("internal void F() { }", "internal void F<T>() { }", "F<int>", "F<int>", null, "System.Action"); // different arity yield return getData("internal void F<T>() { }", "internal void F() { }", "F", "F"); // different arity yield return getData("internal void F<T>() { }", "internal void F() { }", "F<int>", "F<int>", null, "System.Action"); // different arity yield return getData("internal void F<T>() { }", "internal void F<T, U>() { }", "F<int>", "F<int>", null, "System.Action"); // different arity yield return getData("internal void F<T>() { }", "internal void F<T, U>() { }", "F<int, object>", "F<int, object>", null, "System.Action"); // different arity yield return getData("internal void F<T>(T t) { }", "internal new void F<U>(U u) { }", "F<int>", "F<int>", null, "System.Action<System.Int32>"); // different type parameter names yield return getData("internal void F<T>(T t) where T : class { }", "internal new void F<T>(T t) { }", "F<object>", "F<object>", null, "System.Action<System.Object>"); // different type parameter constraints yield return getData("internal void F<T>(T t) { }", "internal new void F<T>(T t) where T : class { }", "F<object>", "F<object>", null, "System.Action<System.Object>"); // different type parameter constraints yield return getData("internal void F<T>(T t) { }", "internal new void F<T>(T t) where T : class { }", "base.F<object>", "F<object>", null, "System.Action<System.Object>"); // different type parameter constraints yield return getData("internal void F<T>(T t) where T : class { }", "internal new void F<T>(T t) where T : struct { }", "F<int>", "F<int>", null, "System.Action<System.Int32>"); // different type parameter constraints // https://github.com/dotnet/roslyn/issues/52701: Assert failure: Unexpected value 'LessDerived' of type 'Microsoft.CodeAnalysis.CSharp.MemberResolutionKind' #if !DEBUG yield return getData("internal void F<T>(T t) where T : class { }", "internal new void F<T>(T t) where T : struct { }", "F<object>", "F<object>", new[] { // (5,29): error CS0453: The type 'object' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'B.F<T>(T)' // System.Delegate d = F<object>; Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F<object>").WithArguments("B.F<T>(T)", "T", "object").WithLocation(5, 29) }); // different type parameter constraints #endif static object?[] getData(string methodA, string methodB, string methodGroupExpression, string methodGroupOnly, DiagnosticDescription[]? expectedDiagnostics = null, string? expectedType = null) { if (expectedDiagnostics is null && expectedType is null) { int offset = methodGroupExpression.Length - methodGroupOnly.Length; expectedDiagnostics = new[] { // (5,29): error CS8917: The delegate type could not be inferred. // System.Delegate d = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, methodGroupOnly).WithLocation(5, 29 + offset) }; } return new object?[] { methodA, methodB, methodGroupExpression, expectedDiagnostics, expectedType }; } } [Theory] [MemberData(nameof(GetBaseAndDerivedTypesData))] public void MethodGroup_BaseAndDerivedTypes(string methodA, string methodB, string methodGroupExpression, DiagnosticDescription[]? expectedDiagnostics, string? expectedType) { var source = $@"partial class B {{ void M() {{ System.Delegate d = {methodGroupExpression}; System.Console.Write(d.GetDelegateTypeName()); }} static void Main() {{ new B().M(); }} }} abstract class A {{ {methodA} }} partial class B : A {{ {methodB} }}"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); if (expectedDiagnostics is null) { CompileAndVerify(comp, expectedOutput: expectedType); } else { comp.VerifyDiagnostics(expectedDiagnostics); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value; var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); } public static IEnumerable<object?[]> GetExtensionMethodsSameScopeData() { yield return getData("internal static void F(this object x) { }", "internal static void F(this string x) { }", "string.Empty.F", "F", null, "B.F", "System.Action"); // different parameter type yield return getData("internal static void F(this object x) { }", "internal static void F(this string x) { }", "this.F", "F", null, "A.F", "System.Action"); // different parameter type yield return getData("internal static void F(this object x) { }", "internal static void F(this object x, object y) { }", "this.F", "F"); // different number of parameters yield return getData("internal static void F(this object x, object y) { }", "internal static void F(this object x, ref object y) { }", "this.F", "F"); // different parameter ref kind yield return getData("internal static void F(this object x, ref object y) { }", "internal static void F(this object x, object y) { }", "this.F", "F"); // different parameter ref kind yield return getData("internal static object F(this object x) => throw null;", "internal static ref object F(this object x) => throw null;", "this.F", "F"); // different return ref kind yield return getData("internal static ref object F(this object x) => throw null;", "internal static object F(this object x) => throw null;", "this.F", "F"); // different return ref kind yield return getData("internal static void F(this object x, object y) { }", "internal static void F<T>(this object x, T y) { }", "this.F", "F"); // different arity yield return getData("internal static void F(this object x, object y) { }", "internal static void F<T>(this object x, T y) { }", "this.F<int>", "F<int>", null, "B.F", "System.Action<System.Int32>"); // different arity yield return getData("internal static void F<T>(this object x) { }", "internal static void F(this object x) { }", "this.F", "F"); // different arity yield return getData("internal static void F<T>(this object x) { }", "internal static void F(this object x) { }", "this.F<int>", "F<int>", null, "A.F", "System.Action"); // different arity yield return getData("internal static void F<T>(this T t) where T : class { }", "internal static void F<T>(this T t) { }", "this.F<object>", "F<object>", new[] { // (5,29): error CS0121: The call is ambiguous between the following methods or properties: 'A.F<T>(T)' and 'B.F<T>(T)' // System.Delegate d = this.F<object>; Diagnostic(ErrorCode.ERR_AmbigCall, "this.F<object>").WithArguments("A.F<T>(T)", "B.F<T>(T)").WithLocation(5, 29) }); // different type parameter constraints yield return getData("internal static void F<T>(this T t) { }", "internal static void F<T>(this T t) where T : class { }", "this.F<object>", "F<object>", new[] { // (5,29): error CS0121: The call is ambiguous between the following methods or properties: 'A.F<T>(T)' and 'B.F<T>(T)' // System.Delegate d = this.F<object>; Diagnostic(ErrorCode.ERR_AmbigCall, "this.F<object>").WithArguments("A.F<T>(T)", "B.F<T>(T)").WithLocation(5, 29) }); // different type parameter constraints yield return getData("internal static void F<T>(this T t) where T : class { }", "internal static void F<T>(this T t) where T : struct { }", "this.F<int>", "F<int>", new[] { // (5,34): error CS0123: No overload for 'F' matches delegate 'Action' // System.Delegate d = this.F<int>; Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "F<int>").WithArguments("F", "System.Action").WithLocation(5, 34) }); // different type parameter constraints static object?[] getData(string methodA, string methodB, string methodGroupExpression, string methodGroupOnly, DiagnosticDescription[]? expectedDiagnostics = null, string? expectedMethod = null, string? expectedType = null) { if (expectedDiagnostics is null && expectedType is null) { int offset = methodGroupExpression.Length - methodGroupOnly.Length; expectedDiagnostics = new[] { // (5,29): error CS8917: The delegate type could not be inferred. // System.Delegate d = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, methodGroupOnly).WithLocation(5, 29 + offset) }; } return new object?[] { methodA, methodB, methodGroupExpression, expectedDiagnostics, expectedMethod, expectedType }; } } [Theory] [MemberData(nameof(GetExtensionMethodsSameScopeData))] public void MethodGroup_ExtensionMethodsSameScope(string methodA, string methodB, string methodGroupExpression, DiagnosticDescription[]? expectedDiagnostics, string? expectedMethod, string? expectedType) { var source = $@"class Program {{ void M() {{ System.Delegate d = {methodGroupExpression}; System.Console.Write(""{{0}}: {{1}}"", d.GetDelegateMethodName(), d.GetDelegateTypeName()); }} static void Main() {{ new Program().M(); }} }} static class A {{ {methodA} }} static class B {{ {methodB} }}"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); if (expectedDiagnostics is null) { CompileAndVerify(comp, expectedOutput: $"{expectedMethod}: {expectedType}"); } else { comp.VerifyDiagnostics(expectedDiagnostics); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value; var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); var symbolInfo = model.GetSymbolInfo(expr); // https://github.com/dotnet/roslyn/issues/52870: GetSymbolInfo() should return resolved method from method group. Assert.Null(symbolInfo.Symbol); } public static IEnumerable<object?[]> GetExtensionMethodsDifferentScopeData() { yield return getData("internal static void F(this object x) { }", "internal static void F(this object x) { }", "this.F", "F", null, "A.F", "System.Action"); // hiding yield return getData("internal static void F(this object x) { }", "internal static void F(this object y) { }", "this.F", "F", null, "A.F", "System.Action"); // different parameter name yield return getData("internal static void F(this object x) { }", "internal static void F(this string x) { }", "string.Empty.F", "F", null, "A.F", "System.Action"); // different parameter type yield return getData("internal static void F(this object x) { }", "internal static void F(this string x) { }", "this.F", "F", null, "A.F", "System.Action"); // different parameter type yield return getData("internal static void F(this object x) { }", "internal static void F(this object x, object y) { }", "this.F", "F"); // different number of parameters yield return getData("internal static void F(this object x, object y) { }", "internal static void F(this object x, ref object y) { }", "this.F", "F"); // different parameter ref kind yield return getData("internal static void F(this object x, ref object y) { }", "internal static void F(this object x, object y) { }", "this.F", "F"); // different parameter ref kind yield return getData("internal static object F(this object x) => throw null;", "internal static ref object F(this object x) => throw null;", "this.F", "F"); // different return ref kind yield return getData("internal static ref object F(this object x) => throw null;", "internal static object F(this object x) => throw null;", "this.F", "F"); // different return ref kind yield return getData("internal static void F(this object x, System.IntPtr y) { }", "internal static void F(this object x, nint y) { }", "this.F", "F", null, "A.F", "System.Action<System.IntPtr>"); // System.IntPtr/nint yield return getData("internal static nint F(this object x) => throw null;", "internal static System.IntPtr F(this object x) => throw null;", "this.F", "F", null, "A.F", "System.Func<System.IntPtr>"); // System.IntPtr/nint yield return getData("internal static void F(this object x, object y) { }", "internal static void F<T>(this object x, T y) { }", "this.F", "F"); // different arity yield return getData("internal static void F(this object x, object y) { }", "internal static void F<T>(this object x, T y) { }", "this.F<int>", "F<int>", null, "N.B.F", "System.Action<System.Int32>"); // different arity yield return getData("internal static void F<T>(this object x) { }", "internal static void F(this object x) { }", "this.F", "F"); // different arity yield return getData("internal static void F<T>(this object x) { }", "internal static void F(this object x) { }", "this.F<int>", "F<int>", null, "A.F", "System.Action"); // different arity yield return getData("internal static void F<T>(this T t) where T : class { }", "internal static void F<T>(this T t) { }", "this.F<object>", "F<object>", null, "A.F", "System.Action"); // different type parameter constraints yield return getData("internal static void F<T>(this T t) { }", "internal static void F<T>(this T t) where T : class { }", "this.F<object>", "F<object>", null, "A.F", "System.Action"); // different type parameter constraints yield return getData("internal static void F<T>(this T t) where T : class { }", "internal static void F<T>(this T t) where T : struct { }", "this.F<int>", "F<int>", new[] { // (6,34): error CS0123: No overload for 'F' matches delegate 'Action' // System.Delegate d = this.F<int>; Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "F<int>").WithArguments("F", "System.Action").WithLocation(6, 34) }); // different type parameter constraints static object?[] getData(string methodA, string methodB, string methodGroupExpression, string methodGroupOnly, DiagnosticDescription[]? expectedDiagnostics = null, string? expectedMethod = null, string? expectedType = null) { if (expectedDiagnostics is null && expectedType is null) { int offset = methodGroupExpression.Length - methodGroupOnly.Length; expectedDiagnostics = new[] { // (6,29): error CS8917: The delegate type could not be inferred. // System.Delegate d = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, methodGroupOnly).WithLocation(6, 29 + offset) }; } return new object?[] { methodA, methodB, methodGroupExpression, expectedDiagnostics, expectedMethod, expectedType }; } } [Theory] [MemberData(nameof(GetExtensionMethodsDifferentScopeData))] public void MethodGroup_ExtensionMethodsDifferentScope(string methodA, string methodB, string methodGroupExpression, DiagnosticDescription[]? expectedDiagnostics, string? expectedMethod, string? expectedType) { var source = $@"using N; class Program {{ void M() {{ System.Delegate d = {methodGroupExpression}; System.Console.Write(""{{0}}: {{1}}"", d.GetDelegateMethodName(), d.GetDelegateTypeName()); }} static void Main() {{ new Program().M(); }} }} static class A {{ {methodA} }} namespace N {{ static class B {{ {methodB} }} }}"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); if (expectedDiagnostics is null) { CompileAndVerify(comp, expectedOutput: $"{expectedMethod}: {expectedType}"); } else { comp.VerifyDiagnostics(expectedDiagnostics); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value; var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); var symbolInfo = model.GetSymbolInfo(expr); // https://github.com/dotnet/roslyn/issues/52870: GetSymbolInfo() should return resolved method from method group. Assert.Null(symbolInfo.Symbol); } [WorkItem(55923, "https://github.com/dotnet/roslyn/issues/55923")] [Fact] public void ConvertMethodGroupToObject_01() { var source = @"class Program { static object GetValue() => 0; static void Main() { object x = GetValue; x = GetValue; x = (object)GetValue; #pragma warning disable 8974 object y = GetValue; y = GetValue; y = (object)GetValue; #pragma warning restore 8974 } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,20): error CS0428: Cannot convert method group 'GetValue' to non-delegate type 'object'. Did you intend to invoke the method? // object x = GetValue; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "GetValue").WithArguments("GetValue", "object").WithLocation(6, 20), // (7,13): error CS0428: Cannot convert method group 'GetValue' to non-delegate type 'object'. Did you intend to invoke the method? // x = GetValue; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "GetValue").WithArguments("GetValue", "object").WithLocation(7, 13), // (8,13): error CS0030: Cannot convert type 'method' to 'object' // x = (object)GetValue; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(object)GetValue").WithArguments("method", "object").WithLocation(8, 13), // (10,20): error CS0428: Cannot convert method group 'GetValue' to non-delegate type 'object'. Did you intend to invoke the method? // object y = GetValue; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "GetValue").WithArguments("GetValue", "object").WithLocation(10, 20), // (11,13): error CS0428: Cannot convert method group 'GetValue' to non-delegate type 'object'. Did you intend to invoke the method? // y = GetValue; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "GetValue").WithArguments("GetValue", "object").WithLocation(11, 13), // (12,13): error CS0030: Cannot convert type 'method' to 'object' // y = (object)GetValue; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(object)GetValue").WithArguments("method", "object").WithLocation(12, 13)); var expectedDiagnostics = new[] { // (6,20): warning CS8974: Converting method group 'GetValue' to non-delegate type 'object'. Did you intend to invoke the method? // object x = GetValue; Diagnostic(ErrorCode.WRN_MethGrpToNonDel, "GetValue").WithArguments("GetValue", "object").WithLocation(6, 20), // (7,13): warning CS8974: Converting method group 'GetValue' to non-delegate type 'object'. Did you intend to invoke the method? // x = GetValue; Diagnostic(ErrorCode.WRN_MethGrpToNonDel, "GetValue").WithArguments("GetValue", "object").WithLocation(7, 13) }; comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [WorkItem(55923, "https://github.com/dotnet/roslyn/issues/55923")] [Fact] public void ConvertMethodGroupToObject_02() { var source = @"class Program { static int F() => 0; static object F1() => F; static object F2() => (object)F; static object F3() { return F; } static object F4() { return (object)F; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (4,27): error CS0428: Cannot convert method group 'F' to non-delegate type 'object'. Did you intend to invoke the method? // static object F1() => F; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "object").WithLocation(4, 27), // (5,27): error CS0030: Cannot convert type 'method' to 'object' // static object F2() => (object)F; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(object)F").WithArguments("method", "object").WithLocation(5, 27), // (6,33): error CS0428: Cannot convert method group 'F' to non-delegate type 'object'. Did you intend to invoke the method? // static object F3() { return F; } Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "object").WithLocation(6, 33), // (7,33): error CS0030: Cannot convert type 'method' to 'object' // static object F4() { return (object)F; } Diagnostic(ErrorCode.ERR_NoExplicitConv, "(object)F").WithArguments("method", "object").WithLocation(7, 33)); var expectedDiagnostics = new[] { // (4,27): warning CS8974: Converting method group 'F' to non-delegate type 'object'. Did you intend to invoke the method? // static object F1() => F; Diagnostic(ErrorCode.WRN_MethGrpToNonDel, "F").WithArguments("F", "object").WithLocation(4, 27), // (6,33): warning CS8974: Converting method group 'F' to non-delegate type 'object'. Did you intend to invoke the method? // static object F3() { return F; } Diagnostic(ErrorCode.WRN_MethGrpToNonDel, "F").WithArguments("F", "object").WithLocation(6, 33) }; comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [WorkItem(55923, "https://github.com/dotnet/roslyn/issues/55923")] [Fact] public void ConvertMethodGroupToObject_03() { var source = @"class Program { static int F() => 0; static void Main() { object[] a = new[] { F, (object)F, F }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,30): error CS0428: Cannot convert method group 'F' to non-delegate type 'object'. Did you intend to invoke the method? // object[] a = new[] { F, (object)F, F }; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "object").WithLocation(6, 30), // (6,33): error CS0030: Cannot convert type 'method' to 'object' // object[] a = new[] { F, (object)F, F }; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(object)F").WithArguments("method", "object").WithLocation(6, 33), // (6,44): error CS0428: Cannot convert method group 'F' to non-delegate type 'object'. Did you intend to invoke the method? // object[] a = new[] { F, (object)F, F }; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "object").WithLocation(6, 44)); var expectedDiagnostics = new[] { // (6,30): warning CS8974: Converting method group 'F' to non-delegate type 'object'. Did you intend to invoke the method? // object[] a = new[] { F, (object)F, F }; Diagnostic(ErrorCode.WRN_MethGrpToNonDel, "F").WithArguments("F", "object").WithLocation(6, 30), // (6,44): warning CS8974: Converting method group 'F' to non-delegate type 'object'. Did you intend to invoke the method? // object[] a = new[] { F, (object)F, F }; Diagnostic(ErrorCode.WRN_MethGrpToNonDel, "F").WithArguments("F", "object").WithLocation(6, 44) }; comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void InstanceMethods_01() { var source = @"using System; class Program { object F1() => null; void F2(object x, int y) { } void F() { Delegate d1 = F1; Delegate d2 = this.F2; Console.WriteLine(""{0}, {1}"", d1.GetDelegateTypeName(), d2.GetDelegateTypeName()); } static void Main() { new Program().F(); } }"; CompileAndVerify(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, expectedOutput: "System.Func<System.Object>, System.Action<System.Object, System.Int32>"); } [Fact] public void InstanceMethods_02() { var source = @"using System; class A { protected virtual void F() { Console.WriteLine(nameof(A)); } } class B : A { protected override void F() { Console.WriteLine(nameof(B)); } static void Invoke(Delegate d) { d.DynamicInvoke(); } void M() { Invoke(F); Invoke(this.F); Invoke(base.F); } static void Main() { new B().M(); } }"; CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, expectedOutput: @"B B A"); } [Fact] public void InstanceMethods_03() { var source = @"using System; class A { protected void F() { Console.WriteLine(nameof(A)); } } class B : A { protected new void F() { Console.WriteLine(nameof(B)); } static void Invoke(Delegate d) { d.DynamicInvoke(); } void M() { Invoke(F); Invoke(this.F); Invoke(base.F); } static void Main() { new B().M(); } }"; CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, expectedOutput: @"B B A"); } [Fact] public void InstanceMethods_04() { var source = @"class Program { T F<T>() => default; static void Main() { var p = new Program(); System.Delegate d = p.F; object o = (System.Delegate)p.F; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (7,31): error CS8917: The delegate type could not be inferred. // System.Delegate d = p.F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F").WithLocation(7, 31), // (8,20): error CS0030: Cannot convert type 'method' to 'Delegate' // object o = (System.Delegate)p.F; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(System.Delegate)p.F").WithArguments("method", "System.Delegate").WithLocation(8, 20)); } [Fact] public void MethodGroup_Inaccessible() { var source = @"using System; class A { private static void F() { } internal static void F(object o) { } } class B { static void Main() { Delegate d = A.F; Console.WriteLine(d.GetDelegateTypeName()); } }"; CompileAndVerify(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, expectedOutput: "System.Action<System.Object>"); } [Fact] public void MethodGroup_IncorrectArity() { var source = @"class Program { static void F0(object o) { } static void F0<T>(object o) { } static void F1(object o) { } static void F1<T, U>(object o) { } static void F2<T>(object o) { } static void F2<T, U>(object o) { } static void Main() { System.Delegate d; d = F0<int, object>; d = F1<int>; d = F2; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (12,13): error CS0308: The non-generic method 'Program.F0(object)' cannot be used with type arguments // d = F0<int, object>; Diagnostic(ErrorCode.ERR_HasNoTypeVars, "F0<int, object>").WithArguments("Program.F0(object)", "method").WithLocation(12, 13), // (13,13): error CS0308: The non-generic method 'Program.F1(object)' cannot be used with type arguments // d = F1<int>; Diagnostic(ErrorCode.ERR_HasNoTypeVars, "F1<int>").WithArguments("Program.F1(object)", "method").WithLocation(13, 13), // (14,13): error CS8917: The delegate type could not be inferred. // d = F2; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F2").WithLocation(14, 13)); } [Fact] public void ExtensionMethods_01() { var source = @"static class E { internal static void F1(this object x, int y) { } internal static void F2(this object x) { } } class Program { void F2(int x) { } static void Main() { System.Delegate d; var p = new Program(); d = p.F1; d = p.F2; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (14,15): error CS8917: The delegate type could not be inferred. // d = p.F2; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F2").WithLocation(14, 15)); } [Fact] public void ExtensionMethods_02() { var source = @"using System; static class E { internal static void F(this System.Type x, int y) { } internal static void F(this string x) { } } class Program { static void Main() { Delegate d1 = typeof(Program).F; Delegate d2 = """".F; Console.WriteLine(""{0}, {1}"", d1.GetDelegateTypeName(), d2.GetDelegateTypeName()); } }"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "System.Action<System.Int32>, System.Action"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var exprs = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Select(d => d.Initializer!.Value).ToArray(); Assert.Equal(2, exprs.Length); foreach (var expr in exprs) { var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); } } [Fact] public void ExtensionMethods_03() { var source = @"using N; namespace N { static class E1 { internal static void F1(this object x, int y) { } internal static void F2(this object x, int y) { } internal static void F2(this object x) { } internal static void F3(this object x) { } } } static class E2 { internal static void F1(this object x) { } } class Program { static void Main() { System.Delegate d; var p = new Program(); d = p.F1; d = p.F2; d = p.F3; d = E1.F1; d = E2.F1; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (22,15): error CS8917: The delegate type could not be inferred. // d = p.F1; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F1").WithLocation(22, 15), // (23,15): error CS8917: The delegate type could not be inferred. // d = p.F2; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F2").WithLocation(23, 15)); } [Fact] public void ExtensionMethods_04() { var source = @"static class E { internal static void F1(this object x, int y) { } } static class Program { static void F2(this object x) { } static void Main() { System.Delegate d; d = E.F1; d = F2; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics(); } [Fact] public void ExtensionMethods_05() { var source = @"using System; static class E { internal static void F(this A a) { } } class A { } class B : A { static void Invoke(Delegate d) { } void M() { Invoke(F); Invoke(this.F); Invoke(base.F); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (14,16): error CS0103: The name 'F' does not exist in the current context // Invoke(F); Diagnostic(ErrorCode.ERR_NameNotInContext, "F").WithArguments("F").WithLocation(14, 16), // (16,21): error CS0117: 'A' does not contain a definition for 'F' // Invoke(base.F); Diagnostic(ErrorCode.ERR_NoSuchMember, "F").WithArguments("A", "F").WithLocation(16, 21)); } [Fact] public void ExtensionMethods_06() { var source = @"static class E { internal static void F1<T>(this object x, T y) { } internal static void F2<T, U>(this T t) { } } class Program { static void F<T>(T t) where T : class { System.Delegate d; d = t.F1; d = t.F2; d = t.F1<int>; d = t.F1<T>; d = t.F2<T, object>; d = t.F2<object, T>; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (11,15): error CS8917: The delegate type could not be inferred. // d = t.F1; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F1").WithLocation(11, 15), // (12,15): error CS8917: The delegate type could not be inferred. // d = t.F2; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F2").WithLocation(12, 15)); } /// <summary> /// Method group with dynamic receiver does not use method group conversion. /// </summary> [Fact] public void DynamicReceiver() { var source = @"using System; class Program { void F() { } static void Main() { dynamic d = new Program(); object obj; try { obj = d.F; } catch (Exception e) { obj = e; } Console.WriteLine(obj.GetType().FullName); } }"; CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, references: new[] { CSharpRef }, expectedOutput: "Microsoft.CSharp.RuntimeBinder.RuntimeBinderException"); } // System.Func<> and System.Action<> cannot be used as the delegate type // when the parameters or return type are not valid type arguments. [WorkItem(55217, "https://github.com/dotnet/roslyn/issues/55217")] [Fact] public void InvalidTypeArguments() { var source = @"unsafe class Program { static int* F() => throw null; static void Main() { System.Delegate d; d = F; d = (int x, int* y) => { }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview, options: TestOptions.UnsafeReleaseExe); comp.VerifyDiagnostics( // (7,13): error CS8917: The delegate type could not be inferred. // d = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F").WithLocation(7, 13), // (8,13): error CS8917: The delegate type could not be inferred. // d = (int x, int* y) => { }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(int x, int* y) => { }").WithLocation(8, 13)); } [Fact] public void GenericDelegateType() { var source = @"using System; class Program { static void Main() { Delegate d = F<int>(); Console.WriteLine(d.GetDelegateTypeName()); } unsafe static Delegate F<T>() { return (T t, int* p) => { }; } }"; // When we synthesize delegate types with parameter types (such as int*) that cannot // be used as type arguments, run the program to report the actual delegate type. var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.UnsafeReleaseExe); comp.VerifyDiagnostics( // (11,16): error CS8917: The delegate type could not be inferred. // return (T t, int* p) => { }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(T t, int* p) => { }").WithLocation(11, 16)); } [Fact] public void Member_01() { var source = @"using System; class Program { static void Main() { Console.WriteLine((() => { }).GetType()); } }"; var expectedDiagnostics = new[] { // (6,27): error CS0023: Operator '.' cannot be applied to operand of type 'lambda expression' // Console.WriteLine((() => { }).GetType()); Diagnostic(ErrorCode.ERR_BadUnaryOp, "(() => { }).GetType").WithArguments(".", "lambda expression").WithLocation(6, 27) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void Member_02() { var source = @"using System; class Program { static void Main() { Console.WriteLine(Main.GetType()); } }"; var expectedDiagnostics = new[] { // (6,27): error CS0119: 'Program.Main()' is a method, which is not valid in the given context // Console.WriteLine(Main.GetType()); Diagnostic(ErrorCode.ERR_BadSKunknown, "Main").WithArguments("Program.Main()", "method").WithLocation(6, 27) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(expectedDiagnostics); } /// <summary> /// Custom modifiers should not affect delegate signature. /// </summary> [Fact] public void CustomModifiers_01() { var sourceA = @".class public A { .method public static void F1(object modopt(int32) x) { ldnull throw } .method public static object modopt(int32) F2() { ldnull throw } }"; var refA = CompileIL(sourceA); var sourceB = @"using System; class B { static void Report(Delegate d) { Console.WriteLine(d.GetDelegateTypeName()); } static void Main() { Report(A.F1); Report(A.F2); } }"; var comp = CreateCompilation(new[] { sourceB, s_utils }, new[] { refA }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"System.Action<System.Object> System.Func<System.Object>"); } /// <summary> /// Custom modifiers should not affect delegate signature. /// </summary> [Fact] public void CustomModifiers_02() { var sourceA = @".class public A { .method public static void F1(object modreq(int32) x) { ldnull throw } .method public static object modreq(int32) F2() { ldnull throw } }"; var refA = CompileIL(sourceA); var sourceB = @"using System; class B { static void Report(Delegate d) { Console.WriteLine(d.GetDelegateTypeName()); } static void Main() { Report(A.F1); Report(A.F2); } }"; var comp = CreateCompilation(new[] { sourceB, s_utils }, new[] { refA }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics( // (10,16): error CS0570: 'A.F1(object)' is not supported by the language // Report(A.F1); Diagnostic(ErrorCode.ERR_BindToBogus, "A.F1").WithArguments("A.F1(object)").WithLocation(10, 16), // (10,16): error CS0648: '' is a type not supported by the language // Report(A.F1); Diagnostic(ErrorCode.ERR_BogusType, "A.F1").WithArguments("").WithLocation(10, 16), // (11,16): error CS0570: 'A.F2()' is not supported by the language // Report(A.F2); Diagnostic(ErrorCode.ERR_BindToBogus, "A.F2").WithArguments("A.F2()").WithLocation(11, 16), // (11,16): error CS0648: '' is a type not supported by the language // Report(A.F2); Diagnostic(ErrorCode.ERR_BogusType, "A.F2").WithArguments("").WithLocation(11, 16)); } [Fact] public void UnmanagedCallersOnlyAttribute_01() { var source = @"using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; class Program { static void Main() { Delegate d = F; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] static void F() { } }"; var comp = CreateCompilation(new[] { source, UnmanagedCallersOnlyAttributeDefinition }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (8,22): error CS8902: 'Program.F()' is attributed with 'UnmanagedCallersOnly' and cannot be converted to a delegate type. Obtain a function pointer to this method. // Delegate d = F; Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeConvertedToDelegate, "F").WithArguments("Program.F()").WithLocation(8, 22)); } [Fact] public void UnmanagedCallersOnlyAttribute_02() { var source = @"using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; class Program { static void Main() { Delegate d = new S().F; } } struct S { } static class E1 { [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] public static void F(this S s) { } } static class E2 { [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] public static void F(this S s) { } }"; var comp = CreateCompilation(new[] { source, UnmanagedCallersOnlyAttributeDefinition }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (8,22): error CS0121: The call is ambiguous between the following methods or properties: 'E1.F(S)' and 'E2.F(S)' // Delegate d = new S().F; Diagnostic(ErrorCode.ERR_AmbigCall, "new S().F").WithArguments("E1.F(S)", "E2.F(S)").WithLocation(8, 22)); } [Fact] public void SystemActionAndFunc_Missing() { var sourceA = @".assembly mscorlib { .ver 0:0:0:0 } .class public System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.ValueType extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.String extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Void extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Boolean extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Int32 extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Delegate extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.MulticastDelegate extends System.Delegate { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } }"; var refA = CompileIL(sourceA, prependDefaultHeader: false, autoInherit: false); var sourceB = @"class Program { static void Main() { System.Delegate d; d = Main; d = () => 1; } }"; var comp = CreateEmptyCompilation(sourceB, new[] { refA }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (6,13): error CS8917: The delegate type could not be inferred. // d = Main; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "Main").WithLocation(6, 13), // (6,13): error CS0518: Predefined type 'System.Action' is not defined or imported // d = Main; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "Main").WithArguments("System.Action").WithLocation(6, 13), // (7,13): error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type // d = () => 1; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Delegate").WithLocation(7, 13), // (7,13): error CS0518: Predefined type 'System.Func`1' is not defined or imported // d = () => 1; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "() => 1").WithArguments("System.Func`1").WithLocation(7, 13)); } private static MetadataReference GetCorlibWithInvalidActionAndFuncOfT() { var sourceA = @".assembly mscorlib { .ver 0:0:0:0 } .class public System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.ValueType extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.String extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.Type extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Void extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Boolean extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Int32 extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Delegate extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Attribute extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Runtime.CompilerServices.RequiredAttributeAttribute extends System.Attribute { .method public hidebysig specialname rtspecialname instance void .ctor(class System.Type t) cil managed { ret } } .class public abstract System.MulticastDelegate extends System.Delegate { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Action`1<T> extends System.MulticastDelegate { .custom instance void System.Runtime.CompilerServices.RequiredAttributeAttribute::.ctor(class System.Type) = ( 01 00 FF 00 00 ) .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } .method public hidebysig instance void Invoke(!T t) { ret } } .class public sealed System.Func`1<T> extends System.MulticastDelegate { .custom instance void System.Runtime.CompilerServices.RequiredAttributeAttribute::.ctor(class System.Type) = ( 01 00 FF 00 00 ) .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } .method public hidebysig instance !T Invoke() { ldnull throw } }"; return CompileIL(sourceA, prependDefaultHeader: false, autoInherit: false); } [Fact] public void SystemActionAndFunc_UseSiteErrors() { var refA = GetCorlibWithInvalidActionAndFuncOfT(); var sourceB = @"class Program { static void F(object o) { } static void Main() { System.Delegate d; d = F; d = () => 1; } }"; var comp = CreateEmptyCompilation(sourceB, new[] { refA }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (9,13): error CS0648: 'Action<T>' is a type not supported by the language // d = F; Diagnostic(ErrorCode.ERR_BogusType, "F").WithArguments("System.Action<T>").WithLocation(9, 13), // (10,13): error CS0648: 'Func<T>' is a type not supported by the language // d = () => 1; Diagnostic(ErrorCode.ERR_BogusType, "() => 1").WithArguments("System.Func<T>").WithLocation(10, 13)); } [Fact] public void SystemLinqExpressionsExpression_Missing() { var sourceA = @".assembly mscorlib { .ver 0:0:0:0 } .class public System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.ValueType extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.String extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.Type extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Void extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Boolean extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Int32 extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Delegate extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.MulticastDelegate extends System.Delegate { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Func`1<T> extends System.MulticastDelegate { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } .method public hidebysig instance !T Invoke() { ldnull throw } } .class public abstract System.Linq.Expressions.Expression extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } }"; var refA = CompileIL(sourceA, prependDefaultHeader: false, autoInherit: false); var sourceB = @"class Program { static void Main() { System.Linq.Expressions.Expression e = () => 1; } }"; var comp = CreateEmptyCompilation(sourceB, new[] { refA }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (5,48): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // System.Linq.Expressions.Expression e = () => 1; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(5, 48), // (5,48): error CS0518: Predefined type 'System.Linq.Expressions.Expression`1' is not defined or imported // System.Linq.Expressions.Expression e = () => 1; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "() => 1").WithArguments("System.Linq.Expressions.Expression`1").WithLocation(5, 48)); } [Fact] public void SystemLinqExpressionsExpression_UseSiteErrors() { var sourceA = @".assembly mscorlib { .ver 0:0:0:0 } .class public System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.ValueType extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.String extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.Type extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Void extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Boolean extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Int32 extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Delegate extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Attribute extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Runtime.CompilerServices.RequiredAttributeAttribute extends System.Attribute { .method public hidebysig specialname rtspecialname instance void .ctor(class System.Type t) cil managed { ret } } .class public abstract System.MulticastDelegate extends System.Delegate { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Func`1<T> extends System.MulticastDelegate { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } .method public hidebysig instance !T Invoke() { ldnull throw } } .class public abstract System.Linq.Expressions.Expression extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Linq.Expressions.LambdaExpression extends System.Linq.Expressions.Expression { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Linq.Expressions.Expression`1<T> extends System.Linq.Expressions.LambdaExpression { .custom instance void System.Runtime.CompilerServices.RequiredAttributeAttribute::.ctor(class System.Type) = ( 01 00 FF 00 00 ) .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } }"; var refA = CompileIL(sourceA, prependDefaultHeader: false, autoInherit: false); var sourceB = @"class Program { static void Main() { System.Linq.Expressions.Expression e = () => 1; } }"; var comp = CreateEmptyCompilation(sourceB, new[] { refA }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (5,48): error CS0648: 'Expression<T>' is a type not supported by the language // System.Linq.Expressions.Expression e = () => 1; Diagnostic(ErrorCode.ERR_BogusType, "() => 1").WithArguments("System.Linq.Expressions.Expression<T>").WithLocation(5, 48)); } // Expression<T> not derived from Expression. private static MetadataReference GetCorlibWithExpressionOfTNotDerivedType() { var sourceA = @".assembly mscorlib { .ver 0:0:0:0 } .class public System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.ValueType extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.String extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.Type extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Void extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Boolean extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Int32 extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Delegate extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.MulticastDelegate extends System.Delegate { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Func`1<T> extends System.MulticastDelegate { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } .method public hidebysig instance !T Invoke() { ldnull throw } } .class public abstract System.Linq.Expressions.Expression extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Linq.Expressions.LambdaExpression extends System.Linq.Expressions.Expression { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Linq.Expressions.Expression`1<T> extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } }"; return CompileIL(sourceA, prependDefaultHeader: false, autoInherit: false); } [Fact] public void SystemLinqExpressionsExpression_NotDerivedType_01() { var refA = GetCorlibWithExpressionOfTNotDerivedType(); var sourceB = @"class Program { static void Main() { System.Linq.Expressions.Expression e = () => 1; } }"; var comp = CreateEmptyCompilation(sourceB, new[] { refA }); comp.VerifyDiagnostics( // (5,48): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // System.Linq.Expressions.Expression e = () => 1; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(5, 48)); } [Fact] public void SystemLinqExpressionsExpression_NotDerivedType_02() { var refA = GetCorlibWithExpressionOfTNotDerivedType(); var sourceB = @"class Program { static T F<T>(T t) where T : System.Linq.Expressions.Expression => t; static void Main() { var e = F(() => 1); } }"; var comp = CreateEmptyCompilation(sourceB, new[] { refA }); comp.VerifyDiagnostics( // (6,17): error CS0311: The type 'System.Linq.Expressions.Expression<System.Func<int>>' cannot be used as type parameter 'T' in the generic type or method 'Program.F<T>(T)'. There is no implicit reference conversion from 'System.Linq.Expressions.Expression<System.Func<int>>' to 'System.Linq.Expressions.Expression'. // var e = F(() => 1); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "F").WithArguments("Program.F<T>(T)", "System.Linq.Expressions.Expression", "T", "System.Linq.Expressions.Expression<System.Func<int>>").WithLocation(6, 17)); } /// <summary> /// System.Linq.Expressions as a type rather than a namespace. /// </summary> [Fact] public void SystemLinqExpressions_IsType() { var sourceA = @"namespace System { public class Object { } public abstract class ValueType { } public class String { } public class Type { } public struct Void { } public struct Boolean { } public struct Int32 { } public struct IntPtr { } public abstract class Delegate { } public abstract class MulticastDelegate : Delegate { } public delegate T Func<T>(); } namespace System.Linq { public class Expressions { public abstract class Expression { } public abstract class LambdaExpression : Expression { } public sealed class Expression<T> : LambdaExpression { } } }"; var sourceB = @"class Program { static void Main() { System.Linq.Expressions.Expression e1 = () => 1; System.Linq.Expressions.LambdaExpression e2 = () => 2; System.Linq.Expressions.Expression<System.Func<int>> e3 = () => 3; } }"; var comp = CreateEmptyCompilation(new[] { sourceA, sourceB }); comp.VerifyDiagnostics( // (5,49): error CS1660: Cannot convert lambda expression to type 'Expressions.Expression' because it is not a delegate type // System.Linq.Expressions.Expression e1 = () => 1; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(5, 49), // (6,55): error CS1660: Cannot convert lambda expression to type 'Expressions.LambdaExpression' because it is not a delegate type // System.Linq.Expressions.LambdaExpression e2 = () => 2; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 2").WithArguments("lambda expression", "System.Linq.Expressions.LambdaExpression").WithLocation(6, 55), // (7,67): error CS1660: Cannot convert lambda expression to type 'Expressions.Expression<Func<int>>' because it is not a delegate type // System.Linq.Expressions.Expression<System.Func<int>> e3 = () => 3; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 3").WithArguments("lambda expression", "System.Linq.Expressions.Expression<System.Func<int>>").WithLocation(7, 67)); } /// <summary> /// System.Linq.Expressions as a nested namespace. /// </summary> [Fact] public void SystemLinqExpressions_IsNestedNamespace() { var sourceA = @"namespace System { public class Object { } public abstract class ValueType { } public class String { } public class Type { } public struct Void { } public struct Boolean { } public struct Int32 { } public struct IntPtr { } public abstract class Delegate { } public abstract class MulticastDelegate : Delegate { } public delegate T Func<T>(); } namespace Root.System.Linq.Expressions { public abstract class Expression { } public abstract class LambdaExpression : Expression { } public sealed class Expression<T> : LambdaExpression { } }"; var sourceB = @"using System; using Root.System.Linq.Expressions; class Program { static void Main() { Expression e1 = () => 1; LambdaExpression e2 = () => 2; Expression<Func<int>> e3 = () => 3; } }"; var comp = CreateEmptyCompilation(new[] { sourceA, sourceB }); comp.VerifyDiagnostics( // (7,25): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // Expression e1 = () => 1; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "Root.System.Linq.Expressions.Expression").WithLocation(7, 25), // (8,31): error CS1660: Cannot convert lambda expression to type 'LambdaExpression' because it is not a delegate type // LambdaExpression e2 = () => 2; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 2").WithArguments("lambda expression", "Root.System.Linq.Expressions.LambdaExpression").WithLocation(8, 31), // (9,36): error CS1660: Cannot convert lambda expression to type 'Expression<Func<int>>' because it is not a delegate type // Expression<Func<int>> e3 = () => 3; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 3").WithArguments("lambda expression", "Root.System.Linq.Expressions.Expression<System.Func<int>>").WithLocation(9, 36)); } [WorkItem(4674, "https://github.com/dotnet/csharplang/issues/4674")] [Fact] public void OverloadResolution_01() { var source = @"using System; class Program { static void M<T>(T t) { Console.WriteLine(""M<T>(T t)""); } static void M(Action<string> a) { Console.WriteLine(""M(Action<string> a)""); } static void F(object o) { } static void Main() { M(F); // C#9: M(Action<string>) } }"; var expectedOutput = "M(Action<string> a)"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [WorkItem(4674, "https://github.com/dotnet/csharplang/issues/4674")] [Fact] public void OverloadResolution_02() { var source = @"using System; class Program { static void Main() { var c = new C(); c.M(Main); // C#9: E.M(object x, Action y) c.M(() => { }); // C#9: E.M(object x, Action y) } } class C { public void M(object y) { Console.WriteLine(""C.M(object y)""); } } static class E { public static void M(this object x, Action y) { Console.WriteLine(""E.M(object x, Action y)""); } }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: @"E.M(object x, Action y) E.M(object x, Action y) "); // Breaking change from C#9 which binds to E.M(object x, Action y). CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, expectedOutput: @"C.M(object y) C.M(object y) "); } [WorkItem(4674, "https://github.com/dotnet/csharplang/issues/4674")] [Fact] public void OverloadResolution_03() { var source = @"using System; class Program { static void Main() { var c = new C(); c.M(Main); // C#9: E.M(object x, Action y) c.M(() => { }); // C#9: E.M(object x, Action y) } } class C { public void M(Delegate d) { Console.WriteLine(""C.M""); } } static class E { public static void M(this object o, Action a) { Console.WriteLine(""E.M""); } }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: @"E.M E.M "); // Breaking change from C#9 which binds to E.M. CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: @"C.M C.M "); } [WorkItem(4674, "https://github.com/dotnet/csharplang/issues/4674")] [Fact] public void OverloadResolution_04() { var source = @"using System; using System.Linq.Expressions; class Program { static void Main() { var c = new C(); c.M(() => 1); } } class C { public void M(Expression e) { Console.WriteLine(""C.M""); } } static class E { public static void M(this object o, Func<int> a) { Console.WriteLine(""E.M""); } }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: @"E.M"); // Breaking change from C#9 which binds to E.M. CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: @"C.M"); } [Fact] public void OverloadResolution_05() { var source = @"using System; class Program { static void Report(string name) { Console.WriteLine(name); } static void FA(Delegate d) { Report(""FA(Delegate)""); } static void FA(Action d) { Report(""FA(Action)""); } static void FB(Delegate d) { Report(""FB(Delegate)""); } static void FB(Func<int> d) { Report(""FB(Func<int>)""); } static void F1() { } static int F2() => 0; static void Main() { FA(F1); FA(F2); FB(F1); FB(F2); FA(() => { }); FA(() => 0); FB(() => { }); FB(() => 0); FA(delegate () { }); FA(delegate () { return 0; }); FB(delegate () { }); FB(delegate () { return 0; }); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (14,12): error CS1503: Argument 1: cannot convert from 'method group' to 'Delegate' // FA(F2); Diagnostic(ErrorCode.ERR_BadArgType, "F2").WithArguments("1", "method group", "System.Delegate").WithLocation(14, 12), // (15,12): error CS1503: Argument 1: cannot convert from 'method group' to 'Delegate' // FB(F1); Diagnostic(ErrorCode.ERR_BadArgType, "F1").WithArguments("1", "method group", "System.Delegate").WithLocation(15, 12), // (18,18): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // FA(() => 0); Diagnostic(ErrorCode.ERR_IllegalStatement, "0").WithLocation(18, 18), // (19,15): error CS1643: Not all code paths return a value in lambda expression of type 'Func<int>' // FB(() => { }); Diagnostic(ErrorCode.ERR_AnonymousReturnExpected, "=>").WithArguments("lambda expression", "System.Func<int>").WithLocation(19, 15), // (22,26): error CS8030: Anonymous function converted to a void returning delegate cannot return a value // FA(delegate () { return 0; }); Diagnostic(ErrorCode.ERR_RetNoObjectRequiredLambda, "return").WithLocation(22, 26), // (23,12): error CS1643: Not all code paths return a value in anonymous method of type 'Func<int>' // FB(delegate () { }); Diagnostic(ErrorCode.ERR_AnonymousReturnExpected, "delegate").WithArguments("anonymous method", "System.Func<int>").WithLocation(23, 12)); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: @"FA(Action) FA(Delegate) FB(Delegate) FB(Func<int>) FA(Action) FA(Delegate) FB(Delegate) FB(Func<int>) FA(Action) FA(Delegate) FB(Delegate) FB(Func<int>) "); } [Fact] public void OverloadResolution_06() { var source = @"using System; using System.Linq.Expressions; class Program { static void Report(string name, Expression e) { Console.WriteLine(""{0}: {1}"", name, e); } static void F(Expression e) { Report(""F(Expression)"", e); } static void F(Expression<Func<int>> e) { Report(""F(Expression<Func<int>>)"", e); } static void Main() { F(() => 0); F(() => string.Empty); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (11,17): error CS0029: Cannot implicitly convert type 'string' to 'int' // F(() => string.Empty); Diagnostic(ErrorCode.ERR_NoImplicitConv, "string.Empty").WithArguments("string", "int").WithLocation(11, 17), // (11,17): error CS1662: Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type // F(() => string.Empty); Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, "string.Empty").WithArguments("lambda expression").WithLocation(11, 17)); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: @"F(Expression<Func<int>>): () => 0 F(Expression): () => String.Empty "); } [Fact] public void OverloadResolution_07() { var source = @"using System; using System.Linq.Expressions; class Program { static void F(Expression e) { } static void F(Expression<Func<int>> e) { } static void Main() { F(delegate () { return 0; }); F(delegate () { return string.Empty; }); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,11): error CS1660: Cannot convert anonymous method to type 'Expression' because it is not a delegate type // F(delegate () { return 0; }); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate () { return 0; }").WithArguments("anonymous method", "System.Linq.Expressions.Expression").WithLocation(9, 11), // (10,11): error CS1660: Cannot convert anonymous method to type 'Expression' because it is not a delegate type // F(delegate () { return string.Empty; }); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate () { return string.Empty; }").WithArguments("anonymous method", "System.Linq.Expressions.Expression").WithLocation(10, 11)); comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics( // (9,11): error CS1946: An anonymous method expression cannot be converted to an expression tree // F(delegate () { return 0; }); Diagnostic(ErrorCode.ERR_AnonymousMethodToExpressionTree, "delegate () { return 0; }").WithLocation(9, 11), // (10,11): error CS1946: An anonymous method expression cannot be converted to an expression tree // F(delegate () { return string.Empty; }); Diagnostic(ErrorCode.ERR_AnonymousMethodToExpressionTree, "delegate () { return string.Empty; }").WithLocation(10, 11)); } [WorkItem(55319, "https://github.com/dotnet/roslyn/issues/55319")] [Fact] public void OverloadResolution_08() { var source = @"using System; using static System.Console; class C { static void Main() { var c = new C(); c.F(x => x); c.F((int x) => x); } void F(Delegate d) => Write(""instance, ""); } static class Extensions { public static void F(this C c, Func<int, int> f) => Write(""extension, ""); }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: "extension, extension, "); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: "extension, instance, "); CompileAndVerify(source, expectedOutput: "extension, instance, "); } [WorkItem(55319, "https://github.com/dotnet/roslyn/issues/55319")] [Fact] public void OverloadResolution_09() { var source = @"using System; using System.Linq.Expressions; using static System.Console; class C { static void Main() { var c = new C(); c.F(x => x); c.F((int x) => x); } void F(Expression e) => Write(""instance, ""); } static class Extensions { public static void F(this C c, Expression<Func<int, int>> e) => Write(""extension, ""); }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: "extension, extension, "); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: "extension, instance, "); CompileAndVerify(source, expectedOutput: "extension, instance, "); } [WorkItem(55319, "https://github.com/dotnet/roslyn/issues/55319")] [Fact] public void OverloadResolution_10() { var source = @"using System; using static System.Console; class C { static object M1(object o) => o; static int M1(int i) => i; static int M2(int i) => i; static void Main() { var c = new C(); c.F(M1); c.F(M2); } void F(Delegate d) => Write(""instance, ""); } static class Extensions { public static void F(this C c, Func<int, int> f) => Write(""extension, ""); }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: "extension, extension, "); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: "extension, instance, "); CompileAndVerify(source, expectedOutput: "extension, instance, "); } [Fact] public void OverloadResolution_11() { var source = @"using System; using System.Linq.Expressions; class C { static object M1(object o) => o; static int M1(int i) => i; static void Main() { F1(x => x); F1(M1); F2(x => x); } static void F1(Delegate d) { } static void F2(Expression e) { } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,12): error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type // F1(x => x); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "x => x").WithArguments("lambda expression", "System.Delegate").WithLocation(9, 12), // (10,12): error CS1503: Argument 1: cannot convert from 'method group' to 'Delegate' // F1(M1); Diagnostic(ErrorCode.ERR_BadArgType, "M1").WithArguments("1", "method group", "System.Delegate").WithLocation(10, 12), // (11,12): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // F2(x => x); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "x => x").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(11, 12)); var expectedDiagnostics10AndLater = new[] { // (9,12): error CS8917: The delegate type could not be inferred. // F1(x => x); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(9, 12), // (10,12): error CS1503: Argument 1: cannot convert from 'method group' to 'Delegate' // F1(M1); Diagnostic(ErrorCode.ERR_BadArgType, "M1").WithArguments("1", "method group", "System.Delegate").WithLocation(10, 12), // (11,12): error CS8917: The delegate type could not be inferred. // F2(x => x); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(11, 12) }; comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics10AndLater); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics10AndLater); } [WorkItem(55691, "https://github.com/dotnet/roslyn/issues/55691")] [Fact] public void OverloadResolution_12() { var source = @"using System; #nullable enable var app = new WebApp(); app.Map(""/sub1"", builder => { builder.UseAuth(); }); app.Map(""/sub2"", (IAppBuilder builder) => { builder.UseAuth(); }); class WebApp : IAppBuilder, IRouteBuilder { public void UseAuth() { } } interface IAppBuilder { void UseAuth(); } interface IRouteBuilder { } static class AppBuilderExtensions { public static IAppBuilder Map(this IAppBuilder app, PathSring path, Action<IAppBuilder> callback) { Console.WriteLine(""AppBuilderExtensions.Map(this IAppBuilder app, PathSring path, Action<IAppBuilder> callback)""); return app; } } static class RouteBuilderExtensions { public static IRouteBuilder Map(this IRouteBuilder routes, string path, Delegate callback) { Console.WriteLine(""RouteBuilderExtensions.Map(this IRouteBuilder routes, string path, Delegate callback)""); return routes; } } struct PathSring { public PathSring(string? path) { Path = path; } public string? Path { get; } public static implicit operator PathSring(string? s) => new PathSring(s); public static implicit operator string?(PathSring path) => path.Path; }"; var expectedOutput = @"AppBuilderExtensions.Map(this IAppBuilder app, PathSring path, Action<IAppBuilder> callback) AppBuilderExtensions.Map(this IAppBuilder app, PathSring path, Action<IAppBuilder> callback) "; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [WorkItem(55691, "https://github.com/dotnet/roslyn/issues/55691")] [Fact] public void OverloadResolution_13() { var source = @"using System; class Program { static void Main() { F(1, () => { }); F(2, Main); } static void F(object obj, Action a) { Console.WriteLine(""F(object obj, Action a)""); } static void F(int i, Delegate d) { Console.WriteLine(""F(int i, Delegate d)""); } }"; var expectedOutput = @"F(object obj, Action a) F(object obj, Action a) "; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [WorkItem(55691, "https://github.com/dotnet/roslyn/issues/55691")] [Fact] public void OverloadResolution_14() { var source = @"using System; using System.Linq.Expressions; class Program { static void Main() { F(() => 1, 2); } static void F(Expression<Func<object>> f, object obj) { Console.WriteLine(""F(Expression<Func<object>> f, object obj)""); } static void F(Expression e, int i) { Console.WriteLine(""F(Expression e, int i)""); } }"; var expectedOutput = @"F(Expression<Func<object>> f, object obj)"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [WorkItem(4674, "https://github.com/dotnet/csharplang/issues/4674")] [Fact] public void OverloadResolution_15() { var source = @"using System; delegate void StringAction(string arg); class Program { static void F<T>(T t) { Console.WriteLine(typeof(T).Name); } static void F(StringAction a) { Console.WriteLine(""StringAction""); } static void M(string arg) { } static void Main() { F((string s) => { }); // C#9: F(StringAction) F(M); // C#9: F(StringAction) } }"; var expectedOutput = @"StringAction StringAction "; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void OverloadResolution_16() { var source = @"using System; class Program { static void F(Func<Func<object>> f, int i) => Report(f); static void F(Func<Func<int>> f, object o) => Report(f); static void Main() { F(() => () => 1, 2); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: @"System.Func`1[System.Func`1[System.Object]]"); // Breaking change from C#9 which binds calls to F(Func<Func<object>>, int). var expectedDiagnostics = new[] { // (8,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.F(Func<Func<object>>, int)' and 'Program.F(Func<Func<int>>, object)' // F(() => () => 1, 2); Diagnostic(ErrorCode.ERR_AmbigCall, "F").WithArguments("Program.F(System.Func<System.Func<object>>, int)", "Program.F(System.Func<System.Func<int>>, object)").WithLocation(8, 9) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void OverloadResolution_17() { var source = @"delegate void StringAction(string arg); class Program { static void F<T>(System.Action<T> a) { } static void F(StringAction a) { } static void Main() { F((string s) => { }); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.F<T>(Action<T>)' and 'Program.F(StringAction)' // F((string s) => { }); Diagnostic(ErrorCode.ERR_AmbigCall, "F").WithArguments("Program.F<T>(System.Action<T>)", "Program.F(StringAction)").WithLocation(8, 9)); } [Fact] public void OverloadResolution_18() { var source = @"delegate void StringAction(string arg); class Program { static void F0<T>(System.Action<T> a) { } static void F1<T>(System.Action<T> a) { } static void F1(StringAction a) { } static void M(string arg) { } static void Main() { F0(M); F1(M); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,9): error CS0411: The type arguments for method 'Program.F0<T>(Action<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F0(M); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F0").WithArguments("Program.F0<T>(System.Action<T>)").WithLocation(10, 9)); } [Fact] public void OverloadResolution_19() { var source = @"delegate void MyAction<T>(T arg); class Program { static void F<T>(System.Action<T> a) { } static void F<T>(MyAction<T> a) { } static void M(string arg) { } static void Main() { F((string s) => { }); F(M); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.F<T>(Action<T>)' and 'Program.F<T>(MyAction<T>)' // F((string s) => { }); Diagnostic(ErrorCode.ERR_AmbigCall, "F").WithArguments("Program.F<T>(System.Action<T>)", "Program.F<T>(MyAction<T>)").WithLocation(9, 9), // (10,9): error CS0411: The type arguments for method 'Program.F<T>(Action<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F(M); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("Program.F<T>(System.Action<T>)").WithLocation(10, 9)); } [Fact] public void OverloadResolution_20() { var source = @"using System; delegate void StringAction(string s); class Program { static void F(Action<string> a) { } static void F(StringAction a) { } static void M(string s) { } static void Main() { F(M); F((string s) => { }); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.F(Action<string>)' and 'Program.F(StringAction)' // F(M); Diagnostic(ErrorCode.ERR_AmbigCall, "F").WithArguments("Program.F(System.Action<string>)", "Program.F(StringAction)").WithLocation(10, 9), // (11,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.F(Action<string>)' and 'Program.F(StringAction)' // F((string s) => { }); Diagnostic(ErrorCode.ERR_AmbigCall, "F").WithArguments("Program.F(System.Action<string>)", "Program.F(StringAction)").WithLocation(11, 9)); } [Fact] public void OverloadResolution_21() { var source = @"using System; class C<T> { public void F(Delegate d) => Report(""F(Delegate d)"", d); public void F(T t) => Report(""F(T t)"", t); public void F(Func<T> f) => Report(""F(Func<T> f)"", f); static void Report(string method, object arg) => Console.WriteLine(""{0}, {1}"", method, arg.GetType()); } class Program { static void Main() { var c = new C<Delegate>(); c.F(() => (Action)null); } }"; string expectedOutput = "F(Func<T> f), System.Func`1[System.Delegate]"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [WorkItem(1361172, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1361172")] [Fact] public void OverloadResolution_22() { var source = @"using System; using System.Linq.Expressions; class C<T> { public void F(Delegate d) => Report(""F(Delegate d)"", d); public void F(T t) => Report(""F(T t)"", t); public void F(Func<T> f) => Report(""F(Func<T> f)"", f); static void Report(string method, object arg) => Console.WriteLine(""{0}, {1}"", method, arg.GetType()); } class Program { static void Main() { var c = new C<Expression>(); c.F(() => Expression.Constant(1)); } }"; string expectedOutput = "F(Func<T> f), System.Func`1[System.Linq.Expressions.Expression]"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void OverloadResolution_23() { var source = @"using System; class Program { static void F(Delegate d) => Console.WriteLine(""F(Delegate d)""); static void F(Func<object> f) => Console.WriteLine(""F(Func<int> f)""); static void Main() { F(() => 1); } }"; string expectedOutput = "F(Func<int> f)"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [WorkItem(1361172, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1361172")] [Fact] public void OverloadResolution_24() { var source = @"using System; using System.Linq.Expressions; class Program { static void F(Expression e) => Console.WriteLine(""F(Expression e)""); static void F(Func<Expression> f) => Console.WriteLine(""F(Func<Expression> f)""); static void Main() { F(() => Expression.Constant(1)); } }"; string expectedOutput = "F(Func<Expression> f)"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [WorkItem(56167, "https://github.com/dotnet/roslyn/issues/56167")] [Fact] public void OverloadResolution_25() { var source = @"using static System.Console; delegate void D(); class Program { static void F(D d) => WriteLine(""D""); static void F<T>(T t) => WriteLine(typeof(T).Name); static void Main() { F(() => { }); } }"; string expectedOutput = "D"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [WorkItem(56167, "https://github.com/dotnet/roslyn/issues/56167")] [Fact] public void OverloadResolution_26() { var source = @"using System; class Program { static void F(Action action) => Console.WriteLine(""Action""); static void F<T>(T t) => Console.WriteLine(typeof(T).Name); static void Main() { int i = 0; F(() => i++); } }"; string expectedOutput = "Action"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [WorkItem(56167, "https://github.com/dotnet/roslyn/issues/56167")] [Fact] public void OverloadResolution_27() { var source = @"using System; using System.Linq.Expressions; class Program { static void F(Action action) => Console.WriteLine(""Action""); static void F(Expression expression) => Console.WriteLine(""Expression""); static int GetValue() => 0; static void Main() { F(() => GetValue()); } }"; string expectedOutput = "Action"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [WorkItem(56319, "https://github.com/dotnet/roslyn/issues/56319")] [Fact] public void OverloadResolution_28() { var source = @"using System; var source = new C<int>(); source.Aggregate(() => 0, (i, j) => i, (i, j) => i, i => i); class C<T> { } static class Extensions { public static TResult Aggregate<TSource, TAccumulate, TResult>( this C<TSource> source, Func<TAccumulate> seedFactory, Func<TAccumulate, TSource, TAccumulate> updateAccumulatorFunc, Func<TAccumulate, TAccumulate, TAccumulate> combineAccumulatorsFunc, Func<TAccumulate, TResult> resultSelector) { Console.WriteLine((typeof(TSource).FullName, typeof(TAccumulate).FullName, typeof(TResult).FullName)); return default; } public static TResult Aggregate<TSource, TAccumulate, TResult>( this C<TSource> source, TAccumulate seed, Func<TAccumulate, TSource, TAccumulate> updateAccumulatorFunc, Func<TAccumulate, TAccumulate, TAccumulate> combineAccumulatorsFunc, Func<TAccumulate, TResult> resultSelector) { Console.WriteLine((typeof(TSource).FullName, typeof(TAccumulate).FullName, typeof(TResult).FullName)); return default; } }"; string expectedOutput = "(System.Int32, System.Int32, System.Int32)"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void OverloadResolution_29() { var source = @"using System; class A { } class B : A { } class Program { static void M<T>(T x, T y) { Console.WriteLine(""M<T>(T x, T y)""); } static void M(Func<object> x, Func<object> y) { Console.WriteLine(""M(Func<object> x, Func<object> y)""); } static void Main() { Func<object> fo = () => new A(); Func<A> fa = () => new A(); M(() => new A(), () => new B()); M(fo, () => new B()); M(fa, () => new B()); } }"; var expectedOutput = @"M(Func<object> x, Func<object> y) M(Func<object> x, Func<object> y) M<T>(T x, T y) "; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void OverloadResolution_30() { var source = @"using System; class Program { static void M<T>(T t, Func<object> f) { Console.WriteLine(""M<T>(T t, Func<object> f)""); } static void M<T>(Func<object> f, T t) { Console.WriteLine(""M<T>(Func<object> f, T t)""); } static object F() => null; static void Main() { M(F, F); M(() => 1, () => 2); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,9): error CS0411: The type arguments for method 'Program.M<T>(T, Func<object>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // M(F, F); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T>(T, System.Func<object>)").WithLocation(9, 9), // (10,9): error CS0411: The type arguments for method 'Program.M<T>(T, Func<object>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // M(() => 1, () => 2); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T>(T, System.Func<object>)").WithLocation(10, 9)); var expectedDiagnostics = new[] { // (9,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M<T>(T, Func<object>)' and 'Program.M<T>(Func<object>, T)' // M(F, F); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M<T>(T, System.Func<object>)", "Program.M<T>(System.Func<object>, T)").WithLocation(9, 9), // (10,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M<T>(T, Func<object>)' and 'Program.M<T>(Func<object>, T)' // M(() => 1, () => 2); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M<T>(T, System.Func<object>)", "Program.M<T>(System.Func<object>, T)").WithLocation(10, 9) }; comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void OverloadResolution_31() { var source = @"using System; using System.Linq.Expressions; class Program { static void M<T>(T t) { Console.WriteLine(""M<T>(T t)""); } static void M(Expression<Func<object>> e) { Console.WriteLine(""M(Expression<Func<object>> e)""); } static void Main() { M(() => string.Empty); } }"; var expectedOutput = "M(Expression<Func<object>> e)"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void OverloadResolution_32() { var source = @"using System; using System.Linq.Expressions; class A { } class B : A { } class Program { static void M<T>(T x, T y) { Console.WriteLine(""M<T>(T x, T y)""); } static void M(Expression<Func<object>> x, Expression<Func<object>> y) { Console.WriteLine(""M(Expression<Func<object>> x, Expression<Func<object>> y)""); } static void Main() { Expression<Func<object>> fo = () => new A(); Expression<Func<A>> fa = () => new A(); M(() => new A(), () => new B()); M(fo, () => new B()); M(fa, () => new B()); } }"; var expectedOutput = @"M(Expression<Func<object>> x, Expression<Func<object>> y) M(Expression<Func<object>> x, Expression<Func<object>> y) M<T>(T x, T y) "; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void OverloadResolution_33() { var source = @"using System; class Program { static void M<T>(object x, T y) { Console.WriteLine(""M<T>(object x, T y)""); } static void M<T, U>(T x, U y) { Console.WriteLine(""M<T, U>(T x, U y)""); } static void Main() { Func<int> f = () => 0; M(() => 1, () => 2); M(() => 1, f); M(f, () => 2); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,9): error CS0411: The type arguments for method 'Program.M<T>(object, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // M(() => 1, () => 2); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T>(object, T)").WithLocation(9, 9), // (10,11): error CS1660: Cannot convert lambda expression to type 'object' because it is not a delegate type // M(() => 1, f); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "object").WithLocation(10, 11), // (11,9): error CS0411: The type arguments for method 'Program.M<T>(object, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // M(f, () => 2); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T>(object, T)").WithLocation(11, 9)); var expectedOutput = @"M<T, U>(T x, U y) M<T, U>(T x, U y) M<T, U>(T x, U y) "; CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void OverloadResolution_34() { var source = @"using System; class Program { static void M<T, U>(Func<T> x, U y) { Console.WriteLine(""M<T, U>(Func<T> x, U y)""); } static void M<T, U>(T x, U y) { Console.WriteLine(""M<T, U>(T x, U y)""); } static void Main() { Func<int> f = () => 0; M(() => 1, () => 2); M(() => 1, f); M(f, () => 2); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,9): error CS0411: The type arguments for method 'Program.M<T, U>(Func<T>, U)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // M(() => 1, () => 2); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T, U>(System.Func<T>, U)").WithLocation(9, 9), // (11,9): error CS0411: The type arguments for method 'Program.M<T, U>(Func<T>, U)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // M(f, () => 2); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T, U>(System.Func<T>, U)").WithLocation(11, 9)); var expectedOutput = @"M<T, U>(Func<T> x, U y) M<T, U>(Func<T> x, U y) M<T, U>(Func<T> x, U y) "; CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void OverloadResolution_35() { var source = @"using System; class Program { static void M(Delegate x, Func<int> y) { Console.WriteLine(""M(Delegate x, Func<int> y)""); } static void M<T, U>(T x, U y) { Console.WriteLine(""M<T, U>(T x, U y)""); } static void Main() { Func<int> f = () => 0; M(() => 1, () => 2); M(() => 1, f); M(f, () => 2); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,11): error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type // M(() => 1, () => 2); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Delegate").WithLocation(9, 11), // (10,11): error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type // M(() => 1, f); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Delegate").WithLocation(10, 11)); var expectedOutput = @"M<T, U>(T x, U y) M<T, U>(T x, U y) M(Delegate x, Func<int> y) "; CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void OverloadResolution_36() { var source = @"using System; class Program { static void F<T>(T t) { Console.WriteLine(""F<{0}>({0} t)"", typeof(T).Name); } static void F(Delegate d) { Console.WriteLine(""F(Delegate d)""); } static void Main() { F(Main); F(() => 1); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,11): error CS1503: Argument 1: cannot convert from 'method group' to 'Delegate' // F(Main); Diagnostic(ErrorCode.ERR_BadArgType, "Main").WithArguments("1", "method group", "System.Delegate").WithLocation(8, 11), // (9,11): error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type // F(() => 1); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Delegate").WithLocation(9, 11)); var expectedOutput = @"F<Action>(Action t) F<Func`1>(Func`1 t)"; CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void OverloadResolution_37() { var source = @"using System; class Program { static void F(object o) { Console.WriteLine(""F(object o)""); } static void F(Delegate d) { Console.WriteLine(""F(Delegate d)""); } static void Main() { F(Main); F(() => 1); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,11): error CS1503: Argument 1: cannot convert from 'method group' to 'object' // F(Main); Diagnostic(ErrorCode.ERR_BadArgType, "Main").WithArguments("1", "method group", "object").WithLocation(8, 11), // (9,11): error CS1660: Cannot convert lambda expression to type 'object' because it is not a delegate type // F(() => 1); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "object").WithLocation(9, 11)); var expectedOutput = @"F(Delegate d) F(Delegate d)"; CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void OverloadResolution_38() { var source = @"using System; class MyString { public static implicit operator MyString(string s) => new MyString(); } class Program { static void F(Delegate d1, Delegate d2, string s) { Console.WriteLine(""F(Delegate d1, Delegate d2, string s)""); } static void F(Func<int> f, Delegate d, MyString s) { Console.WriteLine(""F(Func<int> f, Delegate d, MyString s)""); } static void Main() { F(() => 1, () => 2, string.Empty); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (12,11): error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type // F(() => 1, () => 2, string.Empty); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Delegate").WithLocation(12, 11), // (12,20): error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type // F(() => 1, () => 2, string.Empty); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 2").WithArguments("lambda expression", "System.Delegate").WithLocation(12, 20)); var expectedDiagnostics = new[] { // (12,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.F(Delegate, Delegate, string)' and 'Program.F(Func<int>, Delegate, MyString)' // F(() => 1, () => 2, string.Empty); Diagnostic(ErrorCode.ERR_AmbigCall, "F").WithArguments("Program.F(System.Delegate, System.Delegate, string)", "Program.F(System.Func<int>, System.Delegate, MyString)").WithLocation(12, 9) }; comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void OverloadResolution_39() { var source = @"using System; using System.Linq.Expressions; class C { static void M(Expression e) { Console.WriteLine(""M(Expression e)""); } static void M(object o) { Console.WriteLine(""M(object o)""); } static int F() => 0; static void Main() { M(F); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (10,11): error CS1503: Argument 1: cannot convert from 'method group' to 'Expression' // M(F); Diagnostic(ErrorCode.ERR_BadArgType, "F").WithArguments("1", "method group", "System.Linq.Expressions.Expression").WithLocation(10, 11)); var expectedDiagnostics = new[] { // (10,11): error CS0428: Cannot convert method group 'F' to non-delegate type 'Expression'. Did you intend to invoke the method? // M(F); Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "System.Linq.Expressions.Expression").WithLocation(10, 11) }; comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void OverloadResolution_40() { var source = @"using System; using System.Linq.Expressions; class C { static void M(Expression e) { Console.WriteLine(""M(Expression e)""); } static void M(object o) { Console.WriteLine(""M(object o)""); } static void Main() { M(() => 1); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,11): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // M(() => 1); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(9, 11)); var expectedOutput = @"M(Expression e)"; CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void OverloadResolution_41() { var source = @"using System; using System.Linq.Expressions; class C { static void M(Expression e) { Console.WriteLine(""M(Expression e)""); } static void M(Delegate d) { Console.WriteLine(""M(Delegate d)""); } static int F() => 0; static void Main() { M(F); M(() => 1); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (10,11): error CS1503: Argument 1: cannot convert from 'method group' to 'Expression' // M(F); Diagnostic(ErrorCode.ERR_BadArgType, "F").WithArguments("1", "method group", "System.Linq.Expressions.Expression").WithLocation(10, 11), // (11,11): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // M(() => 1); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(11, 11)); var expectedDiagnostics = new[] { // (10,9): error CS0121: The call is ambiguous between the following methods or properties: 'C.M(Expression)' and 'C.M(Delegate)' // M(F); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C.M(System.Linq.Expressions.Expression)", "C.M(System.Delegate)").WithLocation(10, 9), // (11,9): error CS0121: The call is ambiguous between the following methods or properties: 'C.M(Expression)' and 'C.M(Delegate)' // M(() => 1); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C.M(System.Linq.Expressions.Expression)", "C.M(System.Delegate)").WithLocation(11, 9) }; comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void OverloadResolution_42() { var source = @"using System; using System.Runtime.InteropServices; [ComImport] [Guid(""96A2DE64-6D44-4DA5-BBA4-25F5F07E0E6B"")] interface I { void F(Delegate d, short s); void F(Action a, ref int i); } class C : I { void I.F(Delegate d, short s) => Console.WriteLine(""I.F(Delegate d, short s)""); void I.F(Action a, ref int i) => Console.WriteLine(""I.F(Action a, ref int i)""); } class Program { static void M(I i) { i.F(() => { }, 1); } static void Main() { M(new C()); } }"; var expectedOutput = @"I.F(Action a, ref int i)"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [WorkItem(4674, "https://github.com/dotnet/csharplang/issues/4674")] [Fact] public void OverloadResolution_43() { var source = @"using System; using System.Linq.Expressions; class Program { static int F() => 0; static void Main() { var c = new C(); c.M(F); } } class C { public void M(Expression e) { Console.WriteLine(""C.M""); } } static class E { public static void M(this object o, Func<int> a) { Console.WriteLine(""E.M""); } }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: @"E.M"); var expectedDiagnostics = new[] { // (9,13): error CS0428: Cannot convert method group 'F' to non-delegate type 'Expression'. Did you intend to invoke the method? // c.M(F); Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "System.Linq.Expressions.Expression").WithLocation(9, 13) }; // Breaking change from C#9 which binds to E.M. var comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void OverloadResolution_44() { var source = @"using System; using System.Linq.Expressions; class A { public static void F1(Func<int> f) { Console.WriteLine(""A.F1(Func<int> f)""); } public void F2(Func<int> f) { Console.WriteLine(""A.F2(Func<int> f)""); } } class B : A { public static void F1(Delegate d) { Console.WriteLine(""B.F1(Delegate d)""); } public void F2(Expression e) { Console.WriteLine(""B.F2(Expression e)""); } } class Program { static void Main() { B.F1(() => 1); var b = new B(); b.F2(() => 2); } }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: @"A.F1(Func<int> f) A.F2(Func<int> f)"); // Breaking change from C#9 which binds to methods from A. var expectedOutput = @"B.F1(Delegate d) B.F2(Expression e)"; CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void OverloadResolution_45() { var source = @"using System; using System.Linq.Expressions; class A { public object this[Func<int> f] => Report(""A.this[Func<int> f]""); public static object Report(string message) { Console.WriteLine(message); return null; } } class B1 : A { public object this[Delegate d] => Report(""B1.this[Delegate d]""); } class B2 : A { public object this[Expression e] => Report(""B2.this[Expression e]""); } class Program { static void Main() { var b1 = new B1(); _ = b1[() => 1]; var b2 = new B2(); _ = b2[() => 2]; } }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: @"A.this[Func<int> f] A.this[Func<int> f]"); // Breaking change from C#9 which binds to methods from A. var expectedOutput = @"B1.this[Delegate d] B2.this[Expression e]"; CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void BestCommonType_01() { var source = @"using System; delegate int StringIntDelegate(string s); class Program { static int M(string s) => s.Length; static void Main() { StringIntDelegate d = M; var a1 = new[] { d, (string s) => int.Parse(s) }; var a2 = new[] { (string s) => int.Parse(s), d }; Report(a1[1]); Report(a2[0]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; string expectedOutput = @"StringIntDelegate StringIntDelegate"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); } [Fact] public void BestCommonType_02() { var source = @"using System; delegate int StringIntDelegate(string s); class Program { static int M(string s) => s.Length; static void F(bool b) { StringIntDelegate d = M; var c1 = b ? d : ((string s) => int.Parse(s)); var c2 = b ? ((string s) => int.Parse(s)) : d; Report(c1); Report(c2); } static void Main() { F(false); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; string expectedOutput = @"StringIntDelegate StringIntDelegate"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); } [Fact] public void BestCommonType_03() { var source = @"using System; delegate int StringIntDelegate(string s); class Program { static int M(string s) => s.Length; static void Main() { var f1 = (bool b) => { if (b) return (StringIntDelegate)M; return ((string s) => int.Parse(s)); }; var f2 = (bool b) => { if (b) return ((string s) => int.Parse(s)); return (StringIntDelegate)M; }; Report(f1(true)); Report(f2(true)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"StringIntDelegate StringIntDelegate"); } [Fact] public void BestCommonType_04() { var source = @"using System; delegate int StringIntDelegate(string s); class Program { static int M(string s) => s.Length; static void Main() { var f1 = (bool b) => { if (b) return M; return ((string s) => int.Parse(s)); }; var f2 = (bool b) => { if (b) return ((string s) => int.Parse(s)); return M; }; Report(f1(true)); Report(f2(true)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Func`2[System.String,System.Int32] System.Func`2[System.String,System.Int32]"); } [Fact] public void BestCommonType_05() { var source = @"using System; class Program { static int M1(string s) => s.Length; static int M2(string s) => int.Parse(s); static void Main() { var a1 = new[] { M1, (string s) => int.Parse(s) }; var a2 = new[] { (string s) => s.Length, M2 }; Report(a1[1]); Report(a2[1]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { M1, (string s) => int.Parse(s) }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { M1, (string s) => int.Parse(s) }").WithLocation(8, 18), // (9,18): error CS0826: No best type found for implicitly-typed array // var a2 = new[] { (string s) => s.Length, M2 }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { (string s) => s.Length, M2 }").WithLocation(9, 18)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Func`2[System.String,System.Int32] System.Func`2[System.String,System.Int32]"); } [Fact] public void BestCommonType_06() { var source = @"using System; class Program { static void F1<T>(T t) { } static T F2<T>() => default; static void Main() { var a1 = new[] { F1<object>, F1<string> }; var a2 = new[] { F2<object>, F2<string> }; Report(a1[0]); Report(a2[0]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { F1<object>, F1<string> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F1<object>, F1<string> }").WithLocation(8, 18), // (9,18): error CS0826: No best type found for implicitly-typed array // var a2 = new[] { F2<object>, F2<string> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F2<object>, F2<string> }").WithLocation(9, 18)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Action`1[System.String] System.Func`1[System.Object]"); } [Fact] public void BestCommonType_07() { var source = @"class Program { static void F1<T>(T t) { } static T F2<T>() => default; static T F3<T>(T t) => t; static void Main() { var a1 = new[] { F1<int>, F1<object> }; var a2 = new[] { F2<nint>, F2<System.IntPtr> }; var a3 = new[] { F3<string>, F3<object> }; } }"; var expectedDiagnostics = new[] { // (8,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { F1<int>, F1<object> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F1<int>, F1<object> }").WithLocation(8, 18), // (9,18): error CS0826: No best type found for implicitly-typed array // var a2 = new[] { F2<nint>, F2<System.IntPtr> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F2<nint>, F2<System.IntPtr> }").WithLocation(9, 18), // (10,18): error CS0826: No best type found for implicitly-typed array // var a3 = new[] { F3<string>, F3<object> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F3<string>, F3<object> }").WithLocation(10, 18) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void BestCommonType_08() { var source = @"#nullable enable using System; class Program { static void F<T>(T t) { } static void Main() { var a1 = new[] { F<string?>, F<string> }; var a2 = new[] { F<(int X, object Y)>, F<(int, dynamic)> }; Report(a1[0]); Report(a2[0]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { F<string?>, F<string> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F<string?>, F<string> }").WithLocation(8, 18), // (9,18): error CS0826: No best type found for implicitly-typed array // var a2 = new[] { F<(int X, object Y)>, F<(int, dynamic)> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F<(int X, object Y)>, F<(int, dynamic)> }").WithLocation(9, 18)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Action`1[System.String] System.Action`1[System.ValueTuple`2[System.Int32,System.Object]]"); } [Fact] public void BestCommonType_09() { var source = @"using System; class Program { static void Main() { var a1 = new[] { (object o) => { }, (string s) => { } }; var a2 = new[] { () => (object)null, () => (string)null }; Report(a1[0]); Report(a2[0]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { (object o) => { }, (string s) => { } }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { (object o) => { }, (string s) => { } }").WithLocation(6, 18), // (7,18): error CS0826: No best type found for implicitly-typed array // var a2 = new[] { () => (object)null, () => (string)null }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { () => (object)null, () => (string)null }").WithLocation(7, 18)); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,26): error CS1661: Cannot convert lambda expression to type 'Action<string>' because the parameter types do not match the delegate parameter types // var a1 = new[] { (object o) => { }, (string s) => { } }; Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "(object o) => { }").WithArguments("lambda expression", "System.Action<string>").WithLocation(6, 26), // (6,34): error CS1678: Parameter 1 is declared as type 'object' but should be 'string' // var a1 = new[] { (object o) => { }, (string s) => { } }; Diagnostic(ErrorCode.ERR_BadParamType, "o").WithArguments("1", "", "object", "", "string").WithLocation(6, 34)); } [Fact] public void BestCommonType_10() { var source = @"using System; class Program { static void F1<T>(T t, ref object o) { } static void F2<T, U>(ref T t, U u) { } static void Main() { var a1 = new[] { F1<string>, F1<string> }; var a2 = new[] { F2<object, string>, F2<object, string> }; Report(a1[0]); Report(a2[0]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { F1<string>, F1<string> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F1<string>, F1<string> }").WithLocation(8, 18), // (9,18): error CS0826: No best type found for implicitly-typed array // var a2 = new[] { F2<object, string>, F2<object, string> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F2<object, string>, F2<object, string> }").WithLocation(9, 18)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"<>A{00000004}`2[System.String,System.Object] <>A{00000001}`2[System.Object,System.String]"); } [Fact] [WorkItem(55909, "https://github.com/dotnet/roslyn/issues/55909")] public void BestCommonType_11() { var source = @"using System; class Program { static void F1<T>(T t, ref object o) { } static void F2<T, U>(ref T t, U u) { } static void Main() { var a1 = new[] { F1<object>, F1<string> }; var a2 = new[] { F2<object, string>, F2<object, object> }; Report(a1[0]); Report(a2[0]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var expectedDiagnostics = new[] { // (8,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { F1<object>, F1<string> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F1<object>, F1<string> }").WithLocation(8, 18), // (9,18): error CS0826: No best type found for implicitly-typed array // var a2 = new[] { F2<object, string>, F2<object, object> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F2<object, string>, F2<object, object> }").WithLocation(9, 18) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); // https://github.com/dotnet/roslyn/issues/55909: ConversionsBase.HasImplicitSignatureConversion() // relies on the variance of FunctionTypeSymbol.GetInternalDelegateType() which fails for synthesized // delegate types where the type parameters are invariant. comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void BestCommonType_12() { var source = @"class Program { static void F<T>(ref T t) { } static void Main() { var a1 = new[] { F<object>, F<string> }; var a2 = new[] { (object x, ref object y) => { }, (string x, ref object y) => { } }; var a3 = new[] { (object x, ref object y) => { }, (object x, ref string y) => { } }; } }"; var expectedDiagnostics = new[] { // (6,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { F<object>, F<string> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F<object>, F<string> }").WithLocation(6, 18), // (7,18): error CS0826: No best type found for implicitly-typed array // var a2 = new[] { (object x, ref object y) => { }, (string x, ref object y) => { } }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { (object x, ref object y) => { }, (string x, ref object y) => { } }").WithLocation(7, 18), // (8,18): error CS0826: No best type found for implicitly-typed array // var a3 = new[] { (object x, ref object y) => { }, (object x, ref string y) => { } }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { (object x, ref object y) => { }, (object x, ref string y) => { } }").WithLocation(8, 18) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void BestCommonType_13() { var source = @"using System; class Program { static void F<T>(ref T t) { } static void Main() { var a1 = new[] { F<object>, null }; var a2 = new[] { default, F<string> }; var a3 = new[] { null, default, (object x, ref string y) => { } }; Report(a1[0]); Report(a2[1]); Report(a3[2]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { F<object>, null }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F<object>, null }").WithLocation(7, 18), // (8,18): error CS0826: No best type found for implicitly-typed array // var a2 = new[] { default, F<string> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { default, F<string> }").WithLocation(8, 18), // (9,18): error CS0826: No best type found for implicitly-typed array // var a3 = new[] { null, default, (object x, ref string y) => { } }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { null, default, (object x, ref string y) => { } }").WithLocation(9, 18)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"<>A{00000001}`1[System.Object] <>A{00000001}`1[System.String] <>A{00000004}`2[System.Object,System.String] "); } /// <summary> /// Best common type inference with delegate signatures that cannot be inferred. /// </summary> [Fact] public void BestCommonType_NoInferredSignature() { var source = @"class Program { static void F1() { } static int F1(int i) => i; static void F2() { } static void Main() { var a1 = new[] { F1 }; var a2 = new[] { F1, F2 }; var a3 = new[] { F2, F1 }; var a4 = new[] { x => x }; var a5 = new[] { x => x, (int y) => y }; var a6 = new[] { (int y) => y, static x => x }; var a7 = new[] { x => x, F1 }; var a8 = new[] { F1, (int y) => y }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { F1 }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F1 }").WithLocation(8, 18), // (9,18): error CS0826: No best type found for implicitly-typed array // var a2 = new[] { F1, F2 }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F1, F2 }").WithLocation(9, 18), // (10,18): error CS0826: No best type found for implicitly-typed array // var a3 = new[] { F2, F1 }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F2, F1 }").WithLocation(10, 18), // (11,18): error CS0826: No best type found for implicitly-typed array // var a4 = new[] { x => x }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { x => x }").WithLocation(11, 18), // (12,18): error CS0826: No best type found for implicitly-typed array // var a5 = new[] { x => x, (int y) => y }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { x => x, (int y) => y }").WithLocation(12, 18), // (13,18): error CS0826: No best type found for implicitly-typed array // var a6 = new[] { (int y) => y, static x => x }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { (int y) => y, static x => x }").WithLocation(13, 18), // (14,18): error CS0826: No best type found for implicitly-typed array // var a7 = new[] { x => x, F1 }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { x => x, F1 }").WithLocation(14, 18), // (15,18): error CS0826: No best type found for implicitly-typed array // var a8 = new[] { F1, (int y) => y }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F1, (int y) => y }").WithLocation(15, 18)); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { F1 }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F1 }").WithLocation(8, 18), // (11,18): error CS0826: No best type found for implicitly-typed array // var a4 = new[] { x => x }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { x => x }").WithLocation(11, 18), // (14,18): error CS0826: No best type found for implicitly-typed array // var a7 = new[] { x => x, F1 }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { x => x, F1 }").WithLocation(14, 18)); } [Fact] public void ArrayInitializer_01() { var source = @"using System; using System.Linq.Expressions; class Program { static void Main() { var a1 = new Func<int>[] { () => 1 }; var a2 = new Expression<Func<int>>[] { () => 2 }; Report(a1[0]); Report(a2[0]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; string expectedOutput = $@"System.Func`1[System.Int32] {s_expressionOfTDelegate0ArgTypeName}[System.Func`1[System.Int32]]"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); } [Fact] public void ArrayInitializer_02() { var source = @"using System; using System.Linq.Expressions; class Program { static void Main() { var a1 = new Delegate[] { () => 1 }; var a2 = new Expression[] { () => 2 }; Report(a1[0]); Report(a2[0]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,35): error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type // var a1 = new Delegate[] { () => 1 }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Delegate").WithLocation(7, 35), // (8,37): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // var a2 = new Expression[] { () => 2 }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 2").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(8, 37)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: $@"System.Func`1[System.Int32] {s_expressionOfTDelegate0ArgTypeName}[System.Func`1[System.Int32]]"); } [Fact] public void ArrayInitializer_03() { var source = @"using System; class Program { static void Main() { var a1 = new[] { () => 1 }; Report(a1[0]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { () => 1 }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { () => 1 }").WithLocation(6, 18)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Func`1[System.Int32]"); } [Fact] public void ConditionalOperator_01() { var source = @"class Program { static void F<T>(T t) { } static void Main() { var c1 = F<object> ?? F<string>; var c2 = ((object o) => { }) ?? ((string s) => { }); var c3 = F<string> ?? ((object o) => { }); } }"; var expectedDiagnostics = new[] { // (6,18): error CS0019: Operator '??' cannot be applied to operands of type 'method group' and 'method group' // var c1 = F<object> ?? F<string>; Diagnostic(ErrorCode.ERR_BadBinaryOps, "F<object> ?? F<string>").WithArguments("??", "method group", "method group").WithLocation(6, 18), // (7,18): error CS0019: Operator '??' cannot be applied to operands of type 'lambda expression' and 'lambda expression' // var c2 = ((object o) => { }) ?? ((string s) => { }); Diagnostic(ErrorCode.ERR_BadBinaryOps, "((object o) => { }) ?? ((string s) => { })").WithArguments("??", "lambda expression", "lambda expression").WithLocation(7, 18), // (8,18): error CS0019: Operator '??' cannot be applied to operands of type 'method group' and 'lambda expression' // var c3 = F<string> ?? ((object o) => { }); Diagnostic(ErrorCode.ERR_BadBinaryOps, "F<string> ?? ((object o) => { })").WithArguments("??", "method group", "lambda expression").WithLocation(8, 18) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void LambdaReturn_01() { var source = @"using System; class Program { static void Main() { var a1 = () => () => 1; var a2 = () => Main; Report(a1()); Report(a2()); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Func`1[System.Int32] System.Action"); } [Fact] public void InferredType_MethodGroup() { var source = @"class Program { static void Main() { System.Delegate d = Main; System.Console.Write(d.GetDelegateTypeName()); } }"; var comp = CreateCompilation(new[] { source, s_utils }, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "System.Action"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value; var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); } [Fact] public void InferredType_LambdaExpression() { var source = @"class Program { static void Main() { System.Delegate d = () => { }; System.Console.Write(d.GetDelegateTypeName()); } }"; var comp = CreateCompilation(new[] { source, s_utils }, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "System.Action"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<AnonymousFunctionExpressionSyntax>().Single(); var typeInfo = model.GetTypeInfo(expr); Assert.Equal("System.Action", typeInfo.Type.ToTestDisplayString()); Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); var symbolInfo = model.GetSymbolInfo(expr); var method = (IMethodSymbol)symbolInfo.Symbol!; Assert.Equal(MethodKind.LambdaMethod, method.MethodKind); Assert.True(HaveMatchingSignatures(((INamedTypeSymbol)typeInfo.Type!).DelegateInvokeMethod!, method)); } [WorkItem(55320, "https://github.com/dotnet/roslyn/issues/55320")] [Fact] public void InferredReturnType_01() { var source = @"using System; class Program { static void Main() { Report(() => { return; }); Report((bool b) => { if (b) return; }); Report((bool b) => { if (b) return; else return; }); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Action System.Action`1[System.Boolean] System.Action`1[System.Boolean] "); } [Fact] public void InferredReturnType_02() { var source = @"using System; class Program { static void Main() { Report(async () => { return; }); Report(async (bool b) => { if (b) return; }); Report(async (bool b) => { if (b) return; else return; }); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Func`1[System.Threading.Tasks.Task] System.Func`2[System.Boolean,System.Threading.Tasks.Task] System.Func`2[System.Boolean,System.Threading.Tasks.Task] "); } [WorkItem(55320, "https://github.com/dotnet/roslyn/issues/55320")] [Fact] public void InferredReturnType_03() { var source = @"using System; class Program { static void Main() { Report((bool b) => { if (b) return null; }); Report((bool b) => { if (b) return; else return null; }); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics( // (6,16): error CS8917: The delegate type could not be inferred. // Report((bool b) => { if (b) return null; }); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(bool b) => { if (b) return null; }").WithLocation(6, 16), // (7,16): error CS8917: The delegate type could not be inferred. // Report((bool b) => { if (b) return; else return null; }); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(bool b) => { if (b) return; else return null; }").WithLocation(7, 16), // (7,50): error CS8030: Anonymous function converted to a void returning delegate cannot return a value // Report((bool b) => { if (b) return; else return null; }); Diagnostic(ErrorCode.ERR_RetNoObjectRequiredLambda, "return").WithLocation(7, 50)); } [WorkItem(55320, "https://github.com/dotnet/roslyn/issues/55320")] [Fact] public void InferredReturnType_04() { var source = @"using System; class Program { static void Main() { Report((bool b) => { if (b) return default; }); Report((bool b) => { if (b) return; else return default; }); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics( // (6,16): error CS8917: The delegate type could not be inferred. // Report((bool b) => { if (b) return default; }); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(bool b) => { if (b) return default; }").WithLocation(6, 16), // (7,16): error CS8917: The delegate type could not be inferred. // Report((bool b) => { if (b) return; else return default; }); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(bool b) => { if (b) return; else return default; }").WithLocation(7, 16), // (7,50): error CS8030: Anonymous function converted to a void returning delegate cannot return a value // Report((bool b) => { if (b) return; else return default; }); Diagnostic(ErrorCode.ERR_RetNoObjectRequiredLambda, "return").WithLocation(7, 50)); } [Fact] public void ExplicitReturnType_01() { var source = @"using System; class Program { static void Main() { Report(object () => { return; }); Report(object (bool b) => { if (b) return null; }); Report(object (bool b) => { if (b) return; else return default; }); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics( // (6,31): error CS0126: An object of a type convertible to 'object' is required // Report(object () => { return; }); Diagnostic(ErrorCode.ERR_RetObjectRequired, "return").WithArguments("object").WithLocation(6, 31), // (7,32): error CS1643: Not all code paths return a value in lambda expression of type 'Func<bool, object>' // Report(object (bool b) => { if (b) return null; }); Diagnostic(ErrorCode.ERR_AnonymousReturnExpected, "=>").WithArguments("lambda expression", "System.Func<bool, object>").WithLocation(7, 32), // (8,44): error CS0126: An object of a type convertible to 'object' is required // Report(object (bool b) => { if (b) return; else return default; }); Diagnostic(ErrorCode.ERR_RetObjectRequired, "return").WithArguments("object").WithLocation(8, 44)); } [Fact] public void TypeInference_Constraints_01() { var source = @"using System; using System.Linq.Expressions; class Program { static T F1<T>(T t) where T : Delegate => t; static T F2<T>(T t) where T : Expression => t; static void Main() { Report(F1((int i) => { })); Report(F2(() => 1)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,16): error CS0411: The type arguments for method 'Program.F1<T>(T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F1((int i) => { })); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F1").WithArguments("Program.F1<T>(T)").WithLocation(9, 16), // (10,16): error CS0411: The type arguments for method 'Program.F2<T>(T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F2(() => 1)); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F2").WithArguments("Program.F2<T>(T)").WithLocation(10, 16)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: $@"System.Action`1[System.Int32] {s_expressionOfTDelegate0ArgTypeName}[System.Func`1[System.Int32]] "); } [Fact] public void TypeInference_Constraints_02() { var source = @"using System; using System.Linq.Expressions; class A<T> { public static U F<U>(U u) where U : T => u; } class B { static void Main() { Report(A<object>.F(() => 1)); Report(A<ICloneable>.F(() => 1)); Report(A<Delegate>.F(() => 1)); Report(A<MulticastDelegate>.F(() => 1)); Report(A<Func<int>>.F(() => 1)); Report(A<Expression>.F(() => 1)); Report(A<LambdaExpression>.F(() => 1)); Report(A<Expression<Func<int>>>.F(() => 1)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: $@"System.Func`1[System.Int32] System.Func`1[System.Int32] System.Func`1[System.Int32] System.Func`1[System.Int32] System.Func`1[System.Int32] {s_expressionOfTDelegate0ArgTypeName}[System.Func`1[System.Int32]] {s_expressionOfTDelegate0ArgTypeName}[System.Func`1[System.Int32]] {s_expressionOfTDelegate0ArgTypeName}[System.Func`1[System.Int32]] "); } [Fact] public void TypeInference_Constraints_03() { var source = @"using System; using System.Linq.Expressions; class A<T, U> where U : T { public static V F<V>(V v) where V : U => v; } class B { static void Main() { Report(A<object, object>.F(() => 1)); Report(A<object, Delegate>.F(() => 1)); Report(A<object, Func<int>>.F(() => 1)); Report(A<Delegate, Func<int>>.F(() => 1)); Report(A<object, Expression>.F(() => 1)); Report(A<object, Expression<Func<int>>>.F(() => 1)); Report(A<Expression, LambdaExpression>.F(() => 1)); Report(A<Expression, Expression<Func<int>>>.F(() => 1)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: $@"System.Func`1[System.Int32] System.Func`1[System.Int32] System.Func`1[System.Int32] System.Func`1[System.Int32] {s_expressionOfTDelegate0ArgTypeName}[System.Func`1[System.Int32]] {s_expressionOfTDelegate0ArgTypeName}[System.Func`1[System.Int32]] {s_expressionOfTDelegate0ArgTypeName}[System.Func`1[System.Int32]] {s_expressionOfTDelegate0ArgTypeName}[System.Func`1[System.Int32]] "); } [Fact] public void TypeInference_MatchingSignatures() { var source = @"using System; class Program { static T F<T>(T x, T y) => x; static int F1(string s) => s.Length; static void F2(string s) { } static void Main() { Report(F(F1, (string s) => int.Parse(s))); Report(F((string s) => { }, F2)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,16): error CS0411: The type arguments for method 'Program.F<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F(F1, (string s) => int.Parse(s))); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("Program.F<T>(T, T)").WithLocation(9, 16), // (10,16): error CS0411: The type arguments for method 'Program.F<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F((string s) => { }, F2)); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("Program.F<T>(T, T)").WithLocation(10, 16)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Func`2[System.String,System.Int32] System.Action`1[System.String] "); } [Fact] public void TypeInference_DistinctSignatures() { var source = @"using System; class Program { static T F<T>(T x, T y) => x; static int F1(object o) => o.GetHashCode(); static void F2(object o) { } static void Main() { Report(F(F1, (string s) => int.Parse(s))); Report(F((string s) => { }, F2)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,16): error CS0411: The type arguments for method 'Program.F<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F(F1, (string s) => int.Parse(s))); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("Program.F<T>(T, T)").WithLocation(9, 16), // (10,16): error CS0411: The type arguments for method 'Program.F<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F((string s) => { }, F2)); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("Program.F<T>(T, T)").WithLocation(10, 16)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Func`2[System.String,System.Int32] System.Action`1[System.String] "); } [Fact] public void TypeInference_01() { var source = @"using System; class Program { static T M<T>(T x, T y) => x; static int F1(int i) => i; static void F1() { } static T F2<T>(T t) => t; static void Main() { var f1 = M(x => x, (int y) => y); var f2 = M(F1, F2<int>); var f3 = M(F2<object>, z => z); Report(f1); Report(f2); Report(f3); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (10,18): error CS0411: The type arguments for method 'Program.M<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var f1 = M(x => x, (int y) => y); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T>(T, T)").WithLocation(10, 18), // (11,18): error CS0411: The type arguments for method 'Program.M<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var f2 = M(F1, F2<int>); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T>(T, T)").WithLocation(11, 18), // (12,18): error CS0411: The type arguments for method 'Program.M<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var f3 = M(F2<object>, z => z); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T>(T, T)").WithLocation(12, 18)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Func`2[System.Int32,System.Int32] System.Func`2[System.Int32,System.Int32] System.Func`2[System.Object,System.Object] "); } [Fact] public void TypeInference_02() { var source = @"using System; class Program { static T M<T>(T x, T y) where T : class => x ?? y; static T F<T>() => default; static void Main() { var f1 = M(F<object>, null); var f2 = M(default, F<string>); var f3 = M((object x, ref string y) => { }, default); var f4 = M(null, (ref object x, string y) => { }); Report(f1); Report(f2); Report(f3); Report(f4); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,18): error CS0411: The type arguments for method 'Program.M<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var f1 = M(F<object>, null); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T>(T, T)").WithLocation(8, 18), // (9,18): error CS0411: The type arguments for method 'Program.M<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var f2 = M(default, F<string>); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T>(T, T)").WithLocation(9, 18), // (10,18): error CS0411: The type arguments for method 'Program.M<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var f3 = M((object x, ref string y) => { }, default); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T>(T, T)").WithLocation(10, 18), // (11,18): error CS0411: The type arguments for method 'Program.M<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var f4 = M(null, (ref object x, string y) => { }); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T>(T, T)").WithLocation(11, 18)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Func`1[System.Object] System.Func`1[System.String] <>A{00000004}`2[System.Object,System.String] <>A{00000001}`2[System.Object,System.String] "); } [Fact] public void TypeInference_LowerBoundsMatchingSignature() { var source = @"using System; delegate void D1<T>(T t); delegate T D2<T>(); class Program { static T F<T>(T x, T y) => y; static void Main() { D1<string> d1 = (string s) => { }; D2<int> d2 = () => 1; Report(F(d1, (string s) => { })); Report(F(() => 2, d2)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var expectedOutput = @"D1`1[System.String] D2`1[System.Int32] "; CompileAndVerify(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); } [Fact] public void TypeInference_LowerBoundsDistinctSignature_01() { var source = @"using System; delegate void D1<T>(T t); delegate T D2<T>(); class Program { static T F<T>(T x, T y) => y; static void Main() { D1<string> d1 = (string s) => { }; D2<int> d2 = () => 1; Report(F(d1, (object o) => { })); Report(F(() => 1.0, d2)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var expectedDiagnostics = new[] { // (11,22): error CS1661: Cannot convert lambda expression to type 'D1<string>' because the parameter types do not match the delegate parameter types // Report(F(d1, (object o) => { })); Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "(object o) => { }").WithArguments("lambda expression", "D1<string>").WithLocation(11, 22), // (11,30): error CS1678: Parameter 1 is declared as type 'object' but should be 'string' // Report(F(d1, (object o) => { })); Diagnostic(ErrorCode.ERR_BadParamType, "o").WithArguments("1", "", "object", "", "string").WithLocation(11, 30), // (12,24): error CS0266: Cannot implicitly convert type 'double' to 'int'. An explicit conversion exists (are you missing a cast?) // Report(F(() => 1.0, d2)); Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "1.0").WithArguments("double", "int").WithLocation(12, 24), // (12,24): error CS1662: Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type // Report(F(() => 1.0, d2)); Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, "1.0").WithArguments("lambda expression").WithLocation(12, 24) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void TypeInference_LowerBoundsDistinctSignature_02() { var source = @"using System; class Program { static T F<T>(T x, T y) => y; static void Main() { Report(F((string s) => { }, (object o) => { })); Report(F(() => string.Empty, () => new object())); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,16): error CS0411: The type arguments for method 'Program.F<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F((string s) => { }, (object o) => { })); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("Program.F<T>(T, T)").WithLocation(7, 16), // (8,16): error CS0411: The type arguments for method 'Program.F<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F(() => string.Empty, () => new object())); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("Program.F<T>(T, T)").WithLocation(8, 16)); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,37): error CS1661: Cannot convert lambda expression to type 'Action<string>' because the parameter types do not match the delegate parameter types // Report(F((string s) => { }, (object o) => { })); Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "(object o) => { }").WithArguments("lambda expression", "System.Action<string>").WithLocation(7, 37), // (7,45): error CS1678: Parameter 1 is declared as type 'object' but should be 'string' // Report(F((string s) => { }, (object o) => { })); Diagnostic(ErrorCode.ERR_BadParamType, "o").WithArguments("1", "", "object", "", "string").WithLocation(7, 45)); } [Fact] public void TypeInference_UpperAndLowerBoundsMatchingSignature() { var source = @"using System; delegate void D1<T>(T t); delegate T D2<T>(); class Program { static T F1<T>(Action<T> x, T y) => y; static T F2<T>(T x, Action<T> y) => x; static void Main() { Action<D1<string>> a1 = null; Action<D2<int>> a2 = null; Report(F1(a1, (string s) => { })); Report(F2(() => 2, a2)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var expectedOutput = @"D1`1[System.String] D2`1[System.Int32] "; CompileAndVerify(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); } [Fact] public void TypeInference_UpperAndLowerBoundsDistinctSignature_01() { var source = @"using System; delegate void D1<T>(T t); delegate T D2<T>(); class Program { static T F1<T>(Action<T> x, T y) => y; static T F2<T>(T x, Action<T> y) => x; static void Main() { Action<D1<string>> a1 = null; Action<D2<object>> a2 = null; Report(F1(a1, (object o) => { })); Report(F2(() => string.Empty, a2)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var expectedDiagnostics = new[] { // (12,23): error CS1661: Cannot convert lambda expression to type 'D1<string>' because the parameter types do not match the delegate parameter types // Report(F1(a1, (object o) => { })); Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "(object o) => { }").WithArguments("lambda expression", "D1<string>").WithLocation(12, 23), // (12,31): error CS1678: Parameter 1 is declared as type 'object' but should be 'string' // Report(F1(a1, (object o) => { })); Diagnostic(ErrorCode.ERR_BadParamType, "o").WithArguments("1", "", "object", "", "string").WithLocation(12, 31) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void TypeInference_UpperAndLowerBoundsDistinctSignature_02() { var source = @"using System; delegate void D1<T>(T t); delegate T D2<T>(); class Program { static T F1<T>(Action<T> x, T y) => y; static T F2<T>(T x, Action<T> y) => x; static void Main() { Report(F1((D1<string> d) => { }, (object o) => { })); Report(F2(() => string.Empty, (D2<object> d) => { })); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var expectedDiagnostics = new[] { // (10,42): error CS1661: Cannot convert lambda expression to type 'D1<string>' because the parameter types do not match the delegate parameter types // Report(F1((D1<string> d) => { }, (object o) => { })); Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "(object o) => { }").WithArguments("lambda expression", "D1<string>").WithLocation(10, 42), // (10,50): error CS1678: Parameter 1 is declared as type 'object' but should be 'string' // Report(F1((D1<string> d) => { }, (object o) => { })); Diagnostic(ErrorCode.ERR_BadParamType, "o").WithArguments("1", "", "object", "", "string").WithLocation(10, 50) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void TypeInference_ExactAndLowerBoundsMatchingSignature() { var source = @"using System; delegate void D1<T>(T t); delegate T D2<T>(); class Program { static T F1<T>(ref T x, T y) => y; static T F2<T>(T x, ref T y) => y; static void Main() { D1<string> d1 = (string s) => { }; D2<int> d2 = () => 1; Report(F1(ref d1, (string s) => { })); Report(F2(() => 2, ref d2)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var expectedOutput = @"D1`1[System.String] D2`1[System.Int32] "; CompileAndVerify(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); } [Fact] public void TypeInference_ExactAndLowerBoundsDistinctSignature_01() { var source = @"using System; delegate void D1<T>(T t); delegate T D2<T>(); class Program { static T F1<T>(ref T x, T y) => y; static T F2<T>(T x, ref T y) => y; static void Main() { D1<string> d1 = (string s) => { }; D2<object> d2 = () => new object(); Report(F1(ref d1, (object o) => { })); Report(F2(() => string.Empty, ref d2)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var expectedDiagnostics = new[] { // (12,27): error CS1661: Cannot convert lambda expression to type 'D1<string>' because the parameter types do not match the delegate parameter types // Report(F1(ref d1, (object o) => { })); Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "(object o) => { }").WithArguments("lambda expression", "D1<string>").WithLocation(12, 27), // (12,35): error CS1678: Parameter 1 is declared as type 'object' but should be 'string' // Report(F1(ref d1, (object o) => { })); Diagnostic(ErrorCode.ERR_BadParamType, "o").WithArguments("1", "", "object", "", "string").WithLocation(12, 35) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void TypeInference_ExactAndLowerBoundsDistinctSignature_02() { var source = @"using System; delegate void D1<T>(T t); delegate T D2<T>(); class Program { static T F1<T>(in T x, T y) => y; static T F2<T>(T x, in T y) => y; static void Main() { Report(F1((D1<string> d) => { }, (object o) => { })); Report(F2(() => string.Empty, (D2<object> d) => { })); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var expectedDiagnostics = new[] { // (10,16): error CS0411: The type arguments for method 'Program.F1<T>(in T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F1((D1<string> d) => { }, (object o) => { })); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F1").WithArguments("Program.F1<T>(in T, T)").WithLocation(10, 16), // (11,16): error CS0411: The type arguments for method 'Program.F2<T>(T, in T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F2(() => 1.0, (D2<int> d) => { })); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F2").WithArguments("Program.F2<T>(T, in T)").WithLocation(11, 16) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,42): error CS1661: Cannot convert lambda expression to type 'Action<D1<string>>' because the parameter types do not match the delegate parameter types // Report(F1((D1<string> d) => { }, (object o) => { })); Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "(object o) => { }").WithArguments("lambda expression", "System.Action<D1<string>>").WithLocation(10, 42), // (10,50): error CS1678: Parameter 1 is declared as type 'object' but should be 'D1<string>' // Report(F1((D1<string> d) => { }, (object o) => { })); Diagnostic(ErrorCode.ERR_BadParamType, "o").WithArguments("1", "", "object", "", "D1<string>").WithLocation(10, 50), // (11,16): error CS0411: The type arguments for method 'Program.F2<T>(T, in T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F2(() => 1.0, (D2<int> d) => { })); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F2").WithArguments("Program.F2<T>(T, in T)").WithLocation(11, 16)); } [Fact] public void TypeInference_Nested_01() { var source = @"delegate void D<T>(T t); class Program { static T F1<T>(T t) => t; static D<T> F2<T>(D<T> d) => d; static void Main() { F2(F1((string s) => { })); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,12): error CS0411: The type arguments for method 'Program.F1<T>(T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F2(F1((string s) => { })); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F1").WithArguments("Program.F1<T>(T)").WithLocation(8, 12)); // Reports error on F1() in C#9, and reports error on F2() in C#10. comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,9): error CS0411: The type arguments for method 'Program.F2<T>(D<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F2(F1((string s) => { })); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F2").WithArguments("Program.F2<T>(D<T>)").WithLocation(8, 9)); } [Fact] public void TypeInference_Nested_02() { var source = @"using System.Linq.Expressions; class Program { static T F1<T>(T x) => throw null; static Expression<T> F2<T>(Expression<T> e) => e; static void Main() { F2(F1((object x1) => 1)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,12): error CS0411: The type arguments for method 'Program.F1<T>(T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F2(F1((string s) => { })); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F1").WithArguments("Program.F1<T>(T)").WithLocation(8, 12)); // Reports error on F1() in C#9, and reports error on F2() in C#10. comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,9): error CS0411: The type arguments for method 'Program.F2<T>(Expression<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F2(F1((object x1) => 1)); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F2").WithArguments("Program.F2<T>(System.Linq.Expressions.Expression<T>)").WithLocation(8, 9)); } /// <summary> /// Method type inference with delegate signatures that cannot be inferred. /// </summary> [Fact] public void TypeInference_NoInferredSignature() { var source = @"class Program { static void F1() { } static void F1(int i) { } static void F2() { } static T M1<T>(T t) => t; static T M2<T>(T x, T y) => x; static void Main() { var a1 = M1(F1); var a2 = M2(F1, F2); var a3 = M2(F2, F1); var a4 = M1(x => x); var a5 = M2(x => x, (int y) => y); var a6 = M2((int y) => y, x => x); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (10,18): error CS0411: The type arguments for method 'Program.M1<T>(T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var a1 = M1(F1); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M1").WithArguments("Program.M1<T>(T)").WithLocation(10, 18), // (11,18): error CS0411: The type arguments for method 'Program.M2<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var a2 = M2(F1, F2); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M2").WithArguments("Program.M2<T>(T, T)").WithLocation(11, 18), // (12,18): error CS0411: The type arguments for method 'Program.M2<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var a3 = M2(F2, F1); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M2").WithArguments("Program.M2<T>(T, T)").WithLocation(12, 18), // (13,18): error CS0411: The type arguments for method 'Program.M1<T>(T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var a4 = M1(x => x); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M1").WithArguments("Program.M1<T>(T)").WithLocation(13, 18), // (14,18): error CS0411: The type arguments for method 'Program.M2<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var a5 = M2(x => x, (int y) => y); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M2").WithArguments("Program.M2<T>(T, T)").WithLocation(14, 18), // (15,18): error CS0411: The type arguments for method 'Program.M2<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var a6 = M2((int y) => y, x => x); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M2").WithArguments("Program.M2<T>(T, T)").WithLocation(15, 18)); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,18): error CS0411: The type arguments for method 'Program.M1<T>(T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var a1 = M1(F1); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M1").WithArguments("Program.M1<T>(T)").WithLocation(10, 18), // (13,18): error CS0411: The type arguments for method 'Program.M1<T>(T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var a4 = M1(x => x); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M1").WithArguments("Program.M1<T>(T)").WithLocation(13, 18)); } [Fact] public void TypeInference_ExplicitReturnType_01() { var source = @"using System; using System.Linq.Expressions; class Program { static void F1<T>(Func<T> f) { Console.WriteLine(f.GetType()); } static void F2<T>(Expression<Func<T>> e) { Console.WriteLine(e.GetType()); } static void Main() { F1(int () => throw new Exception()); F2(int () => default); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,12): error CS8773: Feature 'lambda return type' is not available in C# 9.0. Please use language version 10.0 or greater. // F1(int () => throw new Exception()); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "int").WithArguments("lambda return type", "10.0").WithLocation(9, 12), // (10,12): error CS8773: Feature 'lambda return type' is not available in C# 9.0. Please use language version 10.0 or greater. // F2(int () => default); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "int").WithArguments("lambda return type", "10.0").WithLocation(10, 12)); var expectedOutput = $@"System.Func`1[System.Int32] {s_expressionOfTDelegate0ArgTypeName}[System.Func`1[System.Int32]] "; CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [WorkItem(54257, "https://github.com/dotnet/roslyn/issues/54257")] [Fact] public void TypeInference_ExplicitReturnType_02() { var source = @"using System; using System.Linq.Expressions; class Program { static void F1<T>(Func<T, T> f) { Console.WriteLine(f.GetType()); } static void F2<T>(Expression<Func<T, T>> e) { Console.WriteLine(e.GetType()); } static void Main() { F1(int (i) => i); F2(string (s) => s); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,12): error CS8773: Feature 'lambda return type' is not available in C# 9.0. Please use language version 10.0 or greater. // F1(int (i) => i); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "int").WithArguments("lambda return type", "10.0").WithLocation(9, 12), // (10,12): error CS8773: Feature 'lambda return type' is not available in C# 9.0. Please use language version 10.0 or greater. // F2(string (s) => s); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "string").WithArguments("lambda return type", "10.0").WithLocation(10, 12)); var expectedOutput = $@"System.Func`2[System.Int32,System.Int32] {s_expressionOfTDelegate1ArgTypeName}[System.Func`2[System.String,System.String]] "; CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [WorkItem(54257, "https://github.com/dotnet/roslyn/issues/54257")] [Fact] public void TypeInference_ExplicitReturnType_03() { var source = @"using System; delegate ref T D1<T>(T t); delegate ref readonly T D2<T>(T t); class Program { static void F1<T>(D1<T> d) { Console.WriteLine(d.GetType()); } static void F2<T>(D2<T> d) { Console.WriteLine(d.GetType()); } static void Main() { F1((ref int (i) => ref i)); F2((ref readonly string (s) => ref s)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (10,13): error CS8773: Feature 'lambda return type' is not available in C# 9.0. Please use language version 10.0 or greater. // F1((ref int (i) => ref i)); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "ref int").WithArguments("lambda return type", "10.0").WithLocation(10, 13), // (10,32): error CS8166: Cannot return a parameter by reference 'i' because it is not a ref or out parameter // F1((ref int (i) => ref i)); Diagnostic(ErrorCode.ERR_RefReturnParameter, "i").WithArguments("i").WithLocation(10, 32), // (11,13): error CS8773: Feature 'lambda return type' is not available in C# 9.0. Please use language version 10.0 or greater. // F2((ref readonly string (s) => ref s)); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "ref readonly string").WithArguments("lambda return type", "10.0").WithLocation(11, 13), // (11,44): error CS8166: Cannot return a parameter by reference 's' because it is not a ref or out parameter // F2((ref readonly string (s) => ref s)); Diagnostic(ErrorCode.ERR_RefReturnParameter, "s").WithArguments("s").WithLocation(11, 44)); var expectedDiagnostics = new[] { // (10,32): error CS8166: Cannot return a parameter by reference 'i' because it is not a ref or out parameter // F1((ref int (i) => ref i)); Diagnostic(ErrorCode.ERR_RefReturnParameter, "i").WithArguments("i").WithLocation(10, 32), // (11,44): error CS8166: Cannot return a parameter by reference 's' because it is not a ref or out parameter // F2((ref readonly string (s) => ref s)); Diagnostic(ErrorCode.ERR_RefReturnParameter, "s").WithArguments("s").WithLocation(11, 44) }; comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [WorkItem(54257, "https://github.com/dotnet/roslyn/issues/54257")] [Fact] public void TypeInference_ExplicitReturnType_04() { var source = @"using System; using System.Linq.Expressions; class Program { static void F1<T>(Func<T, T> x, T y) { Console.WriteLine(x.GetType()); } static void F2<T>(Expression<Func<T, T>> x, T y) { Console.WriteLine(x.GetType()); } static void Main() { F1(object (o) => o, 1); F1(int (i) => i, 2); F2(object (o) => o, string.Empty); F2(string (s) => s, string.Empty); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,12): error CS8773: Feature 'lambda return type' is not available in C# 9.0. Please use language version 10.0 or greater. // F1(object (o) => o, 1); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "object").WithArguments("lambda return type", "10.0").WithLocation(9, 12), // (10,12): error CS8773: Feature 'lambda return type' is not available in C# 9.0. Please use language version 10.0 or greater. // F1(int (i) => i, 2); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "int").WithArguments("lambda return type", "10.0").WithLocation(10, 12), // (11,12): error CS8773: Feature 'lambda return type' is not available in C# 9.0. Please use language version 10.0 or greater. // F2(object (o) => o, string.Empty); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "object").WithArguments("lambda return type", "10.0").WithLocation(11, 12), // (12,12): error CS8773: Feature 'lambda return type' is not available in C# 9.0. Please use language version 10.0 or greater. // F2(string (s) => s, string.Empty); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "string").WithArguments("lambda return type", "10.0").WithLocation(12, 12)); var expectedOutput = $@"System.Func`2[System.Object,System.Object] System.Func`2[System.Int32,System.Int32] {s_expressionOfTDelegate1ArgTypeName}[System.Func`2[System.Object,System.Object]] {s_expressionOfTDelegate1ArgTypeName}[System.Func`2[System.String,System.String]] "; CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [WorkItem(54257, "https://github.com/dotnet/roslyn/issues/54257")] [Fact] public void TypeInference_ExplicitReturnType_05() { var source = @"using System; using System.Linq.Expressions; class Program { static void F1<T>(Func<T, T> x, T y) { Console.WriteLine(x.GetType()); } static void F2<T>(Expression<Func<T, T>> x, T y) { Console.WriteLine(x.GetType()); } static void Main() { F1(int (i) => i, (object)1); F2(string (s) => s, (object)2); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,9): error CS0411: The type arguments for method 'Program.F1<T>(Func<T, T>, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F1(int (i) => i, (object)1); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F1").WithArguments("Program.F1<T>(System.Func<T, T>, T)").WithLocation(9, 9), // (9,12): error CS8773: Feature 'lambda return type' is not available in C# 9.0. Please use language version 10.0 or greater. // F1(int (i) => i, (object)1); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "int").WithArguments("lambda return type", "10.0").WithLocation(9, 12), // (10,9): error CS0411: The type arguments for method 'Program.F2<T>(Expression<Func<T, T>>, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F2(string (s) => s, (object)2); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F2").WithArguments("Program.F2<T>(System.Linq.Expressions.Expression<System.Func<T, T>>, T)").WithLocation(10, 9), // (10,12): error CS8773: Feature 'lambda return type' is not available in C# 9.0. Please use language version 10.0 or greater. // F2(string (s) => s, (object)2); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "string").WithArguments("lambda return type", "10.0").WithLocation(10, 12)); var expectedDiagnostics = new[] { // (9,9): error CS0411: The type arguments for method 'Program.F1<T>(Func<T, T>, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F1(int (i) => i, (object)1); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F1").WithArguments("Program.F1<T>(System.Func<T, T>, T)").WithLocation(9, 9), // (10,9): error CS0411: The type arguments for method 'Program.F2<T>(Expression<Func<T, T>>, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F2(string (s) => s, (object)2); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F2").WithArguments("Program.F2<T>(System.Linq.Expressions.Expression<System.Func<T, T>>, T)").WithLocation(10, 9) }; comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [WorkItem(54257, "https://github.com/dotnet/roslyn/issues/54257")] [Fact] public void TypeInference_ExplicitReturnType_06() { var source = @"using System; using System.Linq.Expressions; interface I<T> { } class Program { static void F1<T>(Func<T, T> f) { } static void F2<T>(Func<T, I<T>> f) { } static void F3<T>(Func<I<T>, T> f) { } static void F4<T>(Func<I<T>, I<T>> f) { } static void F5<T>(Expression<Func<T, T>> e) { } static void F6<T>(Expression<Func<T, I<T>>> e) { } static void F7<T>(Expression<Func<I<T>, T>> e) { } static void F8<T>(Expression<Func<I<T>, I<T>>> e) { } static void Main() { F1(int (int i) => default); F2(I<int> (int i) => default); F3(int (I<int> i) => default); F4(I<int> (I<int> i) => default); F5(int (int i) => default); F6(I<int> (int i) => default); F7(int (I<int> i) => default); F8(I<int> (I<int> i) => default); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [WorkItem(54257, "https://github.com/dotnet/roslyn/issues/54257")] [Fact] public void TypeInference_ExplicitReturnType_07() { var source = @"using System; using System.Linq.Expressions; interface I<T> { } class Program { static void F1<T>(Func<T, T> f) { } static void F2<T>(Func<T, I<T>> f) { } static void F3<T>(Func<I<T>, T> f) { } static void F4<T>(Func<I<T>, I<T>> f) { } static void F5<T>(Expression<Func<T, T>> e) { } static void F6<T>(Expression<Func<T, I<T>>> e) { } static void F7<T>(Expression<Func<I<T>, T>> e) { } static void F8<T>(Expression<Func<I<T>, I<T>>> e) { } static void Main() { F1(int (object i) => default); F2(I<int> (object i) => default); F3(object (I<int> i) => default); F4(I<object> (I<int> i) => default); F5(object (int i) => default); F6(I<object> (int i) => default); F7(int (I<object> i) => default); F8(I<int> (I<object> i) => default); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (16,9): error CS0411: The type arguments for method 'Program.F1<T>(Func<T, T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F1(int (object i) => default); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F1").WithArguments("Program.F1<T>(System.Func<T, T>)").WithLocation(16, 9), // (17,9): error CS0411: The type arguments for method 'Program.F2<T>(Func<T, I<T>>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F2(I<int> (object i) => default); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F2").WithArguments("Program.F2<T>(System.Func<T, I<T>>)").WithLocation(17, 9), // (18,9): error CS0411: The type arguments for method 'Program.F3<T>(Func<I<T>, T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F3(object (I<int> i) => default); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F3").WithArguments("Program.F3<T>(System.Func<I<T>, T>)").WithLocation(18, 9), // (19,9): error CS0411: The type arguments for method 'Program.F4<T>(Func<I<T>, I<T>>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F4(I<object> (I<int> i) => default); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F4").WithArguments("Program.F4<T>(System.Func<I<T>, I<T>>)").WithLocation(19, 9), // (20,9): error CS0411: The type arguments for method 'Program.F5<T>(Expression<Func<T, T>>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F5(object (int i) => default); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F5").WithArguments("Program.F5<T>(System.Linq.Expressions.Expression<System.Func<T, T>>)").WithLocation(20, 9), // (21,9): error CS0411: The type arguments for method 'Program.F6<T>(Expression<Func<T, I<T>>>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F6(I<object> (int i) => default); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F6").WithArguments("Program.F6<T>(System.Linq.Expressions.Expression<System.Func<T, I<T>>>)").WithLocation(21, 9), // (22,9): error CS0411: The type arguments for method 'Program.F7<T>(Expression<Func<I<T>, T>>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F7(int (I<object> i) => default); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F7").WithArguments("Program.F7<T>(System.Linq.Expressions.Expression<System.Func<I<T>, T>>)").WithLocation(22, 9), // (23,9): error CS0411: The type arguments for method 'Program.F8<T>(Expression<Func<I<T>, I<T>>>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F8(I<int> (I<object> i) => default); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F8").WithArguments("Program.F8<T>(System.Linq.Expressions.Expression<System.Func<I<T>, I<T>>>)").WithLocation(23, 9)); } // Variance in inference from explicit return type is disallowed // (see https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md). [WorkItem(54257, "https://github.com/dotnet/roslyn/issues/54257")] [Fact] public void TypeInference_ExplicitReturnType_08() { var source = @"using System; using System.Linq.Expressions; class Program { static void F1<T>(Func<T, T> x, Func<T, T> y) { Console.WriteLine(x.GetType()); } static void F2<T>(Expression<Func<T, T>> x, Expression<Func<T, T>> y) { Console.WriteLine(x.GetType()); } static void Main() { F1(int (x) => x, int (y) => y); F1(object (x) => x, int (y) => y); F2(string (x) => x, string (y) => y); F2(string (x) => x, object (y) => y); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,12): error CS8773: Feature 'lambda return type' is not available in C# 9.0. Please use language version 10.0 or greater. // F1(int (x) => x, int (y) => y); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "int").WithArguments("lambda return type", "10.0").WithLocation(9, 12), // (9,26): error CS8773: Feature 'lambda return type' is not available in C# 9.0. Please use language version 10.0 or greater. // F1(int (x) => x, int (y) => y); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "int").WithArguments("lambda return type", "10.0").WithLocation(9, 26), // (10,9): error CS0411: The type arguments for method 'Program.F1<T>(Func<T, T>, Func<T, T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F1(object (x) => x, int (y) => y); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F1").WithArguments("Program.F1<T>(System.Func<T, T>, System.Func<T, T>)").WithLocation(10, 9), // (10,12): error CS8773: Feature 'lambda return type' is not available in C# 9.0. Please use language version 10.0 or greater. // F1(object (x) => x, int (y) => y); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "object").WithArguments("lambda return type", "10.0").WithLocation(10, 12), // (10,29): error CS8773: Feature 'lambda return type' is not available in C# 9.0. Please use language version 10.0 or greater. // F1(object (x) => x, int (y) => y); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "int").WithArguments("lambda return type", "10.0").WithLocation(10, 29), // (11,12): error CS8773: Feature 'lambda return type' is not available in C# 9.0. Please use language version 10.0 or greater. // F2(string (x) => x, string (y) => y); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "string").WithArguments("lambda return type", "10.0").WithLocation(11, 12), // (11,29): error CS8773: Feature 'lambda return type' is not available in C# 9.0. Please use language version 10.0 or greater. // F2(string (x) => x, string (y) => y); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "string").WithArguments("lambda return type", "10.0").WithLocation(11, 29), // (12,9): error CS0411: The type arguments for method 'Program.F2<T>(Expression<Func<T, T>>, Expression<Func<T, T>>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F2(string (x) => x, object (y) => y); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F2").WithArguments("Program.F2<T>(System.Linq.Expressions.Expression<System.Func<T, T>>, System.Linq.Expressions.Expression<System.Func<T, T>>)").WithLocation(12, 9), // (12,12): error CS8773: Feature 'lambda return type' is not available in C# 9.0. Please use language version 10.0 or greater. // F2(string (x) => x, object (y) => y); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "string").WithArguments("lambda return type", "10.0").WithLocation(12, 12), // (12,29): error CS8773: Feature 'lambda return type' is not available in C# 9.0. Please use language version 10.0 or greater. // F2(string (x) => x, object (y) => y); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "object").WithArguments("lambda return type", "10.0").WithLocation(12, 29)); var expectedDiagnostics = new[] { // (10,9): error CS0411: The type arguments for method 'Program.F1<T>(Func<T, T>, Func<T, T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F1(object (x) => x, int (y) => y); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F1").WithArguments("Program.F1<T>(System.Func<T, T>, System.Func<T, T>)").WithLocation(10, 9), // (12,9): error CS0411: The type arguments for method 'Program.F2<T>(Expression<Func<T, T>>, Expression<Func<T, T>>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F2(string (x) => x, object (y) => y); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F2").WithArguments("Program.F2<T>(System.Linq.Expressions.Expression<System.Func<T, T>>, System.Linq.Expressions.Expression<System.Func<T, T>>)").WithLocation(12, 9) }; comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [WorkItem(54257, "https://github.com/dotnet/roslyn/issues/54257")] [Fact] public void TypeInference_ExplicitReturnType_09() { var source = @"#nullable enable using System; using System.Linq.Expressions; class Program { static T F1<T>(Func<T, T> f) => default!; static T F2<T>(Expression<Func<T, T>> e) => default!; static void Main() { F1(object (x1) => x1).ToString(); F2(object (x2) => x2).ToString(); F1(object? (y1) => y1).ToString(); F2(object? (y2) => y2).ToString(); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (12,9): warning CS8602: Dereference of a possibly null reference. // F1(object? (y1) => y1).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(object? (y1) => y1)").WithLocation(12, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // F2(object? (y2) => y2).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(object? (y2) => y2)").WithLocation(13, 9)); } [WorkItem(54257, "https://github.com/dotnet/roslyn/issues/54257")] [Fact] public void TypeInference_ExplicitReturnType_10() { var source = @"#nullable enable using System; using System.Linq.Expressions; class Program { static T F1<T>(Func<T, T> f) => default!; static T F2<T>(Expression<Func<T, T>> e) => default!; static void Main() { F1( #nullable disable object (x1) => #nullable enable x1).ToString(); F2( #nullable disable object (x2) => #nullable enable x2).ToString(); F1( #nullable disable object #nullable enable (y1) => y1).ToString(); F2( #nullable disable object #nullable enable (y2) => y2).ToString(); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [WorkItem(54257, "https://github.com/dotnet/roslyn/issues/54257")] [Fact] public void TypeInference_ExplicitReturnType_11() { var source = @"#nullable enable using System; using System.Linq.Expressions; class Program { static T F1<T>(Func<T, T> f) => default!; static T F2<T>(Expression<Func<T, T>> e) => default!; static void Main() { var x1 = F1( #nullable enable object? #nullable disable (x1) => #nullable enable x1); var x2 = F2( #nullable enable object? #nullable disable (x2) => #nullable enable x2); var y1 = F1( #nullable enable object #nullable disable (y1) => #nullable enable y1); var y2 = F2( #nullable enable object #nullable disable (y2) => #nullable enable y2); x1.ToString(); x2.ToString(); y1.ToString(); y2.ToString(); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (38,9): warning CS8602: Dereference of a possibly null reference. // x1.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1").WithLocation(38, 9), // (39,9): warning CS8602: Dereference of a possibly null reference. // x2.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x2").WithLocation(39, 9)); } [WorkItem(54257, "https://github.com/dotnet/roslyn/issues/54257")] [Fact] public void TypeInference_ExplicitReturnType_12() { var source = @"#nullable enable using System; using System.Linq.Expressions; class Program { static T F1<T>(Func<T, T> f) => default!; static T F2<T>(Expression<Func<T, T>> e) => default!; static void Main() { var x1 = F1(object (object x1) => x1); var x2 = F1(object (object? x2) => x2); var x3 = F1(object? (object x3) => x3); var x4 = F1(object? (object? x4) => x4); var y1 = F2(object (object y1) => y1); var y2 = F2(object (object? y2) => y2); var y3 = F2(object? (object y3) => y3); var y4 = F2(object? (object? y4) => y4); x1.ToString(); x2.ToString(); x3.ToString(); x4.ToString(); y1.ToString(); y2.ToString(); y3.ToString(); y4.ToString(); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,21): warning CS8622: Nullability of reference types in type of parameter 'x2' of 'lambda expression' doesn't match the target delegate 'Func<object, object>' (possibly because of nullability attributes). // var x2 = F1(object (object? x2) => x2); Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "object (object? x2) => x2").WithArguments("x2", "lambda expression", "System.Func<object, object>").WithLocation(11, 21), // (11,44): warning CS8603: Possible null reference return. // var x2 = F1(object (object? x2) => x2); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "x2").WithLocation(11, 44), // (12,21): warning CS8621: Nullability of reference types in return type of 'lambda expression' doesn't match the target delegate 'Func<object, object>' (possibly because of nullability attributes). // var x3 = F1(object? (object x3) => x3); Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "object? (object x3) => x3").WithArguments("lambda expression", "System.Func<object, object>").WithLocation(12, 21), // (15,21): warning CS8622: Nullability of reference types in type of parameter 'y2' of 'lambda expression' doesn't match the target delegate 'Func<object, object>' (possibly because of nullability attributes). // var y2 = F2(object (object? y2) => y2); Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "object (object? y2) => y2").WithArguments("y2", "lambda expression", "System.Func<object, object>").WithLocation(15, 21), // (15,44): warning CS8603: Possible null reference return. // var y2 = F2(object (object? y2) => y2); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "y2").WithLocation(15, 44), // (16,21): warning CS8621: Nullability of reference types in return type of 'lambda expression' doesn't match the target delegate 'Func<object, object>' (possibly because of nullability attributes). // var y3 = F2(object? (object y3) => y3); Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "object? (object y3) => y3").WithArguments("lambda expression", "System.Func<object, object>").WithLocation(16, 21), // (21,9): warning CS8602: Dereference of a possibly null reference. // x4.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x4").WithLocation(21, 9), // (25,9): warning CS8602: Dereference of a possibly null reference. // y4.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y4").WithLocation(25, 9)); } [Fact] public void Variance_01() { var source = @"using System; class Program { static void Main() { Action<string> a1 = s => { }; Action<string> a2 = (string s) => { }; Action<string> a3 = (object o) => { }; Action<string> a4 = (Action<object>)((object o) => { }); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,29): error CS1661: Cannot convert lambda expression to type 'Action<string>' because the parameter types do not match the delegate parameter types // Action<string> a3 = (object o) => { }; Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "(object o) => { }").WithArguments("lambda expression", "System.Action<string>").WithLocation(8, 29), // (8,37): error CS1678: Parameter 1 is declared as type 'object' but should be 'string' // Action<string> a3 = (object o) => { }; Diagnostic(ErrorCode.ERR_BadParamType, "o").WithArguments("1", "", "object", "", "string").WithLocation(8, 37)); } [Fact] public void Variance_02() { var source = @"using System; class Program { static void Main() { Func<object> f1 = () => string.Empty; Func<object> f2 = string () => string.Empty; Func<object> f3 = (Func<string>)(() => string.Empty); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,27): error CS8934: Cannot convert lambda expression to type 'Func<object>' because the return type does not match the delegate return type // Func<object> f2 = string () => string.Empty; Diagnostic(ErrorCode.ERR_CantConvAnonMethReturnType, "string () => string.Empty").WithArguments("lambda expression", "System.Func<object>").WithLocation(7, 27)); } [Fact] public void ImplicitlyTypedVariables_01() { var source = @"using System; class Program { static void Main() { var d1 = Main; Report(d1); var d2 = () => { }; Report(d2); var d3 = delegate () { }; Report(d3); } static void Report(Delegate d) => Console.WriteLine(d.GetDelegateTypeName()); }"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (6,18): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // var d1 = Main; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "Main").WithArguments("inferred delegate type", "10.0").WithLocation(6, 18), // (8,18): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // var d2 = () => { }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "() => { }").WithArguments("inferred delegate type", "10.0").WithLocation(8, 18), // (10,18): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // var d3 = delegate () { }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "delegate () { }").WithArguments("inferred delegate type", "10.0").WithLocation(10, 18)); comp = CreateCompilation(new[] { source, s_utils }, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: @"System.Action System.Action System.Action"); verifier.VerifyIL("Program.Main", @"{ // Code size 100 (0x64) .maxstack 2 .locals init (System.Action V_0, //d1 System.Action V_1, //d2 System.Action V_2) //d3 IL_0000: nop IL_0001: ldnull IL_0002: ldftn ""void Program.Main()"" IL_0008: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_000d: stloc.0 IL_000e: ldloc.0 IL_000f: call ""void Program.Report(System.Delegate)"" IL_0014: nop IL_0015: ldsfld ""System.Action Program.<>c.<>9__0_0"" IL_001a: dup IL_001b: brtrue.s IL_0034 IL_001d: pop IL_001e: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0023: ldftn ""void Program.<>c.<Main>b__0_0()"" IL_0029: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_002e: dup IL_002f: stsfld ""System.Action Program.<>c.<>9__0_0"" IL_0034: stloc.1 IL_0035: ldloc.1 IL_0036: call ""void Program.Report(System.Delegate)"" IL_003b: nop IL_003c: ldsfld ""System.Action Program.<>c.<>9__0_1"" IL_0041: dup IL_0042: brtrue.s IL_005b IL_0044: pop IL_0045: ldsfld ""Program.<>c Program.<>c.<>9"" IL_004a: ldftn ""void Program.<>c.<Main>b__0_1()"" IL_0050: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_0055: dup IL_0056: stsfld ""System.Action Program.<>c.<>9__0_1"" IL_005b: stloc.2 IL_005c: ldloc.2 IL_005d: call ""void Program.Report(System.Delegate)"" IL_0062: nop IL_0063: ret }"); } [Fact] public void ImplicitlyTypedVariables_02() { var source = @"var d1 = object.ReferenceEquals; var d2 = () => { }; var d3 = delegate () { }; "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9.WithKind(SourceCodeKind.Script)); comp.VerifyDiagnostics( // (1,10): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // var d1 = object.ReferenceEquals; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "object.ReferenceEquals").WithArguments("inferred delegate type", "10.0").WithLocation(1, 10), // (2,10): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // var d2 = () => { }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "() => { }").WithArguments("inferred delegate type", "10.0").WithLocation(2, 10), // (3,10): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // var d3 = delegate () { }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "delegate () { }").WithArguments("inferred delegate type", "10.0").WithLocation(3, 10)); comp = CreateCompilation(source, parseOptions: TestOptions.Regular10.WithKind(SourceCodeKind.Script)); comp.VerifyDiagnostics(); } [Fact] public void ImplicitlyTypedVariables_03() { var source = @"class Program { static void Main() { ref var d1 = Main; ref var d2 = () => { }; ref var d3 = delegate () { }; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,17): error CS8172: Cannot initialize a by-reference variable with a value // ref var d1 = Main; Diagnostic(ErrorCode.ERR_InitializeByReferenceVariableWithValue, "d1 = Main").WithLocation(5, 17), // (5,22): error CS1657: Cannot use 'Main' as a ref or out value because it is a 'method group' // ref var d1 = Main; Diagnostic(ErrorCode.ERR_RefReadonlyLocalCause, "Main").WithArguments("Main", "method group").WithLocation(5, 22), // (6,17): error CS8172: Cannot initialize a by-reference variable with a value // ref var d2 = () => { }; Diagnostic(ErrorCode.ERR_InitializeByReferenceVariableWithValue, "d2 = () => { }").WithLocation(6, 17), // (6,22): error CS1510: A ref or out value must be an assignable variable // ref var d2 = () => { }; Diagnostic(ErrorCode.ERR_RefLvalueExpected, "() => { }").WithLocation(6, 22), // (7,17): error CS8172: Cannot initialize a by-reference variable with a value // ref var d3 = delegate () { }; Diagnostic(ErrorCode.ERR_InitializeByReferenceVariableWithValue, "d3 = delegate () { }").WithLocation(7, 17), // (7,22): error CS1510: A ref or out value must be an assignable variable // ref var d3 = delegate () { }; Diagnostic(ErrorCode.ERR_RefLvalueExpected, "delegate () { }").WithLocation(7, 22)); } [Fact] public void ImplicitlyTypedVariables_04() { var source = @"class Program { static void Main() { using var d1 = Main; using var d2 = () => { }; using var d3 = delegate () { }; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,9): error CS1674: 'Action': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using var d1 = Main; Diagnostic(ErrorCode.ERR_NoConvToIDisp, "using var d1 = Main;").WithArguments("System.Action").WithLocation(5, 9), // (6,9): error CS1674: 'Action': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using var d2 = () => { }; Diagnostic(ErrorCode.ERR_NoConvToIDisp, "using var d2 = () => { };").WithArguments("System.Action").WithLocation(6, 9), // (7,9): error CS1674: 'Action': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using var d3 = delegate () { }; Diagnostic(ErrorCode.ERR_NoConvToIDisp, "using var d3 = delegate () { };").WithArguments("System.Action").WithLocation(7, 9)); } [Fact] public void ImplicitlyTypedVariables_05() { var source = @"class Program { static void Main() { foreach (var d1 in Main) { } foreach (var d2 in () => { }) { } foreach (var d3 in delegate () { }) { } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,28): error CS0446: Foreach cannot operate on a 'method group'. Did you intend to invoke the 'method group'? // foreach (var d1 in Main) { } Diagnostic(ErrorCode.ERR_AnonMethGrpInForEach, "Main").WithArguments("method group").WithLocation(5, 28), // (6,28): error CS0446: Foreach cannot operate on a 'lambda expression'. Did you intend to invoke the 'lambda expression'? // foreach (var d2 in () => { }) { } Diagnostic(ErrorCode.ERR_AnonMethGrpInForEach, "() => { }").WithArguments("lambda expression").WithLocation(6, 28), // (7,28): error CS0446: Foreach cannot operate on a 'anonymous method'. Did you intend to invoke the 'anonymous method'? // foreach (var d3 in delegate () { }) { } Diagnostic(ErrorCode.ERR_AnonMethGrpInForEach, "delegate () { }").WithArguments("anonymous method").WithLocation(7, 28)); } [Fact] public void ImplicitlyTypedVariables_06() { var source = @"using System; class Program { static void Main() { Func<int> f; var d1 = Main; f = d1; var d2 = object (int x) => x; f = d2; var d3 = delegate () { return string.Empty; }; f = d3; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,13): error CS0029: Cannot implicitly convert type 'System.Action' to 'System.Func<int>' // f = d1; Diagnostic(ErrorCode.ERR_NoImplicitConv, "d1").WithArguments("System.Action", "System.Func<int>").WithLocation(8, 13), // (10,13): error CS0029: Cannot implicitly convert type 'System.Func<int, object>' to 'System.Func<int>' // f = d2; Diagnostic(ErrorCode.ERR_NoImplicitConv, "d2").WithArguments("System.Func<int, object>", "System.Func<int>").WithLocation(10, 13), // (12,13): error CS0029: Cannot implicitly convert type 'System.Func<string>' to 'System.Func<int>' // f = d3; Diagnostic(ErrorCode.ERR_NoImplicitConv, "d3").WithArguments("System.Func<string>", "System.Func<int>").WithLocation(12, 13)); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var variables = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(v => v.Initializer != null); var expectedInfo = new (string?, string?, string?)[] { ("System.Action d1", null, "System.Action"), ("System.Func<System.Int32, System.Object> d2", null, "System.Func<System.Int32, System.Object>"), ("System.Func<System.String> d3", null, "System.Func<System.String>"), }; AssertEx.Equal(expectedInfo, variables.Select(v => getVariableInfo(model, v))); static (string?, string?, string?) getVariableInfo(SemanticModel model, VariableDeclaratorSyntax variable) { var symbol = model.GetDeclaredSymbol(variable); var typeInfo = model.GetTypeInfo(variable.Initializer!.Value); return (symbol?.ToTestDisplayString(), typeInfo.Type?.ToTestDisplayString(), typeInfo.ConvertedType?.ToTestDisplayString()); } } [Fact] public void ImplicitlyTypedVariables_07() { var source = @"class Program { static void Main() { var t = (Main, () => { }); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,13): error CS0815: Cannot assign (method group, lambda expression) to an implicitly-typed variable // var t = (Main, () => { }); Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, "t = (Main, () => { })").WithArguments("(method group, lambda expression)").WithLocation(5, 13)); } [Fact] public void ImplicitlyTypedVariables_08() { var source = @"class Program { static void Main() { (var x1, var y1) = Main; var (x2, y2) = () => { }; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,14): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x1'. // (var x1, var y1) = Main; Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x1").WithArguments("x1").WithLocation(5, 14), // (5,22): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y1'. // (var x1, var y1) = Main; Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y1").WithArguments("y1").WithLocation(5, 22), // (5,28): error CS8131: Deconstruct assignment requires an expression with a type on the right-hand-side. // (var x1, var y1) = Main; Diagnostic(ErrorCode.ERR_DeconstructRequiresExpression, "Main").WithLocation(5, 28), // (6,14): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x2'. // var (x2, y2) = () => { }; Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x2").WithArguments("x2").WithLocation(6, 14), // (6,18): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y2'. // var (x2, y2) = () => { }; Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y2").WithArguments("y2").WithLocation(6, 18), // (6,24): error CS8131: Deconstruct assignment requires an expression with a type on the right-hand-side. // var (x2, y2) = () => { }; Diagnostic(ErrorCode.ERR_DeconstructRequiresExpression, "() => { }").WithLocation(6, 24)); } [Fact] public void ImplicitlyTypedVariables_09() { var source = @"class Program { static void Main() { var (x, y) = (Main, () => { }); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,14): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x'. // var (x, y) = (Main, () => { }); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x").WithArguments("x").WithLocation(5, 14), // (5,17): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y'. // var (x, y) = (Main, () => { }); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y").WithArguments("y").WithLocation(5, 17)); } [Fact] public void ImplicitlyTypedVariables_10() { var source = @"using System; class Program { static void Main() { (var x1, Action y1) = (Main, null); (Action x2, var y2) = (null, () => { }); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,14): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x1'. // (var x1, Action y1) = (Main, null); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x1").WithArguments("x1").WithLocation(6, 14), // (7,25): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y2'. // (Action x2, var y2) = (null, () => { }); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y2").WithArguments("y2").WithLocation(7, 25)); } [Fact] public void ImplicitlyTypedVariables_11() { var source = @"class Program { static void F(object o) { } static void F(int i) { } static void Main() { var d1 = F; var d2 = x => x; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,18): error CS8917: The delegate type could not be inferred. // var d1 = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F").WithLocation(7, 18), // (8,18): error CS8917: The delegate type could not be inferred. // var d2 = x => x; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(8, 18)); } [Fact] public void ImplicitlyTypedVariables_12() { var source = @"class Program { static void F(ref int i) { } static void Main() { var d1 = F; var d2 = (ref int x) => x; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void ImplicitlyTypedVariables_13() { var source = @"using System; class Program { static int F() => 0; static void Main() { var d1 = (F); Report(d1); var d2 = (object (int x) => x); Report(d2); var d3 = (delegate () { return string.Empty; }); Report(d3); } static void Report(Delegate d) => Console.WriteLine(d.GetDelegateTypeName()); }"; CompileAndVerify(new[] { source, s_utils }, options: TestOptions.DebugExe, expectedOutput: @"System.Func<System.Int32> System.Func<System.Int32, System.Object> System.Func<System.String>"); } [Fact] public void ImplicitlyTypedVariables_14() { var source = @"delegate void D(string s); class Program { static void Main() { (D x, var y) = (() => string.Empty, () => string.Empty); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,19): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y'. // (D x, var y) = (() => string.Empty, () => string.Empty); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y").WithArguments("y").WithLocation(6, 19)); } [Fact] public void ImplicitlyTypedVariables_UseSiteErrors() { var source = @"class Program { static void F(object o) { } static void Main() { var d1 = F; var d2 = () => 1; } }"; var comp = CreateEmptyCompilation(source, new[] { GetCorlibWithInvalidActionAndFuncOfT() }); comp.VerifyDiagnostics( // (6,18): error CS0648: 'Action<T>' is a type not supported by the language // var d1 = F; Diagnostic(ErrorCode.ERR_BogusType, "F").WithArguments("System.Action<T>").WithLocation(6, 18), // (7,18): error CS0648: 'Func<T>' is a type not supported by the language // var d2 = () => 1; Diagnostic(ErrorCode.ERR_BogusType, "() => 1").WithArguments("System.Func<T>").WithLocation(7, 18)); } [Fact] public void BinaryOperator_01() { var source = @"using System; class Program { static void Main() { var b1 = (() => { }) == null; var b2 = null == Main; var b3 = Main == (() => { }); Console.WriteLine((b1, b2, b3)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,18): error CS0019: Operator '==' cannot be applied to operands of type 'lambda expression' and '<null>' // var b1 = (() => { }) == null; Diagnostic(ErrorCode.ERR_BadBinaryOps, "(() => { }) == null").WithArguments("==", "lambda expression", "<null>").WithLocation(6, 18), // (7,18): error CS0019: Operator '==' cannot be applied to operands of type '<null>' and 'method group' // var b2 = null == Main; Diagnostic(ErrorCode.ERR_BadBinaryOps, "null == Main").WithArguments("==", "<null>", "method group").WithLocation(7, 18), // (8,18): error CS0019: Operator '==' cannot be applied to operands of type 'method group' and 'lambda expression' // var b3 = Main == (() => { }); Diagnostic(ErrorCode.ERR_BadBinaryOps, "Main == (() => { })").WithArguments("==", "method group", "lambda expression").WithLocation(8, 18)); var expectedOutput = @"(False, False, False)"; CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void BinaryOperator_02() { var source = @"using System; using System.Linq.Expressions; class C { public static C operator+(C c, Delegate d) { Console.WriteLine(""operator+(C c, Delegate d)""); return c; } public static C operator+(C c, Expression e) { Console.WriteLine(""operator=(C c, Expression e)""); return c; } static void Main() { var c = new C(); _ = c + Main; _ = c + (() => 1); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (10,13): error CS0019: Operator '+' cannot be applied to operands of type 'C' and 'method group' // _ = c + Main; Diagnostic(ErrorCode.ERR_BadBinaryOps, "c + Main").WithArguments("+", "C", "method group").WithLocation(10, 13), // (11,13): error CS0019: Operator '+' cannot be applied to operands of type 'C' and 'lambda expression' // _ = c + (() => 1); Diagnostic(ErrorCode.ERR_BadBinaryOps, "c + (() => 1)").WithArguments("+", "C", "lambda expression").WithLocation(11, 13)); var expectedDiagnostics = new[] { // (10,13): error CS0034: Operator '+' is ambiguous on operands of type 'C' and 'method group' // _ = c + Main; Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "c + Main").WithArguments("+", "C", "method group").WithLocation(10, 13), // (11,13): error CS0034: Operator '+' is ambiguous on operands of type 'C' and 'lambda expression' // _ = c + (() => 1); Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "c + (() => 1)").WithArguments("+", "C", "lambda expression").WithLocation(11, 13) }; comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void BinaryOperator_03() { var source = @"using System; class C { public static C operator+(C c, Delegate d) { Console.WriteLine(""operator+(C c, Delegate d)""); return c; } public static C operator+(C c, object o) { Console.WriteLine(""operator+(C c, object o)""); return c; } static int F() => 0; static void Main() { var c = new C(); _ = c + F; _ = c + (() => 1); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (10,13): error CS0019: Operator '+' cannot be applied to operands of type 'C' and 'method group' // _ = c + F; Diagnostic(ErrorCode.ERR_BadBinaryOps, "c + F").WithArguments("+", "C", "method group").WithLocation(10, 13), // (11,13): error CS0019: Operator '+' cannot be applied to operands of type 'C' and 'lambda expression' // _ = c + (() => 1); Diagnostic(ErrorCode.ERR_BadBinaryOps, "c + (() => 1)").WithArguments("+", "C", "lambda expression").WithLocation(11, 13)); var expectedOutput = @"operator+(C c, Delegate d) operator+(C c, Delegate d) "; CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void BinaryOperator_04() { var source = @"using System; using System.Linq.Expressions; class C { public static C operator+(C c, Expression e) { Console.WriteLine(""operator+(C c, Expression e)""); return c; } public static C operator+(C c, object o) { Console.WriteLine(""operator+(C c, object o)""); return c; } static int F() => 0; static void Main() { var c = new C(); _ = c + F; _ = c + (() => 1); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (11,13): error CS0019: Operator '+' cannot be applied to operands of type 'C' and 'method group' // _ = c + F; Diagnostic(ErrorCode.ERR_BadBinaryOps, "c + F").WithArguments("+", "C", "method group").WithLocation(11, 13), // (12,13): error CS0019: Operator '+' cannot be applied to operands of type 'C' and 'lambda expression' // _ = c + (() => 1); Diagnostic(ErrorCode.ERR_BadBinaryOps, "c + (() => 1)").WithArguments("+", "C", "lambda expression").WithLocation(12, 13)); var expectedDiagnostics = new[] { // (11,17): error CS0428: Cannot convert method group 'F' to non-delegate type 'Expression'. Did you intend to invoke the method? // _ = c + F; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "System.Linq.Expressions.Expression").WithLocation(11, 17) }; comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void BinaryOperator_05() { var source = @"using System; class C { public static C operator+(C c, Delegate d) { Console.WriteLine(""operator+(C c, Delegate d)""); return c; } public static C operator+(C c, Func<object> f) { Console.WriteLine(""operator+(C c, Func<object> f)""); return c; } static int F() => 0; static void Main() { var c = new C(); _ = c + F; _ = c + (() => 1); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (10,13): error CS0019: Operator '+' cannot be applied to operands of type 'C' and 'method group' // _ = c + F; Diagnostic(ErrorCode.ERR_BadBinaryOps, "c + F").WithArguments("+", "C", "method group").WithLocation(10, 13)); var expectedOutput = @"operator+(C c, Delegate d) operator+(C c, Func<object> f) "; CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void BinaryOperator_06() { var source = @"using System; using System.Linq.Expressions; class C { public static C operator+(C c, Expression e) { Console.WriteLine(""operator+(C c, Expression e)""); return c; } public static C operator+(C c, Func<object> f) { Console.WriteLine(""operator+(C c, Func<object> f)""); return c; } static void Main() { var c = new C(); _ = c + (() => new object()); _ = c + (() => 1); } }"; var expectedOutput = @"operator+(C c, Func<object> f) operator+(C c, Func<object> f) "; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void BinaryOperator_07() { var source = @"using System; using System.Linq.Expressions; class C { public static C operator+(C c, Expression e) { Console.WriteLine(""operator+(C c, Expression e)""); return c; } public static C operator+(C c, Func<object> f) { Console.WriteLine(""operator+(C c, Func<object> f)""); return c; } static int F() => 0; static void Main() { var c = new C(); _ = c + F; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (11,13): error CS0019: Operator '+' cannot be applied to operands of type 'C' and 'method group' // _ = c + F; Diagnostic(ErrorCode.ERR_BadBinaryOps, "c + F").WithArguments("+", "C", "method group").WithLocation(11, 13)); var expectedDiagnostics = new[] { // (11,17): error CS0428: Cannot convert method group 'F' to non-delegate type 'Expression'. Did you intend to invoke the method? // _ = c + F; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "System.Linq.Expressions.Expression").WithLocation(11, 17) }; comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void BinaryOperator_08() { var source = @"using System; class A { public static A operator+(A a, Func<int> f) { Console.WriteLine(""operator+(A a, Func<int> f)""); return a; } } class B : A { public static B operator+(B b, Delegate d) { Console.WriteLine(""operator+(B b, Delegate d)""); return b; } static int F() => 1; static void Main() { var b = new B(); _ = b + F; _ = b + (() => 2); } }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: @"operator+(A a, Func<int> f) operator+(A a, Func<int> f) "); // Breaking change from C#9. string expectedOutput = @"operator+(B b, Delegate d) operator+(B b, Delegate d) "; CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } /// <summary> /// Ensure the conversion group containing the implicit /// conversion is handled correctly in NullableWalker. /// </summary> [Fact] public void NullableAnalysis_01() { var source = @"#nullable enable class Program { static void Main() { System.Delegate d; d = Main; d = () => { }; d = delegate () { }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics(); } /// <summary> /// Ensure the conversion group containing the explicit /// conversion is handled correctly in NullableWalker. /// </summary> [Fact] public void NullableAnalysis_02() { var source = @"#nullable enable class Program { static void Main() { object o; o = (System.Delegate)Main; o = (System.Delegate)(() => { }); o = (System.Delegate)(delegate () { }); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics(); } [Fact] public void SynthesizedDelegateTypes_01() { var source = @"using System; class Program { static void M1<T>(T t) { var d = (ref T t) => t; Report(d); Console.WriteLine(d(ref t)); } static void M2<U>(U u) where U : struct { var d = (ref U u) => u; Report(d); Console.WriteLine(d(ref u)); } static void M3(double value) { var d = (ref double d) => d; Report(d); Console.WriteLine(d(ref value)); } static void Main() { M1(41); M2(42f); M2(43d); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: @"<>F{00000001}`2[System.Int32,System.Int32] 41 <>F{00000001}`2[System.Single,System.Single] 42 <>F{00000001}`2[System.Double,System.Double] 43 "); verifier.VerifyIL("Program.M1<T>", @"{ // Code size 55 (0x37) .maxstack 2 IL_0000: ldsfld ""<>F{00000001}<T, T> Program.<>c__0<T>.<>9__0_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""Program.<>c__0<T> Program.<>c__0<T>.<>9"" IL_000e: ldftn ""T Program.<>c__0<T>.<M1>b__0_0(ref T)"" IL_0014: newobj ""<>F{00000001}<T, T>..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""<>F{00000001}<T, T> Program.<>c__0<T>.<>9__0_0"" IL_001f: dup IL_0020: call ""void Program.Report(System.Delegate)"" IL_0025: ldarga.s V_0 IL_0027: callvirt ""T <>F{00000001}<T, T>.Invoke(ref T)"" IL_002c: box ""T"" IL_0031: call ""void System.Console.WriteLine(object)"" IL_0036: ret }"); verifier.VerifyIL("Program.M2<U>", @"{ // Code size 55 (0x37) .maxstack 2 IL_0000: ldsfld ""<>F{00000001}<U, U> Program.<>c__1<U>.<>9__1_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""Program.<>c__1<U> Program.<>c__1<U>.<>9"" IL_000e: ldftn ""U Program.<>c__1<U>.<M2>b__1_0(ref U)"" IL_0014: newobj ""<>F{00000001}<U, U>..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""<>F{00000001}<U, U> Program.<>c__1<U>.<>9__1_0"" IL_001f: dup IL_0020: call ""void Program.Report(System.Delegate)"" IL_0025: ldarga.s V_0 IL_0027: callvirt ""U <>F{00000001}<U, U>.Invoke(ref U)"" IL_002c: box ""U"" IL_0031: call ""void System.Console.WriteLine(object)"" IL_0036: ret }"); verifier.VerifyIL("Program.M3", @"{ // Code size 50 (0x32) .maxstack 2 IL_0000: ldsfld ""<>F{00000001}<double, double> Program.<>c.<>9__2_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""Program.<>c Program.<>c.<>9"" IL_000e: ldftn ""double Program.<>c.<M3>b__2_0(ref double)"" IL_0014: newobj ""<>F{00000001}<double, double>..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""<>F{00000001}<double, double> Program.<>c.<>9__2_0"" IL_001f: dup IL_0020: call ""void Program.Report(System.Delegate)"" IL_0025: ldarga.s V_0 IL_0027: callvirt ""double <>F{00000001}<double, double>.Invoke(ref double)"" IL_002c: call ""void System.Console.WriteLine(double)"" IL_0031: ret }"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var nodes = tree.GetRoot().DescendantNodes(); var variables = nodes.OfType<VariableDeclaratorSyntax>().Where(v => v.Identifier.Text == "d").ToArray(); Assert.Equal(3, variables.Length); VerifyLocalDelegateType(model, variables[0], "<>F{00000001}<T, T> d", "T <>F{00000001}<T, T>.Invoke(ref T)"); VerifyLocalDelegateType(model, variables[1], "<>F{00000001}<U, U> d", "U <>F{00000001}<U, U>.Invoke(ref U)"); VerifyLocalDelegateType(model, variables[2], "<>F{00000001}<System.Double, System.Double> d", "System.Double <>F{00000001}<System.Double, System.Double>.Invoke(ref System.Double)"); var identifiers = nodes.OfType<InvocationExpressionSyntax>().Where(i => i.Expression is IdentifierNameSyntax id && id.Identifier.Text == "Report").Select(i => i.ArgumentList.Arguments[0].Expression).ToArray(); Assert.Equal(3, identifiers.Length); VerifyExpressionType(model, identifiers[0], "<>F{00000001}<T, T> d", "<>F{00000001}<T, T>"); VerifyExpressionType(model, identifiers[1], "<>F{00000001}<U, U> d", "<>F{00000001}<U, U>"); VerifyExpressionType(model, identifiers[2], "<>F{00000001}<System.Double, System.Double> d", "<>F{00000001}<System.Double, System.Double>"); } [Fact] public void SynthesizedDelegateTypes_02() { var source = @"using System; class Program { static void M1(A a, int value) { var d = a.F1; d() = value; } static void M2(B b, float value) { var d = b.F2; d() = value; } static void Main() { var a = new A(); M1(a, 41); var b = new B(); M2(b, 42f); Console.WriteLine((a._f, b._f)); } } class A { public int _f; public ref int F1() => ref _f; } class B { public float _f; } static class E { public static ref float F2(this B b) => ref b._f; }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: @"(41, 42)"); verifier.VerifyIL("Program.M1", @"{ // Code size 20 (0x14) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldftn ""ref int A.F1()"" IL_0007: newobj ""<>F{00000001}<int>..ctor(object, System.IntPtr)"" IL_000c: callvirt ""ref int <>F{00000001}<int>.Invoke()"" IL_0011: ldarg.1 IL_0012: stind.i4 IL_0013: ret }"); verifier.VerifyIL("Program.M2", @"{ // Code size 20 (0x14) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldftn ""ref float E.F2(B)"" IL_0007: newobj ""<>F{00000001}<float>..ctor(object, System.IntPtr)"" IL_000c: callvirt ""ref float <>F{00000001}<float>.Invoke()"" IL_0011: ldarg.1 IL_0012: stind.r4 IL_0013: ret }"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var variables = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(v => v.Identifier.Text == "d").ToArray(); Assert.Equal(2, variables.Length); VerifyLocalDelegateType(model, variables[0], "<>F{00000001}<System.Int32> d", "ref System.Int32 <>F{00000001}<System.Int32>.Invoke()"); VerifyLocalDelegateType(model, variables[1], "<>F{00000001}<System.Single> d", "ref System.Single <>F{00000001}<System.Single>.Invoke()"); } [Fact] public void SynthesizedDelegateTypes_03() { var source = @"using System; class Program { static void Main() { Report((ref int x, int y) => { }); Report((int x, ref int y) => { }); Report((ref float x, int y) => { }); Report((float x, ref int y) => { }); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: @"<>A{00000001}`2[System.Int32,System.Int32] <>A{00000004}`2[System.Int32,System.Int32] <>A{00000001}`2[System.Single,System.Int32] <>A{00000004}`2[System.Single,System.Int32] "); verifier.VerifyIL("Program.Main", @"{ // Code size 145 (0x91) .maxstack 2 IL_0000: ldsfld ""<>A{00000001}<int, int> Program.<>c.<>9__0_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""Program.<>c Program.<>c.<>9"" IL_000e: ldftn ""void Program.<>c.<Main>b__0_0(ref int, int)"" IL_0014: newobj ""<>A{00000001}<int, int>..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""<>A{00000001}<int, int> Program.<>c.<>9__0_0"" IL_001f: call ""void Program.Report(System.Delegate)"" IL_0024: ldsfld ""<>A{00000004}<int, int> Program.<>c.<>9__0_1"" IL_0029: dup IL_002a: brtrue.s IL_0043 IL_002c: pop IL_002d: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0032: ldftn ""void Program.<>c.<Main>b__0_1(int, ref int)"" IL_0038: newobj ""<>A{00000004}<int, int>..ctor(object, System.IntPtr)"" IL_003d: dup IL_003e: stsfld ""<>A{00000004}<int, int> Program.<>c.<>9__0_1"" IL_0043: call ""void Program.Report(System.Delegate)"" IL_0048: ldsfld ""<>A{00000001}<float, int> Program.<>c.<>9__0_2"" IL_004d: dup IL_004e: brtrue.s IL_0067 IL_0050: pop IL_0051: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0056: ldftn ""void Program.<>c.<Main>b__0_2(ref float, int)"" IL_005c: newobj ""<>A{00000001}<float, int>..ctor(object, System.IntPtr)"" IL_0061: dup IL_0062: stsfld ""<>A{00000001}<float, int> Program.<>c.<>9__0_2"" IL_0067: call ""void Program.Report(System.Delegate)"" IL_006c: ldsfld ""<>A{00000004}<float, int> Program.<>c.<>9__0_3"" IL_0071: dup IL_0072: brtrue.s IL_008b IL_0074: pop IL_0075: ldsfld ""Program.<>c Program.<>c.<>9"" IL_007a: ldftn ""void Program.<>c.<Main>b__0_3(float, ref int)"" IL_0080: newobj ""<>A{00000004}<float, int>..ctor(object, System.IntPtr)"" IL_0085: dup IL_0086: stsfld ""<>A{00000004}<float, int> Program.<>c.<>9__0_3"" IL_008b: call ""void Program.Report(System.Delegate)"" IL_0090: ret }"); } [Fact] public void SynthesizedDelegateTypes_04() { var source = @"using System; class Program { static int i = 0; static void Main() { Report(int () => i); Report((ref int () => ref i)); Report((ref readonly int () => ref i)); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: @"System.Func`1[System.Int32] <>F{00000001}`1[System.Int32] <>F{00000003}`1[System.Int32] "); verifier.VerifyIL("Program.Main", @"{ // Code size 109 (0x6d) .maxstack 2 IL_0000: ldsfld ""System.Func<int> Program.<>c.<>9__1_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""Program.<>c Program.<>c.<>9"" IL_000e: ldftn ""int Program.<>c.<Main>b__1_0()"" IL_0014: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""System.Func<int> Program.<>c.<>9__1_0"" IL_001f: call ""void Program.Report(System.Delegate)"" IL_0024: ldsfld ""<>F{00000001}<int> Program.<>c.<>9__1_1"" IL_0029: dup IL_002a: brtrue.s IL_0043 IL_002c: pop IL_002d: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0032: ldftn ""ref int Program.<>c.<Main>b__1_1()"" IL_0038: newobj ""<>F{00000001}<int>..ctor(object, System.IntPtr)"" IL_003d: dup IL_003e: stsfld ""<>F{00000001}<int> Program.<>c.<>9__1_1"" IL_0043: call ""void Program.Report(System.Delegate)"" IL_0048: ldsfld ""<>F{00000003}<int> Program.<>c.<>9__1_2"" IL_004d: dup IL_004e: brtrue.s IL_0067 IL_0050: pop IL_0051: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0056: ldftn ""ref readonly int Program.<>c.<Main>b__1_2()"" IL_005c: newobj ""<>F{00000003}<int>..ctor(object, System.IntPtr)"" IL_0061: dup IL_0062: stsfld ""<>F{00000003}<int> Program.<>c.<>9__1_2"" IL_0067: call ""void Program.Report(System.Delegate)"" IL_006c: ret }"); } [Fact] public void SynthesizedDelegateTypes_05() { var source = @"using System; class Program { static int i = 0; static int F1() => i; static ref int F2() => ref i; static ref readonly int F3() => ref i; static void Main() { Report(F1); Report(F2); Report(F3); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: @"System.Func`1[System.Int32] <>F{00000001}`1[System.Int32] <>F{00000003}`1[System.Int32] "); verifier.VerifyIL("Program.Main", @"{ // Code size 52 (0x34) .maxstack 2 IL_0000: ldnull IL_0001: ldftn ""int Program.F1()"" IL_0007: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_000c: call ""void Program.Report(System.Delegate)"" IL_0011: ldnull IL_0012: ldftn ""ref int Program.F2()"" IL_0018: newobj ""<>F{00000001}<int>..ctor(object, System.IntPtr)"" IL_001d: call ""void Program.Report(System.Delegate)"" IL_0022: ldnull IL_0023: ldftn ""ref readonly int Program.F3()"" IL_0029: newobj ""<>F{00000003}<int>..ctor(object, System.IntPtr)"" IL_002e: call ""void Program.Report(System.Delegate)"" IL_0033: ret }"); } [Fact] public void SynthesizedDelegateTypes_06() { var source = @"using System; class Program { static int i = 0; static int F1() => i; static ref int F2() => ref i; static ref readonly int F3() => ref i; static void Main() { var d1 = F1; var d2 = F2; var d3 = F3; Report(d1); Report(d2); Report(d3); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"System.Func`1[System.Int32] <>F{00000001}`1[System.Int32] <>F{00000003}`1[System.Int32] "); } [Fact] public void SynthesizedDelegateTypes_07() { var source = @"using System; class Program { static void Main() { Report(int (ref int i) => i); Report((ref int (ref int i) => ref i)); Report((ref readonly int (ref int i) => ref i)); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput: @"<>F{00000001}`2[System.Int32,System.Int32] <>F{00000005}`2[System.Int32,System.Int32] <>F{0000000d}`2[System.Int32,System.Int32] "); verifier.VerifyIL("Program.Main", @"{ // Code size 109 (0x6d) .maxstack 2 IL_0000: ldsfld ""<>F{00000001}<int, int> Program.<>c.<>9__0_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""Program.<>c Program.<>c.<>9"" IL_000e: ldftn ""int Program.<>c.<Main>b__0_0(ref int)"" IL_0014: newobj ""<>F{00000001}<int, int>..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""<>F{00000001}<int, int> Program.<>c.<>9__0_0"" IL_001f: call ""void Program.Report(System.Delegate)"" IL_0024: ldsfld ""<>F{00000005}<int, int> Program.<>c.<>9__0_1"" IL_0029: dup IL_002a: brtrue.s IL_0043 IL_002c: pop IL_002d: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0032: ldftn ""ref int Program.<>c.<Main>b__0_1(ref int)"" IL_0038: newobj ""<>F{00000005}<int, int>..ctor(object, System.IntPtr)"" IL_003d: dup IL_003e: stsfld ""<>F{00000005}<int, int> Program.<>c.<>9__0_1"" IL_0043: call ""void Program.Report(System.Delegate)"" IL_0048: ldsfld ""<>F{0000000d}<int, int> Program.<>c.<>9__0_2"" IL_004d: dup IL_004e: brtrue.s IL_0067 IL_0050: pop IL_0051: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0056: ldftn ""ref readonly int Program.<>c.<Main>b__0_2(ref int)"" IL_005c: newobj ""<>F{0000000d}<int, int>..ctor(object, System.IntPtr)"" IL_0061: dup IL_0062: stsfld ""<>F{0000000d}<int, int> Program.<>c.<>9__0_2"" IL_0067: call ""void Program.Report(System.Delegate)"" IL_006c: ret }"); } [Fact] public void SynthesizedDelegateTypes_08() { var source = @"#pragma warning disable 414 using System; class Program { static int i = 0; static void Main() { Report((int i) => { }); Report((out int i) => { i = 0; }); Report((ref int i) => { }); Report((in int i) => { }); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: @"System.Action`1[System.Int32] <>A{00000002}`1[System.Int32] <>A{00000001}`1[System.Int32] <>A{00000003}`1[System.Int32] "); verifier.VerifyIL("Program.Main", @"{ // Code size 145 (0x91) .maxstack 2 IL_0000: ldsfld ""System.Action<int> Program.<>c.<>9__1_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""Program.<>c Program.<>c.<>9"" IL_000e: ldftn ""void Program.<>c.<Main>b__1_0(int)"" IL_0014: newobj ""System.Action<int>..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""System.Action<int> Program.<>c.<>9__1_0"" IL_001f: call ""void Program.Report(System.Delegate)"" IL_0024: ldsfld ""<>A{00000002}<int> Program.<>c.<>9__1_1"" IL_0029: dup IL_002a: brtrue.s IL_0043 IL_002c: pop IL_002d: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0032: ldftn ""void Program.<>c.<Main>b__1_1(out int)"" IL_0038: newobj ""<>A{00000002}<int>..ctor(object, System.IntPtr)"" IL_003d: dup IL_003e: stsfld ""<>A{00000002}<int> Program.<>c.<>9__1_1"" IL_0043: call ""void Program.Report(System.Delegate)"" IL_0048: ldsfld ""<>A{00000001}<int> Program.<>c.<>9__1_2"" IL_004d: dup IL_004e: brtrue.s IL_0067 IL_0050: pop IL_0051: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0056: ldftn ""void Program.<>c.<Main>b__1_2(ref int)"" IL_005c: newobj ""<>A{00000001}<int>..ctor(object, System.IntPtr)"" IL_0061: dup IL_0062: stsfld ""<>A{00000001}<int> Program.<>c.<>9__1_2"" IL_0067: call ""void Program.Report(System.Delegate)"" IL_006c: ldsfld ""<>A{00000003}<int> Program.<>c.<>9__1_3"" IL_0071: dup IL_0072: brtrue.s IL_008b IL_0074: pop IL_0075: ldsfld ""Program.<>c Program.<>c.<>9"" IL_007a: ldftn ""void Program.<>c.<Main>b__1_3(in int)"" IL_0080: newobj ""<>A{00000003}<int>..ctor(object, System.IntPtr)"" IL_0085: dup IL_0086: stsfld ""<>A{00000003}<int> Program.<>c.<>9__1_3"" IL_008b: call ""void Program.Report(System.Delegate)"" IL_0090: ret }"); } [Fact] public void SynthesizedDelegateTypes_09() { var source = @"#pragma warning disable 414 using System; class Program { static void M1(int i) { } static void M2(out int i) { i = 0; } static void M3(ref int i) { } static void M4(in int i) { } static void Main() { Report(M1); Report(M2); Report(M3); Report(M4); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: @"System.Action`1[System.Int32] <>A{00000002}`1[System.Int32] <>A{00000001}`1[System.Int32] <>A{00000003}`1[System.Int32] "); verifier.VerifyIL("Program.Main", @"{ // Code size 69 (0x45) .maxstack 2 IL_0000: ldnull IL_0001: ldftn ""void Program.M1(int)"" IL_0007: newobj ""System.Action<int>..ctor(object, System.IntPtr)"" IL_000c: call ""void Program.Report(System.Delegate)"" IL_0011: ldnull IL_0012: ldftn ""void Program.M2(out int)"" IL_0018: newobj ""<>A{00000002}<int>..ctor(object, System.IntPtr)"" IL_001d: call ""void Program.Report(System.Delegate)"" IL_0022: ldnull IL_0023: ldftn ""void Program.M3(ref int)"" IL_0029: newobj ""<>A{00000001}<int>..ctor(object, System.IntPtr)"" IL_002e: call ""void Program.Report(System.Delegate)"" IL_0033: ldnull IL_0034: ldftn ""void Program.M4(in int)"" IL_003a: newobj ""<>A{00000003}<int>..ctor(object, System.IntPtr)"" IL_003f: call ""void Program.Report(System.Delegate)"" IL_0044: ret }"); } [Fact] public void SynthesizedDelegateTypes_10() { var source = @"#pragma warning disable 414 using System; class Program { static void M1(int i) { } static void M2(out int i) { i = 0; } static void M3(ref int i) { } static void M4(in int i) { } static void Main() { var d1 = M1; var d2 = M2; var d3 = M3; var d4 = M4; Report(d1); Report(d2); Report(d3); Report(d4); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"System.Action`1[System.Int32] <>A{00000002}`1[System.Int32] <>A{00000001}`1[System.Int32] <>A{00000003}`1[System.Int32] "); } [WorkItem(55217, "https://github.com/dotnet/roslyn/issues/55217")] [Fact] public void SynthesizedDelegateTypes_11() { var source = @"class Program { unsafe static void Main() { var d1 = int* () => (int*)42; var d2 = (int* p) => { }; var d3 = delegate*<void> () => default; var d4 = (delegate*<void> d) => { }; } }"; var comp = CreateCompilation(source, options: TestOptions.UnsafeReleaseExe); comp.VerifyDiagnostics( // (5,18): error CS8917: The delegate type could not be inferred. // var d1 = int* () => (int*)42; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "int* () => (int*)42").WithLocation(5, 18), // (6,18): error CS8917: The delegate type could not be inferred. // var d2 = (int* p) => { }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(int* p) => { }").WithLocation(6, 18), // (7,18): error CS8917: The delegate type could not be inferred. // var d3 = delegate*<void> () => default; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "delegate*<void> () => default").WithLocation(7, 18), // (8,18): error CS8917: The delegate type could not be inferred. // var d4 = (delegate*<void> d) => { }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(delegate*<void> d) => { }").WithLocation(8, 18)); } [WorkItem(55217, "https://github.com/dotnet/roslyn/issues/55217")] [ConditionalFact(typeof(DesktopOnly))] public void SynthesizedDelegateTypes_12() { var source = @"using System; class Program { static void Main() { var d1 = (TypedReference x) => { }; var d2 = (int x, RuntimeArgumentHandle y) => { }; var d3 = (ArgIterator x) => { }; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,18): error CS8917: The delegate type could not be inferred. // var d1 = (TypedReference x) => { }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(TypedReference x) => { }").WithLocation(6, 18), // (7,18): error CS8917: The delegate type could not be inferred. // var d2 = (int x, RuntimeArgumentHandle y) => { }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(int x, RuntimeArgumentHandle y) => { }").WithLocation(7, 18), // (8,18): error CS8917: The delegate type could not be inferred. // var d3 = (ArgIterator x) => { }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(ArgIterator x) => { }").WithLocation(8, 18)); } [WorkItem(55217, "https://github.com/dotnet/roslyn/issues/55217")] [Fact] public void SynthesizedDelegateTypes_13() { var source = @"ref struct S<T> { } class Program { static void F1(int x, S<int> y) { } static S<T> F2<T>() => throw null; static void Main() { var d1 = F1; var d2 = F2<object>; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,18): error CS8917: The delegate type could not be inferred. // var d1 = F1; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F1").WithLocation(8, 18), // (9,18): error CS8917: The delegate type could not be inferred. // var d2 = F2<object>; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F2<object>").WithLocation(9, 18)); } [Fact] public void SynthesizedDelegateTypes_14() { var source = @"class Program { static ref void F() { } static void Main() { var d1 = F; var d2 = (ref void () => { }); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (3,16): error CS1547: Keyword 'void' cannot be used in this context // static ref void F() { } Diagnostic(ErrorCode.ERR_NoVoidHere, "void").WithLocation(3, 16), // (6,18): error CS8917: The delegate type could not be inferred. // var d1 = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F").WithLocation(6, 18), // (7,19): error CS8917: The delegate type could not be inferred. // var d2 = (ref void () => { }); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "ref void () => { }").WithLocation(7, 19), // (7,23): error CS1547: Keyword 'void' cannot be used in this context // var d2 = (ref void () => { }); Diagnostic(ErrorCode.ERR_NoVoidHere, "void").WithLocation(7, 23)); } [Fact] public void SynthesizedDelegateTypes_15() { var source = @"using System; unsafe class Program { static byte*[] F1() => null; static void F2(byte*[] a) { } static byte*[] F3(ref int i) => null; static void F4(ref byte*[] a) { } static void Main() { Report(int*[] () => null); Report((int*[] a) => { }); Report(int*[] (ref int i) => null); Report((ref int*[] a) => { }); Report(F1); Report(F2); Report(F3); Report(F4); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.UnsafeReleaseExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"System.Func`1[System.Int32*[]] System.Action`1[System.Int32*[]] <>F{00000001}`2[System.Int32,System.Int32*[]] <>A{00000001}`1[System.Int32*[]] System.Func`1[System.Byte*[]] System.Action`1[System.Byte*[]] <>F{00000001}`2[System.Int32,System.Byte*[]] <>A{00000001}`1[System.Byte*[]] "); } [Fact] public void SynthesizedDelegateTypes_16() { var source = @"using System; unsafe class Program { static delegate*<ref int>[] F1() => null; static void F2(delegate*<ref int, void>[] a) { } static delegate*<ref int>[] F3(ref int i) => null; static void F4(ref delegate*<ref int, void>[] a) { } static void Main() { Report(delegate*<int, ref int>[] () => null); Report((delegate*<int, ref int, void>[] a) => { }); Report(delegate*<int, ref int>[] (ref int i) => null); Report((ref delegate*<int, ref int, void>[] a) => { }); Report(F1); Report(F2); Report(F3); Report(F4); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.UnsafeReleaseExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"System.Func`1[(fnptr)[]] System.Action`1[(fnptr)[]] <>F{00000001}`2[System.Int32,(fnptr)[]] <>A{00000001}`1[(fnptr)[]] System.Func`1[(fnptr)[]] System.Action`1[(fnptr)[]] <>F{00000001}`2[System.Int32,(fnptr)[]] <>A{00000001}`1[(fnptr)[]] "); } [Fact] public void SynthesizedDelegateTypes_17() { var source = @"#nullable enable using System; class Program { static void F1(object x, dynamic y) { } static void F2(IntPtr x, nint y) { } static void F3((int x, int y) t) { } static void F4(object? x, object?[] y) { } static void F5(ref object x, dynamic y) { } static void F6(IntPtr x, ref nint y) { } static void F7(ref (int x, int y) t) { } static void F8(object? x, ref object?[] y) { } static void Main() { Report(F1); Report(F2); Report(F3); Report(F4); Report(F5); Report(F6); Report(F7); Report(F8); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"System.Action`2[System.Object,System.Object] System.Action`2[System.IntPtr,System.IntPtr] System.Action`1[System.ValueTuple`2[System.Int32,System.Int32]] System.Action`2[System.Object,System.Object[]] <>A{00000001}`2[System.Object,System.Object] <>A{00000004}`2[System.IntPtr,System.IntPtr] <>A{00000001}`1[System.ValueTuple`2[System.Int32,System.Int32]] <>A{00000004}`2[System.Object,System.Object[]] "); } [Fact] [WorkItem(55570, "https://github.com/dotnet/roslyn/issues/55570")] public void SynthesizedDelegateTypes_18() { var source = @"using System; class Program { static void Main() { Report((int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) => { return 1; }); Report((int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, out int _17) => { _17 = 0; return 2; }); Report((int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, ref int _17) => { return 3; }); Report((int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, in int _17) => { return 4; }); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"<>F`18[System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Int32] <>F{200000000}`18[System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Int32] <>F{100000000}`18[System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Int32] <>F{300000000}`18[System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Int32] "); } [Fact] [WorkItem(55570, "https://github.com/dotnet/roslyn/issues/55570")] public void SynthesizedDelegateTypes_19() { var source = @"using System; class Program { static void F1(ref int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17, object _18) { } static void F2(ref int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17, out object _18) { _18 = null; } static void F3(ref int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17, ref object _18) { } static void F4(ref int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17, in object _18) { } static void Main() { Report(F1); Report(F2); Report(F3); Report(F4); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"<>A{00000001}`18[System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object] <>A{800000001}`18[System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object] <>A{400000001}`18[System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object] <>A{c00000001}`18[System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object] "); } [Fact] [WorkItem(55570, "https://github.com/dotnet/roslyn/issues/55570")] public void SynthesizedDelegateTypes_20() { var source = @"using System; class Program { static void F1( int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17, object _18, int _19, object _20, int _21, object _22, int _23, object _24, int _25, object _26, int _27, object _28, int _29, object _30, int _31, ref object _32, int _33) { } static void F2( int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17, object _18, int _19, object _20, int _21, object _22, int _23, object _24, int _25, object _26, int _27, object _28, int _29, object _30, int _31, ref object _32, out int _33) { _33 = 0; } static void F3( int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17, object _18, int _19, object _20, int _21, object _22, int _23, object _24, int _25, object _26, int _27, object _28, int _29, object _30, int _31, ref object _32, ref int _33) { } static void F4( int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17, object _18, int _19, object _20, int _21, object _22, int _23, object _24, int _25, object _26, int _27, object _28, int _29, object _30, int _31, ref object _32, in int _33) { } static void Main() { Report(F1); Report(F2); Report(F3); Report(F4); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"<>A{4000000000000000\,00000000}`33[System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32] <>A{4000000000000000\,00000002}`33[System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32] <>A{4000000000000000\,00000001}`33[System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32] <>A{4000000000000000\,00000003}`33[System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32] "); } /// <summary> /// Synthesized delegate types should only be emitted if used. /// </summary> [Fact] [WorkItem(55896, "https://github.com/dotnet/roslyn/issues/55896")] public void SynthesizedDelegateTypes_21() { var source = @"using System; delegate void D2(object x, ref object y); delegate void D4(out object x, ref object y); class Program { static void M(Delegate d) { Report(d); } static void M(D2 d) { Report(d); } static void M(D4 d) { Report(d); } static void F1(ref object x, object y) { } static void F2(object x, ref object y) { } static void Main() { M(F1); M(F2); M((ref object x, out object y) => { y = null; }); M((out object x, ref object y) => { x = null; }); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(comp, validator: validator, expectedOutput: @"<>A{00000001}`2[System.Object,System.Object] D2 <>A{00000009}`2[System.Object,System.Object] D4"); static void validator(PEAssembly assembly) { var reader = assembly.GetMetadataReader(); var actualTypes = reader.GetTypeDefNames().Select(h => reader.GetString(h)).ToArray(); // https://github.com/dotnet/roslyn/issues/55896: Should not include <>A{00000004}`2 or <>A{00000006}`2. string[] expectedTypes = new[] { "<Module>", "<>A{00000001}`2", "<>A{00000004}`2", "<>A{00000006}`2", "<>A{00000009}`2", "D2", "D4", "Program", "<>c", }; AssertEx.Equal(expectedTypes, actualTypes); } } private static void VerifyLocalDelegateType(SemanticModel model, VariableDeclaratorSyntax variable, string expectedLocal, string expectedInvokeMethod) { var local = (ILocalSymbol)model.GetDeclaredSymbol(variable)!; Assert.Equal(expectedLocal, local.ToTestDisplayString()); var delegateType = ((INamedTypeSymbol)local.Type); Assert.Equal(Accessibility.Internal, delegateType.DeclaredAccessibility); Assert.Equal(expectedInvokeMethod, delegateType.DelegateInvokeMethod.ToTestDisplayString()); } private static void VerifyExpressionType(SemanticModel model, ExpressionSyntax variable, string expectedSymbol, string expectedType) { var symbol = model.GetSymbolInfo(variable).Symbol; Assert.Equal(expectedSymbol, symbol.ToTestDisplayString()); var type = model.GetTypeInfo(variable).Type; Assert.Equal(expectedType, type.ToTestDisplayString()); } [Fact] public void ClassifyConversionFromExpression() { var source = @"class Program { static void Main() { object o = () => 1; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var funcOfT = comp.GetWellKnownType(WellKnownType.System_Func_T); var tree = comp.SyntaxTrees[0]; var expr = tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().Single(); var model = comp.GetSemanticModel(tree); model = ((CSharpSemanticModel)model).GetMemberModel(expr); verifyConversions(model, expr, comp.GetSpecialType(SpecialType.System_MulticastDelegate).GetPublicSymbol(), ConversionKind.FunctionType, ConversionKind.FunctionType); verifyConversions(model, expr, comp.GetWellKnownType(WellKnownType.System_Linq_Expressions_Expression).GetPublicSymbol(), ConversionKind.FunctionType, ConversionKind.FunctionType); verifyConversions(model, expr, getFunctionType(funcOfT.Construct(comp.GetSpecialType(SpecialType.System_Int32))), ConversionKind.FunctionType, ConversionKind.FunctionType); verifyConversions(model, expr, getFunctionType(funcOfT.Construct(comp.GetSpecialType(SpecialType.System_Object))), ConversionKind.NoConversion, ConversionKind.NoConversion); static ITypeSymbol getFunctionType(NamedTypeSymbol delegateType) { return new FunctionTypeSymbol_PublicModel(new FunctionTypeSymbol(delegateType)); } static void verifyConversions(SemanticModel model, ExpressionSyntax expr, ITypeSymbol destination, ConversionKind expectedImplicitKind, ConversionKind expectedExplicitKind) { Assert.Equal(expectedImplicitKind, model.ClassifyConversion(expr, destination, isExplicitInSource: false).Kind); Assert.Equal(expectedExplicitKind, model.ClassifyConversion(expr, destination, isExplicitInSource: true).Kind); } } private sealed class FunctionTypeSymbol_PublicModel : Symbols.PublicModel.TypeSymbol { private readonly FunctionTypeSymbol _underlying; internal FunctionTypeSymbol_PublicModel(FunctionTypeSymbol underlying) : base(nullableAnnotation: default) { _underlying = underlying; } internal override TypeSymbol UnderlyingTypeSymbol => _underlying; internal override NamespaceOrTypeSymbol UnderlyingNamespaceOrTypeSymbol => _underlying; internal override Symbol UnderlyingSymbol => _underlying; protected override void Accept(SymbolVisitor visitor) => throw new NotImplementedException(); protected override TResult Accept<TResult>(SymbolVisitor<TResult> visitor) => throw new NotImplementedException(); protected override ITypeSymbol WithNullableAnnotation(CodeAnalysis.NullableAnnotation nullableAnnotation) => this; } [WorkItem(56407, "https://github.com/dotnet/roslyn/issues/56407")] [Fact] public void UserDefinedConversions_01() { var source = @"using System.Linq.Expressions; public class Program { public static void Main() { SomeMethod((Employee e) => e.Name); } public static void SomeMethod(Field field) { } public class Employee { public string Name { get; set; } } public class Field { public static implicit operator Field(Expression expression) => null; } }"; var expectedDiagnostics = new[] { // (7,20): error CS1660: Cannot convert lambda expression to type 'Program.Field' because it is not a delegate type // SomeMethod((Employee e) => e.Name); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "(Employee e) => e.Name").WithArguments("lambda expression", "Program.Field").WithLocation(7, 20) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void UserDefinedConversions_Implicit_01() { var source = @"using System; using System.Linq.Expressions; class C1 { public static implicit operator C1(Func<int> f) { Console.WriteLine(""operator C1(Func<int> f)""); return new C1(); } } class C2 { public static implicit operator C2(Expression<Func<int>> e) { Console.WriteLine(""operator C2(Expression<Func<int>> e)""); return new C2(); } } class Program { static int F() => 0; static void Main() { C1 c1 = () => 1; C2 c2 = () => 2; c1 = F; _ = (C1)(() => 1); _ = (C2)(() => 2); _ = (C1)F; } }"; var expectedDiagnostics = new[] { // (16,17): error CS1660: Cannot convert lambda expression to type 'C1' because it is not a delegate type // C1 c1 = () => 1; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "C1").WithLocation(16, 17), // (17,17): error CS1660: Cannot convert lambda expression to type 'C2' because it is not a delegate type // C2 c2 = () => 2; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 2").WithArguments("lambda expression", "C2").WithLocation(17, 17), // (18,14): error CS0428: Cannot convert method group 'F' to non-delegate type 'C1'. Did you intend to invoke the method? // c1 = F; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "C1").WithLocation(18, 14) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void UserDefinedConversions_Implicit_02() { var source = @"using System; class C1 { public static implicit operator C1(object o) { Console.WriteLine(""operator C1(object o)""); return new C1(); } } class C2 { public static implicit operator C2(ICloneable c) { Console.WriteLine(""operator C2(ICloneable c)""); return new C2(); } } class Program { static int F() => 0; static void Main() { C1 c1 = () => 1; C2 c2 = () => 2; c1 = F; c2 = F; _ = (C1)(() => 1); _ = (C2)(() => 2); _ = (C1)F; _ = (C2)F; } }"; var expectedDiagnostics = new[] { // (4,37): error CS0553: 'C1.implicit operator C1(object)': user-defined conversions to or from a base type are not allowed // public static implicit operator C1(object o) { Console.WriteLine("operator C1(object o)"); return new C1(); } Diagnostic(ErrorCode.ERR_ConversionWithBase, "C1").WithArguments("C1.implicit operator C1(object)").WithLocation(4, 37), // (8,37): error CS0552: 'C2.implicit operator C2(ICloneable)': user-defined conversions to or from an interface are not allowed // public static implicit operator C2(ICloneable c) { Console.WriteLine("operator C2(ICloneable c)"); return new C2(); } Diagnostic(ErrorCode.ERR_ConversionWithInterface, "C2").WithArguments("C2.implicit operator C2(System.ICloneable)").WithLocation(8, 37), // (15,17): error CS1660: Cannot convert lambda expression to type 'C1' because it is not a delegate type // C1 c1 = () => 1; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "C1").WithLocation(15, 17), // (16,17): error CS1660: Cannot convert lambda expression to type 'C2' because it is not a delegate type // C2 c2 = () => 2; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 2").WithArguments("lambda expression", "C2").WithLocation(16, 17), // (17,14): error CS0428: Cannot convert method group 'F' to non-delegate type 'C1'. Did you intend to invoke the method? // c1 = F; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "C1").WithLocation(17, 14), // (18,14): error CS0428: Cannot convert method group 'F' to non-delegate type 'C2'. Did you intend to invoke the method? // c2 = F; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "C2").WithLocation(18, 14), // (19,18): error CS1660: Cannot convert lambda expression to type 'C1' because it is not a delegate type // _ = (C1)(() => 1); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "C1").WithLocation(19, 18), // (20,18): error CS1660: Cannot convert lambda expression to type 'C2' because it is not a delegate type // _ = (C2)(() => 2); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 2").WithArguments("lambda expression", "C2").WithLocation(20, 18), // (21,13): error CS0030: Cannot convert type 'method' to 'C1' // _ = (C1)F; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(C1)F").WithArguments("method", "C1").WithLocation(21, 13), // (22,13): error CS0030: Cannot convert type 'method' to 'C2' // _ = (C2)F; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(C2)F").WithArguments("method", "C2").WithLocation(22, 13) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void UserDefinedConversions_Implicit_03() { var source = @"using System; using System.Linq.Expressions; class C1 { public static implicit operator C1(Delegate d) { Console.WriteLine(""operator C1(Delegate d)""); return new C1(); } } class C2 { public static implicit operator C2(MulticastDelegate d) { Console.WriteLine(""operator C2(MulticastDelegate d)""); return new C2(); } } class C3 { public static implicit operator C3(Expression e) { Console.WriteLine(""operator C3(Expression e)""); return new C3(); } } class C4 { public static implicit operator C4(LambdaExpression e) { Console.WriteLine(""operator C4(LambdaExpression e)""); return new C4(); } } class Program { static int F() => 0; static void Main() { C1 c1 = () => 1; C2 c2 = () => 2; C3 c3 = () => 3; C4 c4 = () => 4; c1 = F; c2 = F; _ = (C1)(() => 1); _ = (C2)(() => 2); _ = (C3)(() => 3); _ = (C4)(() => 4); _ = (C1)F; _ = (C2)F; } }"; var expectedDiagnostics = new[] { // (24,17): error CS1660: Cannot convert lambda expression to type 'C1' because it is not a delegate type // C1 c1 = () => 1; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "C1").WithLocation(24, 17), // (25,17): error CS1660: Cannot convert lambda expression to type 'C2' because it is not a delegate type // C2 c2 = () => 2; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 2").WithArguments("lambda expression", "C2").WithLocation(25, 17), // (26,17): error CS1660: Cannot convert lambda expression to type 'C3' because it is not a delegate type // C3 c3 = () => 3; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 3").WithArguments("lambda expression", "C3").WithLocation(26, 17), // (27,17): error CS1660: Cannot convert lambda expression to type 'C4' because it is not a delegate type // C4 c4 = () => 4; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 4").WithArguments("lambda expression", "C4").WithLocation(27, 17), // (28,14): error CS0428: Cannot convert method group 'F' to non-delegate type 'C1'. Did you intend to invoke the method? // c1 = F; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "C1").WithLocation(28, 14), // (29,14): error CS0428: Cannot convert method group 'F' to non-delegate type 'C2'. Did you intend to invoke the method? // c2 = F; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "C2").WithLocation(29, 14), // (30,18): error CS1660: Cannot convert lambda expression to type 'C1' because it is not a delegate type // _ = (C1)(() => 1); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "C1").WithLocation(30, 18), // (31,18): error CS1660: Cannot convert lambda expression to type 'C2' because it is not a delegate type // _ = (C2)(() => 2); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 2").WithArguments("lambda expression", "C2").WithLocation(31, 18), // (32,18): error CS1660: Cannot convert lambda expression to type 'C3' because it is not a delegate type // _ = (C3)(() => 3); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 3").WithArguments("lambda expression", "C3").WithLocation(32, 18), // (33,18): error CS1660: Cannot convert lambda expression to type 'C4' because it is not a delegate type // _ = (C4)(() => 4); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 4").WithArguments("lambda expression", "C4").WithLocation(33, 18), // (34,13): error CS0030: Cannot convert type 'method' to 'C1' // _ = (C1)F; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(C1)F").WithArguments("method", "C1").WithLocation(34, 13), // (35,13): error CS0030: Cannot convert type 'method' to 'C2' // _ = (C2)F; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(C2)F").WithArguments("method", "C2").WithLocation(35, 13) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void UserDefinedConversions_Implicit_04() { var source = @"using System; class C<T> { public static implicit operator C<T>(T t) { Console.WriteLine(""operator C<{0}>({0} t)"", typeof(T).FullName); return new C<T>(); } } class Program { static int F() => 0; static void Main() { C<object> c1 = () => 1; C<ICloneable> c2 = () => 2; c1 = F; c2 = F; _ = (C<object>)(() => 1); _ = (C<ICloneable>)(() => 2); _ = (C<object>)F; _ = (C<ICloneable>)F; } }"; var expectedDiagnostics = new[] { // (11,24): error CS1660: Cannot convert lambda expression to type 'C<object>' because it is not a delegate type // C<object> c1 = () => 1; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "C<object>").WithLocation(11, 24), // (12,28): error CS1660: Cannot convert lambda expression to type 'C<ICloneable>' because it is not a delegate type // C<ICloneable> c2 = () => 2; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 2").WithArguments("lambda expression", "C<System.ICloneable>").WithLocation(12, 28), // (13,14): error CS0428: Cannot convert method group 'F' to non-delegate type 'C<object>'. Did you intend to invoke the method? // c1 = F; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "C<object>").WithLocation(13, 14), // (14,14): error CS0428: Cannot convert method group 'F' to non-delegate type 'C<ICloneable>'. Did you intend to invoke the method? // c2 = F; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "C<System.ICloneable>").WithLocation(14, 14), // (15,25): error CS1660: Cannot convert lambda expression to type 'C<object>' because it is not a delegate type // _ = (C<object>)(() => 1); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "C<object>").WithLocation(15, 25), // (16,29): error CS1660: Cannot convert lambda expression to type 'C<ICloneable>' because it is not a delegate type // _ = (C<ICloneable>)(() => 2); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 2").WithArguments("lambda expression", "C<System.ICloneable>").WithLocation(16, 29), // (17,13): error CS0030: Cannot convert type 'method' to 'C<object>' // _ = (C<object>)F; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(C<object>)F").WithArguments("method", "C<object>").WithLocation(17, 13), // (18,13): error CS0030: Cannot convert type 'method' to 'C<ICloneable>' // _ = (C<ICloneable>)F; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(C<ICloneable>)F").WithArguments("method", "C<System.ICloneable>").WithLocation(18, 13) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void UserDefinedConversions_Implicit_05() { var source = @"using System; using System.Linq.Expressions; class C<T> { public static implicit operator C<T>(T t) { Console.WriteLine(""operator C<{0}>({0} t)"", typeof(T).FullName); return new C<T>(); } } class Program { static int F() => 0; static void Main() { C<Delegate> c1 = () => 1; C<MulticastDelegate> c2 = () => 2; C<Expression> c3 = () => 3; C<LambdaExpression> c4 = () => 4; c1 = F; c2 = F; _ = (C<Delegate>)(() => 1); _ = (C<MulticastDelegate>)(() => 2); _ = (C<Expression>)(() => 3); _ = (C<LambdaExpression>)(() => 4); _ = (C<Delegate>)F; _ = (C<MulticastDelegate>)F; } }"; var expectedDiagnostics = new[] { // (12,26): error CS1660: Cannot convert lambda expression to type 'C<Delegate>' because it is not a delegate type // C<Delegate> c1 = () => 1; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "C<System.Delegate>").WithLocation(12, 26), // (13,35): error CS1660: Cannot convert lambda expression to type 'C<MulticastDelegate>' because it is not a delegate type // C<MulticastDelegate> c2 = () => 2; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 2").WithArguments("lambda expression", "C<System.MulticastDelegate>").WithLocation(13, 35), // (14,28): error CS1660: Cannot convert lambda expression to type 'C<Expression>' because it is not a delegate type // C<Expression> c3 = () => 3; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 3").WithArguments("lambda expression", "C<System.Linq.Expressions.Expression>").WithLocation(14, 28), // (15,34): error CS1660: Cannot convert lambda expression to type 'C<LambdaExpression>' because it is not a delegate type // C<LambdaExpression> c4 = () => 4; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 4").WithArguments("lambda expression", "C<System.Linq.Expressions.LambdaExpression>").WithLocation(15, 34), // (16,14): error CS0428: Cannot convert method group 'F' to non-delegate type 'C<Delegate>'. Did you intend to invoke the method? // c1 = F; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "C<System.Delegate>").WithLocation(16, 14), // (17,14): error CS0428: Cannot convert method group 'F' to non-delegate type 'C<MulticastDelegate>'. Did you intend to invoke the method? // c2 = F; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "C<System.MulticastDelegate>").WithLocation(17, 14), // (18,27): error CS1660: Cannot convert lambda expression to type 'C<Delegate>' because it is not a delegate type // _ = (C<Delegate>)(() => 1); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "C<System.Delegate>").WithLocation(18, 27), // (19,36): error CS1660: Cannot convert lambda expression to type 'C<MulticastDelegate>' because it is not a delegate type // _ = (C<MulticastDelegate>)(() => 2); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 2").WithArguments("lambda expression", "C<System.MulticastDelegate>").WithLocation(19, 36), // (20,29): error CS1660: Cannot convert lambda expression to type 'C<Expression>' because it is not a delegate type // _ = (C<Expression>)(() => 3); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 3").WithArguments("lambda expression", "C<System.Linq.Expressions.Expression>").WithLocation(20, 29), // (21,35): error CS1660: Cannot convert lambda expression to type 'C<LambdaExpression>' because it is not a delegate type // _ = (C<LambdaExpression>)(() => 4); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 4").WithArguments("lambda expression", "C<System.Linq.Expressions.LambdaExpression>").WithLocation(21, 35), // (22,13): error CS0030: Cannot convert type 'method' to 'C<Delegate>' // _ = (C<Delegate>)F; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(C<Delegate>)F").WithArguments("method", "C<System.Delegate>").WithLocation(22, 13), // (23,13): error CS0030: Cannot convert type 'method' to 'C<MulticastDelegate>' // _ = (C<MulticastDelegate>)F; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(C<MulticastDelegate>)F").WithArguments("method", "C<System.MulticastDelegate>").WithLocation(23, 13) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void UserDefinedConversions_Explicit_01() { var source = @"using System; using System.Linq.Expressions; class C1 { public static explicit operator C1(Func<int> f) { Console.WriteLine(""operator C1(Func<int> f)""); return new C1(); } } class C2 { public static explicit operator C2(Expression<Func<int>> e) { Console.WriteLine(""operator C2(Expression<Func<int>> e)""); return new C2(); } } class Program { static int F() => 0; static void Main() { _ = (C1)(() => 1); _ = (C2)(() => 2); _ = (C1)F; } }"; string expectedOutput = @"operator C1(Func<int> f) operator C2(Expression<Func<int>> e) operator C1(Func<int> f) "; CompileAndVerify(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); } [Fact] public void UserDefinedConversions_Explicit_02() { var source = @"using System; class C1 { public static explicit operator C1(object o) { Console.WriteLine(""operator C1(object o)""); return new C1(); } } class C2 { public static explicit operator C2(ICloneable c) { Console.WriteLine(""operator C2(ICloneable c)""); return new C2(); } } class Program { static int F() => 0; static void Main() { _ = (C1)(() => 1); _ = (C2)(() => 2); _ = (C1)F; _ = (C2)F; } }"; var expectedDiagnostics = new[] { // (4,37): error CS0553: 'C1.explicit operator C1(object)': user-defined conversions to or from a base type are not allowed // public static explicit operator C1(object o) { Console.WriteLine("operator C1(object o)"); return new C1(); } Diagnostic(ErrorCode.ERR_ConversionWithBase, "C1").WithArguments("C1.explicit operator C1(object)").WithLocation(4, 37), // (8,37): error CS0552: 'C2.explicit operator C2(ICloneable)': user-defined conversions to or from an interface are not allowed // public static explicit operator C2(ICloneable c) { Console.WriteLine("operator C2(ICloneable c)"); return new C2(); } Diagnostic(ErrorCode.ERR_ConversionWithInterface, "C2").WithArguments("C2.explicit operator C2(System.ICloneable)").WithLocation(8, 37), // (15,18): error CS1660: Cannot convert lambda expression to type 'C1' because it is not a delegate type // _ = (C1)(() => 1); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "C1").WithLocation(15, 18), // (16,18): error CS1660: Cannot convert lambda expression to type 'C2' because it is not a delegate type // _ = (C2)(() => 2); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 2").WithArguments("lambda expression", "C2").WithLocation(16, 18), // (17,13): error CS0030: Cannot convert type 'method' to 'C1' // _ = (C1)F; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(C1)F").WithArguments("method", "C1").WithLocation(17, 13), // (18,13): error CS0030: Cannot convert type 'method' to 'C2' // _ = (C2)F; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(C2)F").WithArguments("method", "C2").WithLocation(18, 13) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void UserDefinedConversions_Explicit_03() { var source = @"using System; using System.Linq.Expressions; class C1 { public static explicit operator C1(Delegate d) { Console.WriteLine(""operator C1(Delegate d)""); return new C1(); } } class C2 { public static explicit operator C2(MulticastDelegate d) { Console.WriteLine(""operator C2(MulticastDelegate d)""); return new C2(); } } class C3 { public static explicit operator C3(Expression e) { Console.WriteLine(""operator C3(Expression e)""); return new C3(); } } class C4 { public static explicit operator C4(LambdaExpression e) { Console.WriteLine(""operator C4(LambdaExpression e)""); return new C4(); } } class Program { static int F() => 0; static void Main() { _ = (C1)(() => 1); _ = (C2)(() => 2); _ = (C3)(() => 3); _ = (C4)(() => 4); _ = (C1)F; _ = (C2)F; } }"; var expectedDiagnostics = new[] { // (24,18): error CS1660: Cannot convert lambda expression to type 'C1' because it is not a delegate type // _ = (C1)(() => 1); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "C1").WithLocation(24, 18), // (25,18): error CS1660: Cannot convert lambda expression to type 'C2' because it is not a delegate type // _ = (C2)(() => 2); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 2").WithArguments("lambda expression", "C2").WithLocation(25, 18), // (26,18): error CS1660: Cannot convert lambda expression to type 'C3' because it is not a delegate type // _ = (C3)(() => 3); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 3").WithArguments("lambda expression", "C3").WithLocation(26, 18), // (27,18): error CS1660: Cannot convert lambda expression to type 'C4' because it is not a delegate type // _ = (C4)(() => 4); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 4").WithArguments("lambda expression", "C4").WithLocation(27, 18), // (28,13): error CS0030: Cannot convert type 'method' to 'C1' // _ = (C1)F; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(C1)F").WithArguments("method", "C1").WithLocation(28, 13), // (29,13): error CS0030: Cannot convert type 'method' to 'C2' // _ = (C2)F; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(C2)F").WithArguments("method", "C2").WithLocation(29, 13) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void UserDefinedConversions_Explicit_04() { var source = @"using System; class C<T> { public static explicit operator C<T>(T t) { Console.WriteLine(""operator C<{0}>({0} t)"", typeof(T).FullName); return new C<T>(); } } class Program { static int F() => 0; static void Main() { _ = (C<object>)(() => 1); _ = (C<ICloneable>)(() => 2); _ = (C<object>)F; _ = (C<ICloneable>)F; } }"; var expectedDiagnostics = new[] { // (11,25): error CS1660: Cannot convert lambda expression to type 'C<object>' because it is not a delegate type // _ = (C<object>)(() => 1); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "C<object>").WithLocation(11, 25), // (12,29): error CS1660: Cannot convert lambda expression to type 'C<ICloneable>' because it is not a delegate type // _ = (C<ICloneable>)(() => 2); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 2").WithArguments("lambda expression", "C<System.ICloneable>").WithLocation(12, 29), // (13,13): error CS0030: Cannot convert type 'method' to 'C<object>' // _ = (C<object>)F; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(C<object>)F").WithArguments("method", "C<object>").WithLocation(13, 13), // (14,13): error CS0030: Cannot convert type 'method' to 'C<ICloneable>' // _ = (C<ICloneable>)F; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(C<ICloneable>)F").WithArguments("method", "C<System.ICloneable>").WithLocation(14, 13) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void UserDefinedConversions_Explicit_05() { var source = @"using System; using System.Linq.Expressions; class C<T> { public static explicit operator C<T>(T t) { Console.WriteLine(""operator C<{0}>({0} t)"", typeof(T).FullName); return new C<T>(); } } class Program { static int F() => 0; static void Main() { _ = (C<Delegate>)(() => 1); _ = (C<MulticastDelegate>)(() => 2); _ = (C<Expression>)(() => 3); _ = (C<LambdaExpression>)(() => 4); _ = (C<Delegate>)F; _ = (C<MulticastDelegate>)F; } }"; var expectedDiagnostics = new[] { // (12,27): error CS1660: Cannot convert lambda expression to type 'C<Delegate>' because it is not a delegate type // _ = (C<Delegate>)(() => 1); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "C<System.Delegate>").WithLocation(12, 27), // (13,36): error CS1660: Cannot convert lambda expression to type 'C<MulticastDelegate>' because it is not a delegate type // _ = (C<MulticastDelegate>)(() => 2); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 2").WithArguments("lambda expression", "C<System.MulticastDelegate>").WithLocation(13, 36), // (14,29): error CS1660: Cannot convert lambda expression to type 'C<Expression>' because it is not a delegate type // _ = (C<Expression>)(() => 3); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 3").WithArguments("lambda expression", "C<System.Linq.Expressions.Expression>").WithLocation(14, 29), // (15,35): error CS1660: Cannot convert lambda expression to type 'C<LambdaExpression>' because it is not a delegate type // _ = (C<LambdaExpression>)(() => 4); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 4").WithArguments("lambda expression", "C<System.Linq.Expressions.LambdaExpression>").WithLocation(15, 35), // (16,13): error CS0030: Cannot convert type 'method' to 'C<Delegate>' // _ = (C<Delegate>)F; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(C<Delegate>)F").WithArguments("method", "C<System.Delegate>").WithLocation(16, 13), // (17,13): error CS0030: Cannot convert type 'method' to 'C<MulticastDelegate>' // _ = (C<MulticastDelegate>)F; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(C<MulticastDelegate>)F").WithArguments("method", "C<System.MulticastDelegate>").WithLocation(17, 13) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void TaskRunArgument() { var source = @"using System.Threading.Tasks; class Program { static async Task F() { await Task.Run(() => { }); } }"; var verifier = CompileAndVerify(source, parseOptions: TestOptions.RegularPreview); var method = (MethodSymbol)verifier.TestData.GetMethodsByName()["Program.<>c.<F>b__0_0()"].Method; Assert.Equal("void Program.<>c.<F>b__0_0()", method.ToTestDisplayString()); verifier.VerifyIL("Program.<>c.<F>b__0_0()", @"{ // Code size 1 (0x1) .maxstack 0 IL_0000: ret }"); } } }
1
dotnet/roslyn
56,416
Do not include function type conversions in user-defined conversions
Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
cston
"2021-09-15T18:16:38Z"
"2021-09-24T23:24:46Z"
bb99d0bc89bde01650d2a694d720d600dd952dcb
3913f352cf066fa485869d866e4753fa721cbe93
Do not include function type conversions in user-defined conversions. Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
./src/EditorFeatures/Test/InheritanceMargin/InheritanceMarginTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.InheritanceMargin; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.InheritanceMargin { [Trait(Traits.Feature, Traits.Features.InheritanceMargin)] [UseExportProvider] public class InheritanceMarginTests { private const string SearchAreaTag = "SeachTag"; #region Helpers private static Task VerifyNoItemForDocumentAsync(string markup, string languageName) => VerifyInSingleDocumentAsync(markup, languageName); private static Task VerifyInSingleDocumentAsync( string markup, string languageName, params TestInheritanceMemberItem[] memberItems) { markup = @$"<![CDATA[ {markup}]]>"; var workspaceFile = $@" <Workspace> <Project Language=""{languageName}"" CommonReferences=""true""> <Document> {markup} </Document> </Project> </Workspace>"; var cancellationToken = CancellationToken.None; using var testWorkspace = TestWorkspace.Create( workspaceFile, composition: EditorTestCompositions.EditorFeatures); var testHostDocument = testWorkspace.Documents[0]; return VerifyTestMemberInDocumentAsync(testWorkspace, testHostDocument, memberItems, cancellationToken); } private static async Task VerifyTestMemberInDocumentAsync( TestWorkspace testWorkspace, TestHostDocument testHostDocument, TestInheritanceMemberItem[] memberItems, CancellationToken cancellationToken) { var document = testWorkspace.CurrentSolution.GetRequiredDocument(testHostDocument.Id); var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var searchingSpan = root.Span; // Look for the search span, if not found, then pass the whole document span to the service. if (testHostDocument.AnnotatedSpans.TryGetValue(SearchAreaTag, out var spans) && spans.IsSingle()) { searchingSpan = spans[0]; } var service = document.GetRequiredLanguageService<IInheritanceMarginService>(); var actualItems = await service.GetInheritanceMemberItemsAsync( document, searchingSpan, cancellationToken).ConfigureAwait(false); var sortedActualItems = actualItems.OrderBy(item => item.LineNumber).ToImmutableArray(); var sortedExpectedItems = memberItems.OrderBy(item => item.LineNumber).ToImmutableArray(); Assert.Equal(sortedExpectedItems.Length, sortedActualItems.Length); for (var i = 0; i < sortedActualItems.Length; i++) { await VerifyInheritanceMemberAsync(testWorkspace, sortedExpectedItems[i], sortedActualItems[i]); } } private static async Task VerifyInheritanceMemberAsync(TestWorkspace testWorkspace, TestInheritanceMemberItem expectedItem, InheritanceMarginItem actualItem) { Assert.Equal(expectedItem.LineNumber, actualItem.LineNumber); Assert.Equal(expectedItem.MemberName, actualItem.DisplayTexts.JoinText()); Assert.Equal(expectedItem.Targets.Length, actualItem.TargetItems.Length); var expectedTargets = expectedItem.Targets .Select(info => TestInheritanceTargetItem.Create(info, testWorkspace)) .OrderBy(target => target.TargetSymbolName) .ToImmutableArray(); var sortedActualTargets = actualItem.TargetItems.OrderBy(target => target.DefinitionItem.DisplayParts.JoinText()) .ToImmutableArray(); for (var i = 0; i < expectedTargets.Length; i++) { await VerifyInheritanceTargetAsync(expectedTargets[i], sortedActualTargets[i]); } } private static async Task VerifyInheritanceTargetAsync(TestInheritanceTargetItem expectedTarget, InheritanceTargetItem actualTarget) { Assert.Equal(expectedTarget.TargetSymbolName, actualTarget.DefinitionItem.DisplayParts.JoinText()); Assert.Equal(expectedTarget.RelationshipToMember, actualTarget.RelationToMember); if (expectedTarget.IsInMetadata) { Assert.True(actualTarget.DefinitionItem.Properties.ContainsKey("MetadataSymbolKey")); Assert.True(actualTarget.DefinitionItem.SourceSpans.IsEmpty); } else { var actualDocumentSpans = actualTarget.DefinitionItem.SourceSpans.OrderBy(documentSpan => documentSpan.SourceSpan.Start).ToImmutableArray(); var expectedDocumentSpans = expectedTarget.DocumentSpans.OrderBy(documentSpan => documentSpan.SourceSpan.Start).ToImmutableArray(); Assert.Equal(expectedDocumentSpans.Length, actualDocumentSpans.Length); for (var i = 0; i < actualDocumentSpans.Length; i++) { var docSpan = await actualDocumentSpans[i].TryRehydrateAsync(CancellationToken.None); Assert.Equal(expectedDocumentSpans[i].SourceSpan, docSpan.Value.SourceSpan); Assert.Equal(expectedDocumentSpans[i].Document.FilePath, docSpan.Value.Document.FilePath); } } } /// <summary> /// Project of markup1 is referencing project of markup2 /// </summary> private static async Task VerifyInDifferentProjectsAsync( (string markupInProject1, string languageName) markup1, (string markupInProject2, string languageName) markup2, TestInheritanceMemberItem[] memberItemsInMarkup1, TestInheritanceMemberItem[] memberItemsInMarkup2) { var workspaceFile = $@" <Workspace> <Project Language=""{markup1.languageName}"" AssemblyName=""Assembly1"" CommonReferences=""true""> <ProjectReference>Assembly2</ProjectReference> <Document> <![CDATA[ {markup1.markupInProject1}]]> </Document> </Project> <Project Language=""{markup2.languageName}"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> <![CDATA[ {markup2.markupInProject2}]]> </Document> </Project> </Workspace>"; var cancellationToken = CancellationToken.None; using var testWorkspace = TestWorkspace.Create( workspaceFile, composition: EditorTestCompositions.EditorFeatures); var testHostDocument1 = testWorkspace.Documents.Single(doc => doc.Project.AssemblyName.Equals("Assembly1")); var testHostDocument2 = testWorkspace.Documents.Single(doc => doc.Project.AssemblyName.Equals("Assembly2")); await VerifyTestMemberInDocumentAsync(testWorkspace, testHostDocument1, memberItemsInMarkup1, cancellationToken).ConfigureAwait(false); await VerifyTestMemberInDocumentAsync(testWorkspace, testHostDocument2, memberItemsInMarkup2, cancellationToken).ConfigureAwait(false); } private class TestInheritanceMemberItem { public readonly int LineNumber; public readonly string MemberName; public readonly ImmutableArray<TargetInfo> Targets; public TestInheritanceMemberItem( int lineNumber, string memberName, ImmutableArray<TargetInfo> targets) { LineNumber = lineNumber; MemberName = memberName; Targets = targets; } } private class TargetInfo { public readonly string TargetSymbolDisplayName; public readonly string? LocationTag; public readonly InheritanceRelationship Relationship; public readonly bool InMetadata; public TargetInfo( string targetSymbolDisplayName, string locationTag, InheritanceRelationship relationship) { TargetSymbolDisplayName = targetSymbolDisplayName; LocationTag = locationTag; Relationship = relationship; InMetadata = false; } public TargetInfo( string targetSymbolDisplayName, InheritanceRelationship relationship, bool inMetadata) { TargetSymbolDisplayName = targetSymbolDisplayName; Relationship = relationship; InMetadata = inMetadata; LocationTag = null; } } private class TestInheritanceTargetItem { public readonly string TargetSymbolName; public readonly InheritanceRelationship RelationshipToMember; public readonly ImmutableArray<DocumentSpan> DocumentSpans; public readonly bool IsInMetadata; public TestInheritanceTargetItem( string targetSymbolName, InheritanceRelationship relationshipToMember, ImmutableArray<DocumentSpan> documentSpans, bool isInMetadata) { TargetSymbolName = targetSymbolName; RelationshipToMember = relationshipToMember; DocumentSpans = documentSpans; IsInMetadata = isInMetadata; } public static TestInheritanceTargetItem Create( TargetInfo targetInfo, TestWorkspace testWorkspace) { if (targetInfo.InMetadata) { return new TestInheritanceTargetItem( targetInfo.TargetSymbolDisplayName, targetInfo.Relationship, ImmutableArray<DocumentSpan>.Empty, isInMetadata: true); } else { using var _ = ArrayBuilder<DocumentSpan>.GetInstance(out var builder); // If the target is not in metadata, there must be a location tag to give the span! Assert.True(targetInfo.LocationTag != null); foreach (var testHostDocument in testWorkspace.Documents) { if (targetInfo.LocationTag != null) { var annotatedSpans = testHostDocument.AnnotatedSpans; if (annotatedSpans.TryGetValue(targetInfo.LocationTag, out var spans)) { var document = testWorkspace.CurrentSolution.GetRequiredDocument(testHostDocument.Id); builder.AddRange(spans.Select(span => new DocumentSpan(document, span))); } } } return new TestInheritanceTargetItem( targetInfo.TargetSymbolDisplayName, targetInfo.Relationship, builder.ToImmutable(), isInMetadata: false); } } } #endregion #region TestsForCSharp [Fact] public Task TestCSharpClassWithErrorBaseType() { var markup = @" public class Bar : SomethingUnknown { }"; return VerifyNoItemForDocumentAsync(markup, LanguageNames.CSharp); } [Fact] public Task TestCSharpReferencingMetadata() { var markup = @" using System.Collections; public class Bar : IEnumerable { public IEnumerator GetEnumerator () { return null }; }"; var itemForBar = new TestInheritanceMemberItem( lineNumber: 3, memberName: "class Bar", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "interface IEnumerable", relationship: InheritanceRelationship.ImplementedInterface, inMetadata: true))); var itemForGetEnumerator = new TestInheritanceMemberItem( lineNumber: 5, memberName: "IEnumerator Bar.GetEnumerator()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "IEnumerator IEnumerable.GetEnumerator()", relationship: InheritanceRelationship.ImplementedMember, inMetadata: true))); return VerifyInSingleDocumentAsync(markup, LanguageNames.CSharp, itemForBar, itemForGetEnumerator); } [Fact] public Task TestCSharpClassImplementingInterface() { var markup = @" interface {|target1:IBar|} { } public class {|target2:Bar|} : IBar { } "; var itemOnLine2 = new TestInheritanceMemberItem( lineNumber: 2, memberName: "interface IBar", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "class Bar", locationTag: "target2", relationship: InheritanceRelationship.ImplementingType))); var itemOnLine3 = new TestInheritanceMemberItem( lineNumber: 3, memberName: "class Bar", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "interface IBar", locationTag: "target1", relationship: InheritanceRelationship.ImplementedInterface))); return VerifyInSingleDocumentAsync( markup, LanguageNames.CSharp, itemOnLine2, itemOnLine3); } [Fact] public Task TestCSharpInterfaceImplementingInterface() { var markup = @" interface {|target1:IBar|} { } interface {|target2:IBar2|} : IBar { } "; var itemOnLine2 = new TestInheritanceMemberItem( lineNumber: 2, memberName: "interface IBar", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "interface IBar2", locationTag: "target2", relationship: InheritanceRelationship.ImplementingType)) ); var itemOnLine3 = new TestInheritanceMemberItem( lineNumber: 3, memberName: "interface IBar2", targets: ImmutableArray<TargetInfo>.Empty .Add(new TargetInfo( targetSymbolDisplayName: "interface IBar", locationTag: "target1", relationship: InheritanceRelationship.InheritedInterface)) ); return VerifyInSingleDocumentAsync( markup, LanguageNames.CSharp, itemOnLine2, itemOnLine3); } [Fact] public Task TestCSharpClassInheritsClass() { var markup = @" class {|target2:A|} { } class {|target1:B|} : A { } "; var itemOnLine2 = new TestInheritanceMemberItem( lineNumber: 2, memberName: "class A", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "class B", locationTag: "target1", relationship: InheritanceRelationship.DerivedType)) ); var itemOnLine3 = new TestInheritanceMemberItem( lineNumber: 3, memberName: "class B", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "class A", locationTag: "target2", relationship: InheritanceRelationship.BaseType)) ); return VerifyInSingleDocumentAsync( markup, LanguageNames.CSharp, itemOnLine2, itemOnLine3); } [Theory] [InlineData("class")] [InlineData("struct")] [InlineData("enum")] [InlineData("interface")] public Task TestCSharpTypeWithoutBaseType(string typeName) { var markup = $@" public {typeName} Bar {{ }}"; return VerifyNoItemForDocumentAsync(markup, LanguageNames.CSharp); } [Theory] [InlineData("public Bar() { }")] [InlineData("public static void Bar3() { }")] [InlineData("public static void ~Bar() { }")] [InlineData("public static Bar operator +(Bar a, Bar b) => new Bar();")] public Task TestCSharpSpecialMember(string memberDeclaration) { var markup = $@" public abstract class {{|target1:Bar1|}} {{}} public class Bar : Bar1 {{ {{|{SearchAreaTag}:{memberDeclaration}|}} }}"; return VerifyInSingleDocumentAsync( markup, LanguageNames.CSharp, new TestInheritanceMemberItem( lineNumber: 4, memberName: "class Bar", targets: ImmutableArray.Create( new TargetInfo( targetSymbolDisplayName: "class Bar1", locationTag: "target1", relationship: InheritanceRelationship.BaseType)))); } [Fact] public Task TestCSharpEventDeclaration() { var markup = @" using System; interface {|target2:IBar|} { event EventHandler {|target4:e|}; } public class {|target1:Bar|} : IBar { public event EventHandler {|target3:e|} { add {} remove {} } }"; var itemForIBar = new TestInheritanceMemberItem( lineNumber: 3, memberName: "interface IBar", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "class Bar", locationTag: "target1", relationship: InheritanceRelationship.ImplementingType))); var itemForBar = new TestInheritanceMemberItem( lineNumber: 7, memberName: "class Bar", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "interface IBar", locationTag: "target2", relationship: InheritanceRelationship.ImplementedInterface))); var itemForEventInInterface = new TestInheritanceMemberItem( lineNumber: 5, memberName: "event EventHandler IBar.e", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "event EventHandler Bar.e", locationTag: "target3", relationship: InheritanceRelationship.ImplementingMember))); var itemForEventInClass = new TestInheritanceMemberItem( lineNumber: 9, memberName: "event EventHandler Bar.e", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "event EventHandler IBar.e", locationTag: "target4", relationship: InheritanceRelationship.ImplementedMember))); return VerifyInSingleDocumentAsync( markup, LanguageNames.CSharp, itemForIBar, itemForBar, itemForEventInInterface, itemForEventInClass); } [Fact] public Task TestCSharpEventFieldDeclarations() { var markup = @"using System; interface {|target2:IBar|} { event EventHandler {|target5:e1|}, {|target6:e2|}; } public class {|target1:Bar|} : IBar { public event EventHandler {|target3:e1|}, {|target4:e2|}; }"; var itemForIBar = new TestInheritanceMemberItem( lineNumber: 2, memberName: "interface IBar", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "class Bar", locationTag: "target1", relationship: InheritanceRelationship.ImplementingType))); var itemForBar = new TestInheritanceMemberItem( lineNumber: 6, memberName: "class Bar", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "interface IBar", locationTag: "target2", relationship: InheritanceRelationship.ImplementedInterface))); var itemForE1InInterface = new TestInheritanceMemberItem( lineNumber: 4, memberName: "event EventHandler IBar.e1", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "event EventHandler Bar.e1", locationTag: "target3", relationship: InheritanceRelationship.ImplementingMember))); var itemForE2InInterface = new TestInheritanceMemberItem( lineNumber: 4, memberName: "event EventHandler IBar.e2", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "event EventHandler Bar.e2", locationTag: "target4", relationship: InheritanceRelationship.ImplementingMember))); var itemForE1InClass = new TestInheritanceMemberItem( lineNumber: 8, memberName: "event EventHandler Bar.e1", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "event EventHandler IBar.e1", locationTag: "target5", relationship: InheritanceRelationship.ImplementedMember))); var itemForE2InClass = new TestInheritanceMemberItem( lineNumber: 8, memberName: "event EventHandler Bar.e2", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "event EventHandler IBar.e2", locationTag: "target6", relationship: InheritanceRelationship.ImplementedMember))); return VerifyInSingleDocumentAsync( markup, LanguageNames.CSharp, itemForIBar, itemForBar, itemForE1InInterface, itemForE2InInterface, itemForE1InClass, itemForE2InClass); } [Fact] public Task TestCSharpInterfaceMembers() { var markup = @"using System; interface {|target1:IBar|} { void {|target4:Foo|}(); int {|target6:Poo|} { get; set; } event EventHandler {|target8:Eoo|}; int {|target9:this|}[int i] { get; set; } } public class {|target2:Bar|} : IBar { public void {|target3:Foo|}() { } public int {|target5:Poo|} { get; set; } public event EventHandler {|target7:Eoo|}; public int {|target10:this|}[int i] { get => 1; set { } } }"; var itemForEooInClass = new TestInheritanceMemberItem( lineNumber: 13, memberName: "event EventHandler Bar.Eoo", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "event EventHandler IBar.Eoo", locationTag: "target8", relationship: InheritanceRelationship.ImplementedMember)) ); var itemForEooInInterface = new TestInheritanceMemberItem( lineNumber: 6, memberName: "event EventHandler IBar.Eoo", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "event EventHandler Bar.Eoo", locationTag: "target7", relationship: InheritanceRelationship.ImplementingMember)) ); var itemForPooInInterface = new TestInheritanceMemberItem( lineNumber: 5, memberName: "int IBar.Poo { get; set; }", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "int Bar.Poo { get; set; }", locationTag: "target5", relationship: InheritanceRelationship.ImplementingMember)) ); var itemForPooInClass = new TestInheritanceMemberItem( lineNumber: 12, memberName: "int Bar.Poo { get; set; }", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "int IBar.Poo { get; set; }", locationTag: "target6", relationship: InheritanceRelationship.ImplementedMember)) ); var itemForFooInInterface = new TestInheritanceMemberItem( lineNumber: 4, memberName: "void IBar.Foo()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "void Bar.Foo()", locationTag: "target3", relationship: InheritanceRelationship.ImplementingMember)) ); var itemForFooInClass = new TestInheritanceMemberItem( lineNumber: 11, memberName: "void Bar.Foo()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "void IBar.Foo()", locationTag: "target4", relationship: InheritanceRelationship.ImplementedMember)) ); var itemForIBar = new TestInheritanceMemberItem( lineNumber: 2, memberName: "interface IBar", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "class Bar", locationTag: "target2", relationship: InheritanceRelationship.ImplementingType)) ); var itemForBar = new TestInheritanceMemberItem( lineNumber: 9, memberName: "class Bar", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "interface IBar", locationTag: "target1", relationship: InheritanceRelationship.ImplementedInterface)) ); var itemForIndexerInClass = new TestInheritanceMemberItem( lineNumber: 14, memberName: "int Bar.this[int] { get; set; }", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "int IBar.this[int] { get; set; }", locationTag: "target9", relationship: InheritanceRelationship.ImplementedMember)) ); var itemForIndexerInInterface = new TestInheritanceMemberItem( lineNumber: 7, memberName: "int IBar.this[int] { get; set; }", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "int Bar.this[int] { get; set; }", locationTag: "target10", relationship: InheritanceRelationship.ImplementingMember)) ); return VerifyInSingleDocumentAsync( markup, LanguageNames.CSharp, itemForEooInClass, itemForEooInInterface, itemForPooInInterface, itemForPooInClass, itemForFooInInterface, itemForFooInClass, itemForIBar, itemForBar, itemForIndexerInInterface, itemForIndexerInClass); } [Theory] [InlineData("abstract")] [InlineData("virtual")] public Task TestCSharpAbstractClassMembers(string modifier) { var markup = $@"using System; public abstract class {{|target2:Bar|}} {{ public {modifier} void {{|target4:Foo|}}(); public {modifier} int {{|target6:Poo|}} {{ get; set; }} public {modifier} event EventHandler {{|target8:Eoo|}}; }} public class {{|target1:Bar2|}} : Bar {{ public override void {{|target3:Foo|}}() {{ }} public override int {{|target5:Poo|}} {{ get; set; }} public override event EventHandler {{|target7:Eoo|}}; }} "; var itemForEooInClass = new TestInheritanceMemberItem( lineNumber: 12, memberName: "override event EventHandler Bar2.Eoo", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: $"{modifier} event EventHandler Bar.Eoo", locationTag: "target8", relationship: InheritanceRelationship.OverriddenMember))); var itemForEooInAbstractClass = new TestInheritanceMemberItem( lineNumber: 6, memberName: $"{modifier} event EventHandler Bar.Eoo", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "override event EventHandler Bar2.Eoo", locationTag: "target7", relationship: InheritanceRelationship.OverridingMember))); var itemForPooInClass = new TestInheritanceMemberItem( lineNumber: 11, memberName: "override int Bar2.Poo { get; set; }", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: $"{modifier} int Bar.Poo {{ get; set; }}", locationTag: "target6", relationship: InheritanceRelationship.OverriddenMember))); var itemForPooInAbstractClass = new TestInheritanceMemberItem( lineNumber: 5, memberName: $"{modifier} int Bar.Poo {{ get; set; }}", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "override int Bar2.Poo { get; set; }", locationTag: "target5", relationship: InheritanceRelationship.OverridingMember))); var itemForFooInAbstractClass = new TestInheritanceMemberItem( lineNumber: 4, memberName: $"{modifier} void Bar.Foo()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "override void Bar2.Foo()", locationTag: "target3", relationship: InheritanceRelationship.OverridingMember))); var itemForFooInClass = new TestInheritanceMemberItem( lineNumber: 10, memberName: "override void Bar2.Foo()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: $"{modifier} void Bar.Foo()", locationTag: "target4", relationship: InheritanceRelationship.OverriddenMember))); var itemForBar = new TestInheritanceMemberItem( lineNumber: 2, memberName: "class Bar", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "class Bar2", locationTag: "target1", relationship: InheritanceRelationship.DerivedType))); var itemForBar2 = new TestInheritanceMemberItem( lineNumber: 8, memberName: "class Bar2", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "class Bar", locationTag: "target2", relationship: InheritanceRelationship.BaseType))); return VerifyInSingleDocumentAsync( markup, LanguageNames.CSharp, itemForBar, itemForBar2, itemForFooInAbstractClass, itemForFooInClass, itemForPooInClass, itemForPooInAbstractClass, itemForEooInClass, itemForEooInAbstractClass); } [Theory] [CombinatorialData] public Task TestCSharpOverrideMemberCanFindImplementingInterface(bool testDuplicate) { var markup1 = @"using System; public interface {|target4:IBar|} { void {|target6:Foo|}(); } public class {|target1:Bar1|} : IBar { public virtual void {|target2:Foo|}() { } } public class {|target5:Bar2|} : Bar1 { public override void {|target3:Foo|}() { } }"; var markup2 = @"using System; public interface {|target4:IBar|} { void {|target6:Foo|}(); } public class {|target1:Bar1|} : IBar { public virtual void {|target2:Foo|}() { } } public class {|target5:Bar2|} : Bar1, IBar { public override void {|target3:Foo|}() { } }"; var itemForIBar = new TestInheritanceMemberItem( lineNumber: 2, memberName: "interface IBar", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "class Bar1", locationTag: "target1", relationship: InheritanceRelationship.ImplementingType), new TargetInfo( targetSymbolDisplayName: "class Bar2", locationTag: "target5", relationship: InheritanceRelationship.ImplementingType))); var itemForFooInIBar = new TestInheritanceMemberItem( lineNumber: 4, memberName: "void IBar.Foo()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "virtual void Bar1.Foo()", locationTag: "target2", relationship: InheritanceRelationship.ImplementingMember), new TargetInfo( targetSymbolDisplayName: "override void Bar2.Foo()", locationTag: "target3", relationship: InheritanceRelationship.ImplementingMember))); var itemForBar1 = new TestInheritanceMemberItem( lineNumber: 6, memberName: "class Bar1", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "interface IBar", locationTag: "target4", relationship: InheritanceRelationship.ImplementedInterface), new TargetInfo( targetSymbolDisplayName: "class Bar2", locationTag: "target5", relationship: InheritanceRelationship.DerivedType))); var itemForFooInBar1 = new TestInheritanceMemberItem( lineNumber: 8, memberName: "virtual void Bar1.Foo()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "void IBar.Foo()", locationTag: "target6", relationship: InheritanceRelationship.ImplementedMember), new TargetInfo( targetSymbolDisplayName: "override void Bar2.Foo()", locationTag: "target3", relationship: InheritanceRelationship.OverridingMember))); var itemForBar2 = new TestInheritanceMemberItem( lineNumber: 10, memberName: "class Bar2", targets: ImmutableArray.Create( new TargetInfo( targetSymbolDisplayName: "class Bar1", locationTag: "target1", relationship: InheritanceRelationship.BaseType), new TargetInfo( targetSymbolDisplayName: "interface IBar", locationTag: "target4", relationship: InheritanceRelationship.ImplementedInterface))); var itemForFooInBar2 = new TestInheritanceMemberItem( lineNumber: 12, memberName: "override void Bar2.Foo()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "void IBar.Foo()", locationTag: "target6", relationship: InheritanceRelationship.ImplementedMember), new TargetInfo( targetSymbolDisplayName: "virtual void Bar1.Foo()", locationTag: "target2", relationship: InheritanceRelationship.OverriddenMember))); return VerifyInSingleDocumentAsync( testDuplicate ? markup2 : markup1, LanguageNames.CSharp, itemForIBar, itemForFooInIBar, itemForBar1, itemForFooInBar1, itemForBar2, itemForFooInBar2); } [Fact] public Task TestCSharpFindGenericsBaseType() { var markup = @" public interface {|target2:IBar|}<T> { void {|target4:Foo|}(); } public class {|target1:Bar2|} : IBar<int>, IBar<string> { public void {|target3:Foo|}(); }"; var itemForIBar = new TestInheritanceMemberItem( lineNumber: 2, memberName: "interface IBar<T>", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "class Bar2", locationTag: "target1", relationship: InheritanceRelationship.ImplementingType))); var itemForFooInIBar = new TestInheritanceMemberItem( lineNumber: 4, memberName: "void IBar<T>.Foo()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "void Bar2.Foo()", locationTag: "target3", relationship: InheritanceRelationship.ImplementingMember))); // Only have one IBar<T> item var itemForBar2 = new TestInheritanceMemberItem( lineNumber: 7, memberName: "class Bar2", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "interface IBar<T>", locationTag: "target2", relationship: InheritanceRelationship.ImplementedInterface))); // Only have one IBar<T>.Foo item var itemForFooInBar2 = new TestInheritanceMemberItem( lineNumber: 9, memberName: "void Bar2.Foo()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "void IBar<T>.Foo()", locationTag: "target4", relationship: InheritanceRelationship.ImplementedMember))); return VerifyInSingleDocumentAsync( markup, LanguageNames.CSharp, itemForIBar, itemForFooInIBar, itemForBar2, itemForFooInBar2); } [Fact] public Task TestCSharpExplicitInterfaceImplementation() { var markup = @" interface {|target2:IBar|}<T> { void {|target3:Foo|}(T t); } abstract class {|target1:AbsBar|} : IBar<int> { void IBar<int>.{|target4:Foo|}(int t) { throw new System.NotImplementedException(); } }"; var itemForIBar = new TestInheritanceMemberItem( lineNumber: 2, memberName: "interface IBar<T>", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "class AbsBar", locationTag: "target1", relationship: InheritanceRelationship.ImplementingType))); var itemForFooInIBar = new TestInheritanceMemberItem( lineNumber: 4, memberName: "void IBar<T>.Foo(T)", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "void AbsBar.IBar<int>.Foo(int)", locationTag: "target4", relationship: InheritanceRelationship.ImplementingMember))); var itemForAbsBar = new TestInheritanceMemberItem( lineNumber: 7, memberName: "class AbsBar", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "interface IBar<T>", locationTag: "target2", relationship: InheritanceRelationship.ImplementedInterface))); var itemForFooInAbsBar = new TestInheritanceMemberItem( lineNumber: 9, memberName: "void AbsBar.IBar<int>.Foo(int)", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "void IBar<T>.Foo(T)", locationTag: "target3", relationship: InheritanceRelationship.ImplementedMember) )); return VerifyInSingleDocumentAsync( markup, LanguageNames.CSharp, itemForIBar, itemForFooInIBar, itemForAbsBar, itemForFooInAbsBar); } [Fact] public Task TestStaticAbstractMemberInterface() { var markup = @" interface {|target5:I1|}<T> where T : I1<T> { static abstract void {|target4:M1|}(); static abstract int {|target7:P1|} { get; set; } static abstract event EventHandler {|target9:e1|}; static abstract int operator {|target11:+|}(T i1); static abstract implicit operator {|target12:int|}(T i1); } public class {|target1:Class1|} : I1<Class1> { public static void {|target2:M1|}() {} public static int {|target6:P1|} { get => 1; set { } } public static event EventHandler {|target8:e1|}; public static int operator {|target10:+|}(Class1 i) => 1; public static implicit operator {|target13:int|}(Class1 i) => 0; }"; var itemForI1 = new TestInheritanceMemberItem( lineNumber: 2, memberName: "interface I1<T>", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "class Class1", locationTag: "target1", relationship: InheritanceRelationship.ImplementingType))); var itemForM1InI1 = new TestInheritanceMemberItem( lineNumber: 4, memberName: "void I1<T>.M1()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "static void Class1.M1()", locationTag: "target2", relationship: InheritanceRelationship.ImplementingMember))); var itemForAbsClass1 = new TestInheritanceMemberItem( lineNumber: 11, memberName: "class Class1", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "interface I1<T>", locationTag: "target5", relationship: InheritanceRelationship.ImplementedInterface))); var itemForM1InClass1 = new TestInheritanceMemberItem( lineNumber: 13, memberName: "static void Class1.M1()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "void I1<T>.M1()", locationTag: "target4", relationship: InheritanceRelationship.ImplementedMember))); var itemForP1InI1 = new TestInheritanceMemberItem( lineNumber: 5, memberName: "int I1<T>.P1 { get; set; }", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "static int Class1.P1 { get; set; }", locationTag: "target6", relationship: InheritanceRelationship.ImplementingMember))); var itemForP1InClass1 = new TestInheritanceMemberItem( lineNumber: 14, memberName: "static int Class1.P1 { get; set; }", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "int I1<T>.P1 { get; set; }", locationTag: "target7", relationship: InheritanceRelationship.ImplementedMember))); var itemForE1InI1 = new TestInheritanceMemberItem( lineNumber: 6, memberName: "event EventHandler I1<T>.e1", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "static event EventHandler Class1.e1", locationTag: "target8", relationship: InheritanceRelationship.ImplementingMember))); var itemForE1InClass1 = new TestInheritanceMemberItem( lineNumber: 15, memberName: "static event EventHandler Class1.e1", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "event EventHandler I1<T>.e1", locationTag: "target9", relationship: InheritanceRelationship.ImplementedMember))); var itemForPlusOperatorInI1 = new TestInheritanceMemberItem( lineNumber: 7, memberName: "int I1<T>.operator +(T)", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "static int Class1.operator +(Class1)", locationTag: "target10", relationship: InheritanceRelationship.ImplementingMember))); var itemForPlusOperatorInClass1 = new TestInheritanceMemberItem( lineNumber: 16, memberName: "static int Class1.operator +(Class1)", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "int I1<T>.operator +(T)", locationTag: "target11", relationship: InheritanceRelationship.ImplementedMember))); var itemForIntOperatorInI1 = new TestInheritanceMemberItem( lineNumber: 8, memberName: "I1<T>.implicit operator int(T)", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "static Class1.implicit operator int(Class1)", locationTag: "target13", relationship: InheritanceRelationship.ImplementingMember))); var itemForIntOperatorInClass1 = new TestInheritanceMemberItem( lineNumber: 17, memberName: "static Class1.implicit operator int(Class1)", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "I1<T>.implicit operator int(T)", locationTag: "target12", relationship: InheritanceRelationship.ImplementedMember))); return VerifyInSingleDocumentAsync( markup, LanguageNames.CSharp, itemForI1, itemForAbsClass1, itemForM1InI1, itemForM1InClass1, itemForP1InI1, itemForP1InClass1, itemForE1InI1, itemForE1InClass1, itemForPlusOperatorInI1, itemForPlusOperatorInClass1, itemForIntOperatorInI1, itemForIntOperatorInClass1); } #endregion #region TestsForVisualBasic [Fact] public Task TestVisualBasicWithErrorBaseType() { var markup = @" Namespace MyNamespace Public Class Bar Implements SomethingNotExist End Class End Namespace"; return VerifyNoItemForDocumentAsync(markup, LanguageNames.VisualBasic); } [Fact] public Task TestVisualBasicReferencingMetadata() { var markup = @" Namespace MyNamespace Public Class Bar Implements System.Collections.IEnumerable Public Function GetEnumerator() As System.Collections.IEnumerator Implements System.Collections.IEnumerable.GetEnumerator Throw New NotImplementedException() End Function End Class End Namespace"; var itemForBar = new TestInheritanceMemberItem( lineNumber: 3, memberName: "Class Bar", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Interface IEnumerable", relationship: InheritanceRelationship.ImplementedInterface, inMetadata: true))); var itemForGetEnumerator = new TestInheritanceMemberItem( lineNumber: 5, memberName: "Function Bar.GetEnumerator() As IEnumerator", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Function IEnumerable.GetEnumerator() As IEnumerator", relationship: InheritanceRelationship.ImplementedMember, inMetadata: true))); return VerifyInSingleDocumentAsync(markup, LanguageNames.VisualBasic, itemForBar, itemForGetEnumerator); } [Fact] public Task TestVisualBasicClassImplementingInterface() { var markup = @" Interface {|target2:IBar|} End Interface Class {|target1:Bar|} Implements IBar End Class"; var itemForIBar = new TestInheritanceMemberItem( lineNumber: 2, memberName: "Interface IBar", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Class Bar", locationTag: "target1", relationship: InheritanceRelationship.ImplementingType))); var itemForBar = new TestInheritanceMemberItem( lineNumber: 4, memberName: "Class Bar", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Interface IBar", locationTag: "target2", relationship: InheritanceRelationship.ImplementedInterface))); return VerifyInSingleDocumentAsync( markup, LanguageNames.VisualBasic, itemForIBar, itemForBar); } [Fact] public Task TestVisualBasicInterfaceImplementingInterface() { var markup = @" Interface {|target2:IBar2|} End Interface Interface {|target1:IBar|} Inherits IBar2 End Interface"; var itemForIBar2 = new TestInheritanceMemberItem( lineNumber: 2, memberName: "Interface IBar2", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Interface IBar", locationTag: "target1", relationship: InheritanceRelationship.ImplementingType))); var itemForIBar = new TestInheritanceMemberItem( lineNumber: 4, memberName: "Interface IBar", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Interface IBar2", locationTag: "target2", relationship: InheritanceRelationship.InheritedInterface))); return VerifyInSingleDocumentAsync(markup, LanguageNames.VisualBasic, itemForIBar2, itemForIBar); } [Fact] public Task TestVisualBasicClassInheritsClass() { var markup = @" Class {|target2:Bar2|} End Class Class {|target1:Bar|} Inherits Bar2 End Class"; var itemForBar2 = new TestInheritanceMemberItem( lineNumber: 2, memberName: "Class Bar2", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Class Bar", locationTag: "target1", relationship: InheritanceRelationship.DerivedType))); var itemForBar = new TestInheritanceMemberItem( lineNumber: 4, memberName: "Class Bar", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Class Bar2", locationTag: "target2", relationship: InheritanceRelationship.BaseType))); return VerifyInSingleDocumentAsync(markup, LanguageNames.VisualBasic, itemForBar2, itemForBar); } [Theory] [InlineData("Class")] [InlineData("Structure")] [InlineData("Enum")] [InlineData("Interface")] public Task TestVisualBasicTypeWithoutBaseType(string typeName) { var markup = $@" {typeName} Bar End {typeName}"; return VerifyNoItemForDocumentAsync(markup, LanguageNames.VisualBasic); } [Fact] public Task TestVisualBasicMetadataInterface() { var markup = @" Imports System.Collections Class Bar Implements IEnumerable End Class"; return VerifyInSingleDocumentAsync( markup, LanguageNames.VisualBasic, new TestInheritanceMemberItem( lineNumber: 3, memberName: "Class Bar", targets: ImmutableArray.Create( new TargetInfo( targetSymbolDisplayName: "Interface IEnumerable", relationship: InheritanceRelationship.ImplementedInterface, inMetadata: true)))); } [Fact] public Task TestVisualBasicEventStatement() { var markup = @" Interface {|target2:IBar|} Event {|target4:e|} As EventHandler End Interface Class {|target1:Bar|} Implements IBar Public Event {|target3:e|} As EventHandler Implements IBar.e End Class"; var itemForIBar = new TestInheritanceMemberItem( lineNumber: 2, memberName: "Interface IBar", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Class Bar", locationTag: "target1", relationship: InheritanceRelationship.ImplementingType))); var itemForBar = new TestInheritanceMemberItem( lineNumber: 5, memberName: "Class Bar", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Interface IBar", locationTag: "target2", relationship: InheritanceRelationship.ImplementedInterface))); var itemForEventInInterface = new TestInheritanceMemberItem( lineNumber: 3, memberName: "Event IBar.e As EventHandler", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Event Bar.e As EventHandler", locationTag: "target3", relationship: InheritanceRelationship.ImplementingMember))); var itemForEventInClass = new TestInheritanceMemberItem( lineNumber: 7, memberName: "Event Bar.e As EventHandler", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Event IBar.e As EventHandler", locationTag: "target4", relationship: InheritanceRelationship.ImplementedMember))); return VerifyInSingleDocumentAsync( markup, LanguageNames.VisualBasic, itemForIBar, itemForBar, itemForEventInInterface, itemForEventInClass); } [Fact] public Task TestVisualBasicEventBlock() { var markup = @" Interface {|target2:IBar|} Event {|target4:e|} As EventHandler End Interface Class {|target1:Bar|} Implements IBar Public Custom Event {|target3:e|} As EventHandler Implements IBar.e End Event End Class"; var itemForIBar = new TestInheritanceMemberItem( lineNumber: 2, memberName: "Interface IBar", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Class Bar", locationTag: "target1", relationship: InheritanceRelationship.ImplementingType))); var itemForBar = new TestInheritanceMemberItem( lineNumber: 5, memberName: "Class Bar", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Interface IBar", locationTag: "target2", relationship: InheritanceRelationship.ImplementedInterface))); var itemForEventInInterface = new TestInheritanceMemberItem( lineNumber: 3, memberName: "Event IBar.e As EventHandler", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Event Bar.e As EventHandler", locationTag: "target3", relationship: InheritanceRelationship.ImplementingMember))); var itemForEventInClass = new TestInheritanceMemberItem( lineNumber: 7, memberName: "Event Bar.e As EventHandler", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Event IBar.e As EventHandler", locationTag: "target4", relationship: InheritanceRelationship.ImplementedMember))); return VerifyInSingleDocumentAsync( markup, LanguageNames.VisualBasic, itemForIBar, itemForBar, itemForEventInInterface, itemForEventInClass); } [Fact] public Task TestVisualBasicInterfaceMembers() { var markup = @" Interface {|target2:IBar|} Property {|target4:Poo|} As Integer Function {|target6:Foo|}() As Integer End Interface Class {|target1:Bar|} Implements IBar Public Property {|target3:Poo|} As Integer Implements IBar.Poo Get Return 1 End Get Set(value As Integer) End Set End Property Public Function {|target5:Foo|}() As Integer Implements IBar.Foo Return 1 End Function End Class"; var itemForIBar = new TestInheritanceMemberItem( lineNumber: 2, memberName: "Interface IBar", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Class Bar", locationTag: "target1", relationship: InheritanceRelationship.ImplementingType))); var itemForBar = new TestInheritanceMemberItem( lineNumber: 7, memberName: "Class Bar", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Interface IBar", locationTag: "target2", relationship: InheritanceRelationship.ImplementedInterface))); var itemForPooInInterface = new TestInheritanceMemberItem( lineNumber: 3, memberName: "Property IBar.Poo As Integer", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Property Bar.Poo As Integer", locationTag: "target3", relationship: InheritanceRelationship.ImplementingMember))); var itemForPooInClass = new TestInheritanceMemberItem( lineNumber: 9, memberName: "Property Bar.Poo As Integer", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Property IBar.Poo As Integer", locationTag: "target4", relationship: InheritanceRelationship.ImplementedMember))); var itemForFooInInterface = new TestInheritanceMemberItem( lineNumber: 4, memberName: "Function IBar.Foo() As Integer", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Function Bar.Foo() As Integer", locationTag: "target5", relationship: InheritanceRelationship.ImplementingMember))); var itemForFooInClass = new TestInheritanceMemberItem( lineNumber: 16, memberName: "Function Bar.Foo() As Integer", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Function IBar.Foo() As Integer", locationTag: "target6", relationship: InheritanceRelationship.ImplementedMember))); return VerifyInSingleDocumentAsync( markup, LanguageNames.VisualBasic, itemForIBar, itemForBar, itemForPooInInterface, itemForPooInClass, itemForFooInInterface, itemForFooInClass); } [Fact] public Task TestVisualBasicMustInheritClassMember() { var markup = @" MustInherit Class {|target2:Bar1|} Public MustOverride Sub {|target4:Foo|}() End Class Class {|target1:Bar|} Inherits Bar1 Public Overrides Sub {|target3:Foo|}() End Sub End Class"; var itemForBar1 = new TestInheritanceMemberItem( lineNumber: 2, memberName: "Class Bar1", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: $"Class Bar", locationTag: "target1", relationship: InheritanceRelationship.DerivedType))); var itemForBar = new TestInheritanceMemberItem( lineNumber: 6, memberName: "Class Bar", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Class Bar1", locationTag: "target2", relationship: InheritanceRelationship.BaseType))); var itemForFooInBar1 = new TestInheritanceMemberItem( lineNumber: 3, memberName: "MustOverride Sub Bar1.Foo()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Overrides Sub Bar.Foo()", locationTag: "target3", relationship: InheritanceRelationship.OverridingMember))); var itemForFooInBar = new TestInheritanceMemberItem( lineNumber: 8, memberName: "Overrides Sub Bar.Foo()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "MustOverride Sub Bar1.Foo()", locationTag: "target4", relationship: InheritanceRelationship.OverriddenMember))); return VerifyInSingleDocumentAsync( markup, LanguageNames.VisualBasic, itemForBar1, itemForBar, itemForFooInBar1, itemForFooInBar); } [Theory] [CombinatorialData] public Task TestVisualBasicOverrideMemberCanFindImplementingInterface(bool testDuplicate) { var markup1 = @" Interface {|target4:IBar|} Sub {|target6:Foo|}() End Interface Class {|target1:Bar1|} Implements IBar Public Overridable Sub {|target2:Foo|}() Implements IBar.Foo End Sub End Class Class {|target5:Bar2|} Inherits Bar1 Public Overrides Sub {|target3:Foo|}() End Sub End Class"; var markup2 = @" Interface {|target4:IBar|} Sub {|target6:Foo|}() End Interface Class {|target1:Bar1|} Implements IBar Public Overridable Sub {|target2:Foo|}() Implements IBar.Foo End Sub End Class Class {|target5:Bar2|} Inherits Bar1 Public Overrides Sub {|target3:Foo|}() End Sub End Class"; var itemForIBar = new TestInheritanceMemberItem( lineNumber: 2, memberName: "Interface IBar", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Class Bar1", locationTag: "target1", relationship: InheritanceRelationship.ImplementingType), new TargetInfo( targetSymbolDisplayName: "Class Bar2", locationTag: "target5", relationship: InheritanceRelationship.ImplementingType))); var itemForFooInIBar = new TestInheritanceMemberItem( lineNumber: 3, memberName: "Sub IBar.Foo()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Overridable Sub Bar1.Foo()", locationTag: "target2", relationship: InheritanceRelationship.ImplementingMember), new TargetInfo( targetSymbolDisplayName: "Overrides Sub Bar2.Foo()", locationTag: "target3", relationship: InheritanceRelationship.ImplementingMember))); var itemForBar1 = new TestInheritanceMemberItem( lineNumber: 6, memberName: "Class Bar1", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Interface IBar", locationTag: "target4", relationship: InheritanceRelationship.ImplementedInterface), new TargetInfo( targetSymbolDisplayName: "Class Bar2", locationTag: "target5", relationship: InheritanceRelationship.DerivedType))); var itemForFooInBar1 = new TestInheritanceMemberItem( lineNumber: 8, memberName: "Overridable Sub Bar1.Foo()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Sub IBar.Foo()", locationTag: "target6", relationship: InheritanceRelationship.ImplementedMember), new TargetInfo( targetSymbolDisplayName: "Overrides Sub Bar2.Foo()", locationTag: "target3", relationship: InheritanceRelationship.OverridingMember))); var itemForBar2 = new TestInheritanceMemberItem( lineNumber: 12, memberName: "Class Bar2", targets: ImmutableArray.Create( new TargetInfo( targetSymbolDisplayName: "Class Bar1", locationTag: "target1", relationship: InheritanceRelationship.BaseType), new TargetInfo( targetSymbolDisplayName: "Interface IBar", locationTag: "target4", relationship: InheritanceRelationship.ImplementedInterface))); var itemForFooInBar2 = new TestInheritanceMemberItem( lineNumber: 14, memberName: "Overrides Sub Bar2.Foo()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Sub IBar.Foo()", locationTag: "target6", relationship: InheritanceRelationship.ImplementedMember), new TargetInfo( targetSymbolDisplayName: "Overridable Sub Bar1.Foo()", locationTag: "target2", relationship: InheritanceRelationship.OverriddenMember))); return VerifyInSingleDocumentAsync( testDuplicate ? markup2 : markup1, LanguageNames.VisualBasic, itemForIBar, itemForFooInIBar, itemForBar1, itemForFooInBar1, itemForBar2, itemForFooInBar2); } [Fact] public Task TestVisualBasicFindGenericsBaseType() { var markup = @" Public Interface {|target5:IBar|}(Of T) Sub {|target6:Foo|}() End Interface Public Class {|target1:Bar|} Implements IBar(Of Integer) Implements IBar(Of String) Public Sub {|target3:Foo|}() Implements IBar(Of Integer).Foo Throw New NotImplementedException() End Sub Private Sub {|target4:IBar_Foo|}() Implements IBar(Of String).Foo Throw New NotImplementedException() End Sub End Class"; var itemForIBar = new TestInheritanceMemberItem( lineNumber: 2, memberName: "Interface IBar(Of T)", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Class Bar", locationTag: "target1", relationship: InheritanceRelationship.ImplementingType))); var itemForFooInIBar = new TestInheritanceMemberItem( lineNumber: 3, memberName: "Sub IBar(Of T).Foo()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Sub Bar.Foo()", locationTag: "target3", relationship: InheritanceRelationship.ImplementingMember), new TargetInfo( targetSymbolDisplayName: "Sub Bar.IBar_Foo()", locationTag: "target4", relationship: InheritanceRelationship.ImplementingMember))); var itemForBar = new TestInheritanceMemberItem( lineNumber: 6, memberName: "Class Bar", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Interface IBar(Of T)", locationTag: "target5", relationship: InheritanceRelationship.ImplementedInterface))); var itemForFooInBar = new TestInheritanceMemberItem( lineNumber: 10, memberName: "Sub Bar.Foo()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Sub IBar(Of T).Foo()", locationTag: "target6", relationship: InheritanceRelationship.ImplementedMember))); var itemForIBar_FooInBar = new TestInheritanceMemberItem( lineNumber: 14, memberName: "Sub Bar.IBar_Foo()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Sub IBar(Of T).Foo()", locationTag: "target6", relationship: InheritanceRelationship.ImplementedMember))); return VerifyInSingleDocumentAsync( markup, LanguageNames.VisualBasic, itemForIBar, itemForFooInIBar, itemForBar, itemForFooInBar, itemForIBar_FooInBar); } #endregion [Fact] public Task TestCSharpProjectReferencingVisualBasicProject() { var markup1 = @" using MyNamespace; namespace BarNs { public class {|target2:Bar|} : IBar { public void {|target4:Foo|}() { } } }"; var markup2 = @" Namespace MyNamespace Public Interface {|target1:IBar|} Sub {|target3:Foo|}() End Interface End Namespace"; var itemForBar = new TestInheritanceMemberItem( lineNumber: 5, memberName: "class Bar", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Interface IBar", locationTag: "target1", relationship: InheritanceRelationship.ImplementedInterface))); var itemForFooInMarkup1 = new TestInheritanceMemberItem( lineNumber: 7, memberName: "void Bar.Foo()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Sub IBar.Foo()", locationTag: "target3", relationship: InheritanceRelationship.ImplementedMember))); var itemForIBar = new TestInheritanceMemberItem( lineNumber: 3, memberName: "Interface IBar", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "class Bar", locationTag: "target2", relationship: InheritanceRelationship.ImplementingType))); var itemForFooInMarkup2 = new TestInheritanceMemberItem( lineNumber: 4, memberName: "Sub IBar.Foo()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "void Bar.Foo()", locationTag: "target4", relationship: InheritanceRelationship.ImplementingMember))); return VerifyInDifferentProjectsAsync( (markup1, LanguageNames.CSharp), (markup2, LanguageNames.VisualBasic), new[] { itemForBar, itemForFooInMarkup1 }, new[] { itemForIBar, itemForFooInMarkup2 }); } [Fact] public Task TestVisualBasicProjectReferencingCSharpProject() { var markup1 = @" Imports BarNs Namespace MyNamespace Public Class {|target2:Bar44|} Implements IBar Public Sub {|target4:Foo|}() Implements IBar.Foo End Sub End Class End Namespace"; var markup2 = @" namespace BarNs { public interface {|target1:IBar|} { void {|target3:Foo|}(); } }"; var itemForBar44 = new TestInheritanceMemberItem( lineNumber: 4, memberName: "Class Bar44", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "interface IBar", locationTag: "target1", relationship: InheritanceRelationship.ImplementedInterface))); var itemForFooInMarkup1 = new TestInheritanceMemberItem( lineNumber: 7, memberName: "Sub Bar44.Foo()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "void IBar.Foo()", locationTag: "target3", relationship: InheritanceRelationship.ImplementedMember))); var itemForIBar = new TestInheritanceMemberItem( lineNumber: 4, memberName: "interface IBar", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Class Bar44", locationTag: "target2", relationship: InheritanceRelationship.ImplementingType))); var itemForFooInMarkup2 = new TestInheritanceMemberItem( lineNumber: 6, memberName: "void IBar.Foo()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Sub Bar44.Foo()", locationTag: "target4", relationship: InheritanceRelationship.ImplementingMember))); return VerifyInDifferentProjectsAsync( (markup1, LanguageNames.VisualBasic), (markup2, LanguageNames.CSharp), new[] { itemForBar44, itemForFooInMarkup1 }, new[] { itemForIBar, itemForFooInMarkup2 }); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.InheritanceMargin; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.InheritanceMargin { [Trait(Traits.Feature, Traits.Features.InheritanceMargin)] [UseExportProvider] public class InheritanceMarginTests { private const string SearchAreaTag = "SeachTag"; #region Helpers private static Task VerifyNoItemForDocumentAsync(string markup, string languageName) => VerifyInSingleDocumentAsync(markup, languageName); private static Task VerifyInSingleDocumentAsync( string markup, string languageName, params TestInheritanceMemberItem[] memberItems) { markup = @$"<![CDATA[ {markup}]]>"; var workspaceFile = $@" <Workspace> <Project Language=""{languageName}"" CommonReferences=""true""> <Document> {markup} </Document> </Project> </Workspace>"; var cancellationToken = CancellationToken.None; using var testWorkspace = TestWorkspace.Create( workspaceFile, composition: EditorTestCompositions.EditorFeatures); var testHostDocument = testWorkspace.Documents[0]; return VerifyTestMemberInDocumentAsync(testWorkspace, testHostDocument, memberItems, cancellationToken); } private static async Task VerifyTestMemberInDocumentAsync( TestWorkspace testWorkspace, TestHostDocument testHostDocument, TestInheritanceMemberItem[] memberItems, CancellationToken cancellationToken) { var document = testWorkspace.CurrentSolution.GetRequiredDocument(testHostDocument.Id); var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var searchingSpan = root.Span; // Look for the search span, if not found, then pass the whole document span to the service. if (testHostDocument.AnnotatedSpans.TryGetValue(SearchAreaTag, out var spans) && spans.IsSingle()) { searchingSpan = spans[0]; } var service = document.GetRequiredLanguageService<IInheritanceMarginService>(); var actualItems = await service.GetInheritanceMemberItemsAsync( document, searchingSpan, cancellationToken).ConfigureAwait(false); var sortedActualItems = actualItems.OrderBy(item => item.LineNumber).ToImmutableArray(); var sortedExpectedItems = memberItems.OrderBy(item => item.LineNumber).ToImmutableArray(); Assert.Equal(sortedExpectedItems.Length, sortedActualItems.Length); for (var i = 0; i < sortedActualItems.Length; i++) { await VerifyInheritanceMemberAsync(testWorkspace, sortedExpectedItems[i], sortedActualItems[i]); } } private static async Task VerifyInheritanceMemberAsync(TestWorkspace testWorkspace, TestInheritanceMemberItem expectedItem, InheritanceMarginItem actualItem) { Assert.Equal(expectedItem.LineNumber, actualItem.LineNumber); Assert.Equal(expectedItem.MemberName, actualItem.DisplayTexts.JoinText()); Assert.Equal(expectedItem.Targets.Length, actualItem.TargetItems.Length); var expectedTargets = expectedItem.Targets .Select(info => TestInheritanceTargetItem.Create(info, testWorkspace)) .OrderBy(target => target.TargetSymbolName) .ToImmutableArray(); var sortedActualTargets = actualItem.TargetItems.OrderBy(target => target.DefinitionItem.DisplayParts.JoinText()) .ToImmutableArray(); for (var i = 0; i < expectedTargets.Length; i++) { await VerifyInheritanceTargetAsync(expectedTargets[i], sortedActualTargets[i]); } } private static async Task VerifyInheritanceTargetAsync(TestInheritanceTargetItem expectedTarget, InheritanceTargetItem actualTarget) { Assert.Equal(expectedTarget.TargetSymbolName, actualTarget.DefinitionItem.DisplayParts.JoinText()); Assert.Equal(expectedTarget.RelationshipToMember, actualTarget.RelationToMember); if (expectedTarget.IsInMetadata) { Assert.True(actualTarget.DefinitionItem.Properties.ContainsKey("MetadataSymbolKey")); Assert.True(actualTarget.DefinitionItem.SourceSpans.IsEmpty); } else { var actualDocumentSpans = actualTarget.DefinitionItem.SourceSpans.OrderBy(documentSpan => documentSpan.SourceSpan.Start).ToImmutableArray(); var expectedDocumentSpans = expectedTarget.DocumentSpans.OrderBy(documentSpan => documentSpan.SourceSpan.Start).ToImmutableArray(); Assert.Equal(expectedDocumentSpans.Length, actualDocumentSpans.Length); for (var i = 0; i < actualDocumentSpans.Length; i++) { var docSpan = await actualDocumentSpans[i].TryRehydrateAsync(CancellationToken.None); Assert.Equal(expectedDocumentSpans[i].SourceSpan, docSpan.Value.SourceSpan); Assert.Equal(expectedDocumentSpans[i].Document.FilePath, docSpan.Value.Document.FilePath); } } } /// <summary> /// Project of markup1 is referencing project of markup2 /// </summary> private static async Task VerifyInDifferentProjectsAsync( (string markupInProject1, string languageName) markup1, (string markupInProject2, string languageName) markup2, TestInheritanceMemberItem[] memberItemsInMarkup1, TestInheritanceMemberItem[] memberItemsInMarkup2) { var workspaceFile = $@" <Workspace> <Project Language=""{markup1.languageName}"" AssemblyName=""Assembly1"" CommonReferences=""true""> <ProjectReference>Assembly2</ProjectReference> <Document> <![CDATA[ {markup1.markupInProject1}]]> </Document> </Project> <Project Language=""{markup2.languageName}"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> <![CDATA[ {markup2.markupInProject2}]]> </Document> </Project> </Workspace>"; var cancellationToken = CancellationToken.None; using var testWorkspace = TestWorkspace.Create( workspaceFile, composition: EditorTestCompositions.EditorFeatures); var testHostDocument1 = testWorkspace.Documents.Single(doc => doc.Project.AssemblyName.Equals("Assembly1")); var testHostDocument2 = testWorkspace.Documents.Single(doc => doc.Project.AssemblyName.Equals("Assembly2")); await VerifyTestMemberInDocumentAsync(testWorkspace, testHostDocument1, memberItemsInMarkup1, cancellationToken).ConfigureAwait(false); await VerifyTestMemberInDocumentAsync(testWorkspace, testHostDocument2, memberItemsInMarkup2, cancellationToken).ConfigureAwait(false); } private class TestInheritanceMemberItem { public readonly int LineNumber; public readonly string MemberName; public readonly ImmutableArray<TargetInfo> Targets; public TestInheritanceMemberItem( int lineNumber, string memberName, ImmutableArray<TargetInfo> targets) { LineNumber = lineNumber; MemberName = memberName; Targets = targets; } } private class TargetInfo { public readonly string TargetSymbolDisplayName; public readonly string? LocationTag; public readonly InheritanceRelationship Relationship; public readonly bool InMetadata; public TargetInfo( string targetSymbolDisplayName, string locationTag, InheritanceRelationship relationship) { TargetSymbolDisplayName = targetSymbolDisplayName; LocationTag = locationTag; Relationship = relationship; InMetadata = false; } public TargetInfo( string targetSymbolDisplayName, InheritanceRelationship relationship, bool inMetadata) { TargetSymbolDisplayName = targetSymbolDisplayName; Relationship = relationship; InMetadata = inMetadata; LocationTag = null; } } private class TestInheritanceTargetItem { public readonly string TargetSymbolName; public readonly InheritanceRelationship RelationshipToMember; public readonly ImmutableArray<DocumentSpan> DocumentSpans; public readonly bool IsInMetadata; public TestInheritanceTargetItem( string targetSymbolName, InheritanceRelationship relationshipToMember, ImmutableArray<DocumentSpan> documentSpans, bool isInMetadata) { TargetSymbolName = targetSymbolName; RelationshipToMember = relationshipToMember; DocumentSpans = documentSpans; IsInMetadata = isInMetadata; } public static TestInheritanceTargetItem Create( TargetInfo targetInfo, TestWorkspace testWorkspace) { if (targetInfo.InMetadata) { return new TestInheritanceTargetItem( targetInfo.TargetSymbolDisplayName, targetInfo.Relationship, ImmutableArray<DocumentSpan>.Empty, isInMetadata: true); } else { using var _ = ArrayBuilder<DocumentSpan>.GetInstance(out var builder); // If the target is not in metadata, there must be a location tag to give the span! Assert.True(targetInfo.LocationTag != null); foreach (var testHostDocument in testWorkspace.Documents) { if (targetInfo.LocationTag != null) { var annotatedSpans = testHostDocument.AnnotatedSpans; if (annotatedSpans.TryGetValue(targetInfo.LocationTag, out var spans)) { var document = testWorkspace.CurrentSolution.GetRequiredDocument(testHostDocument.Id); builder.AddRange(spans.Select(span => new DocumentSpan(document, span))); } } } return new TestInheritanceTargetItem( targetInfo.TargetSymbolDisplayName, targetInfo.Relationship, builder.ToImmutable(), isInMetadata: false); } } } #endregion #region TestsForCSharp [Fact] public Task TestCSharpClassWithErrorBaseType() { var markup = @" public class Bar : SomethingUnknown { }"; return VerifyNoItemForDocumentAsync(markup, LanguageNames.CSharp); } [Fact] public Task TestCSharpReferencingMetadata() { var markup = @" using System.Collections; public class Bar : IEnumerable { public IEnumerator GetEnumerator () { return null }; }"; var itemForBar = new TestInheritanceMemberItem( lineNumber: 3, memberName: "class Bar", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "interface IEnumerable", relationship: InheritanceRelationship.ImplementedInterface, inMetadata: true))); var itemForGetEnumerator = new TestInheritanceMemberItem( lineNumber: 5, memberName: "IEnumerator Bar.GetEnumerator()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "IEnumerator IEnumerable.GetEnumerator()", relationship: InheritanceRelationship.ImplementedMember, inMetadata: true))); return VerifyInSingleDocumentAsync(markup, LanguageNames.CSharp, itemForBar, itemForGetEnumerator); } [Fact] public Task TestCSharpClassImplementingInterface() { var markup = @" interface {|target1:IBar|} { } public class {|target2:Bar|} : IBar { } "; var itemOnLine2 = new TestInheritanceMemberItem( lineNumber: 2, memberName: "interface IBar", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "class Bar", locationTag: "target2", relationship: InheritanceRelationship.ImplementingType))); var itemOnLine3 = new TestInheritanceMemberItem( lineNumber: 3, memberName: "class Bar", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "interface IBar", locationTag: "target1", relationship: InheritanceRelationship.ImplementedInterface))); return VerifyInSingleDocumentAsync( markup, LanguageNames.CSharp, itemOnLine2, itemOnLine3); } [Fact] public Task TestCSharpInterfaceImplementingInterface() { var markup = @" interface {|target1:IBar|} { } interface {|target2:IBar2|} : IBar { } "; var itemOnLine2 = new TestInheritanceMemberItem( lineNumber: 2, memberName: "interface IBar", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "interface IBar2", locationTag: "target2", relationship: InheritanceRelationship.ImplementingType)) ); var itemOnLine3 = new TestInheritanceMemberItem( lineNumber: 3, memberName: "interface IBar2", targets: ImmutableArray<TargetInfo>.Empty .Add(new TargetInfo( targetSymbolDisplayName: "interface IBar", locationTag: "target1", relationship: InheritanceRelationship.InheritedInterface)) ); return VerifyInSingleDocumentAsync( markup, LanguageNames.CSharp, itemOnLine2, itemOnLine3); } [Fact] public Task TestCSharpClassInheritsClass() { var markup = @" class {|target2:A|} { } class {|target1:B|} : A { } "; var itemOnLine2 = new TestInheritanceMemberItem( lineNumber: 2, memberName: "class A", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "class B", locationTag: "target1", relationship: InheritanceRelationship.DerivedType)) ); var itemOnLine3 = new TestInheritanceMemberItem( lineNumber: 3, memberName: "class B", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "class A", locationTag: "target2", relationship: InheritanceRelationship.BaseType)) ); return VerifyInSingleDocumentAsync( markup, LanguageNames.CSharp, itemOnLine2, itemOnLine3); } [Theory] [InlineData("class")] [InlineData("struct")] [InlineData("enum")] [InlineData("interface")] public Task TestCSharpTypeWithoutBaseType(string typeName) { var markup = $@" public {typeName} Bar {{ }}"; return VerifyNoItemForDocumentAsync(markup, LanguageNames.CSharp); } [Theory] [InlineData("public Bar() { }")] [InlineData("public static void Bar3() { }")] [InlineData("public static void ~Bar() { }")] [InlineData("public static Bar operator +(Bar a, Bar b) => new Bar();")] public Task TestCSharpSpecialMember(string memberDeclaration) { var markup = $@" public abstract class {{|target1:Bar1|}} {{}} public class Bar : Bar1 {{ {{|{SearchAreaTag}:{memberDeclaration}|}} }}"; return VerifyInSingleDocumentAsync( markup, LanguageNames.CSharp, new TestInheritanceMemberItem( lineNumber: 4, memberName: "class Bar", targets: ImmutableArray.Create( new TargetInfo( targetSymbolDisplayName: "class Bar1", locationTag: "target1", relationship: InheritanceRelationship.BaseType)))); } [Fact] public Task TestCSharpEventDeclaration() { var markup = @" using System; interface {|target2:IBar|} { event EventHandler {|target4:e|}; } public class {|target1:Bar|} : IBar { public event EventHandler {|target3:e|} { add {} remove {} } }"; var itemForIBar = new TestInheritanceMemberItem( lineNumber: 3, memberName: "interface IBar", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "class Bar", locationTag: "target1", relationship: InheritanceRelationship.ImplementingType))); var itemForBar = new TestInheritanceMemberItem( lineNumber: 7, memberName: "class Bar", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "interface IBar", locationTag: "target2", relationship: InheritanceRelationship.ImplementedInterface))); var itemForEventInInterface = new TestInheritanceMemberItem( lineNumber: 5, memberName: "event EventHandler IBar.e", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "event EventHandler Bar.e", locationTag: "target3", relationship: InheritanceRelationship.ImplementingMember))); var itemForEventInClass = new TestInheritanceMemberItem( lineNumber: 9, memberName: "event EventHandler Bar.e", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "event EventHandler IBar.e", locationTag: "target4", relationship: InheritanceRelationship.ImplementedMember))); return VerifyInSingleDocumentAsync( markup, LanguageNames.CSharp, itemForIBar, itemForBar, itemForEventInInterface, itemForEventInClass); } [Fact] public Task TestCSharpEventFieldDeclarations() { var markup = @"using System; interface {|target2:IBar|} { event EventHandler {|target5:e1|}, {|target6:e2|}; } public class {|target1:Bar|} : IBar { public event EventHandler {|target3:e1|}, {|target4:e2|}; }"; var itemForIBar = new TestInheritanceMemberItem( lineNumber: 2, memberName: "interface IBar", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "class Bar", locationTag: "target1", relationship: InheritanceRelationship.ImplementingType))); var itemForBar = new TestInheritanceMemberItem( lineNumber: 6, memberName: "class Bar", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "interface IBar", locationTag: "target2", relationship: InheritanceRelationship.ImplementedInterface))); var itemForE1InInterface = new TestInheritanceMemberItem( lineNumber: 4, memberName: "event EventHandler IBar.e1", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "event EventHandler Bar.e1", locationTag: "target3", relationship: InheritanceRelationship.ImplementingMember))); var itemForE2InInterface = new TestInheritanceMemberItem( lineNumber: 4, memberName: "event EventHandler IBar.e2", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "event EventHandler Bar.e2", locationTag: "target4", relationship: InheritanceRelationship.ImplementingMember))); var itemForE1InClass = new TestInheritanceMemberItem( lineNumber: 8, memberName: "event EventHandler Bar.e1", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "event EventHandler IBar.e1", locationTag: "target5", relationship: InheritanceRelationship.ImplementedMember))); var itemForE2InClass = new TestInheritanceMemberItem( lineNumber: 8, memberName: "event EventHandler Bar.e2", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "event EventHandler IBar.e2", locationTag: "target6", relationship: InheritanceRelationship.ImplementedMember))); return VerifyInSingleDocumentAsync( markup, LanguageNames.CSharp, itemForIBar, itemForBar, itemForE1InInterface, itemForE2InInterface, itemForE1InClass, itemForE2InClass); } [Fact] public Task TestCSharpInterfaceMembers() { var markup = @"using System; interface {|target1:IBar|} { void {|target4:Foo|}(); int {|target6:Poo|} { get; set; } event EventHandler {|target8:Eoo|}; int {|target9:this|}[int i] { get; set; } } public class {|target2:Bar|} : IBar { public void {|target3:Foo|}() { } public int {|target5:Poo|} { get; set; } public event EventHandler {|target7:Eoo|}; public int {|target10:this|}[int i] { get => 1; set { } } }"; var itemForEooInClass = new TestInheritanceMemberItem( lineNumber: 13, memberName: "event EventHandler Bar.Eoo", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "event EventHandler IBar.Eoo", locationTag: "target8", relationship: InheritanceRelationship.ImplementedMember)) ); var itemForEooInInterface = new TestInheritanceMemberItem( lineNumber: 6, memberName: "event EventHandler IBar.Eoo", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "event EventHandler Bar.Eoo", locationTag: "target7", relationship: InheritanceRelationship.ImplementingMember)) ); var itemForPooInInterface = new TestInheritanceMemberItem( lineNumber: 5, memberName: "int IBar.Poo { get; set; }", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "int Bar.Poo { get; set; }", locationTag: "target5", relationship: InheritanceRelationship.ImplementingMember)) ); var itemForPooInClass = new TestInheritanceMemberItem( lineNumber: 12, memberName: "int Bar.Poo { get; set; }", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "int IBar.Poo { get; set; }", locationTag: "target6", relationship: InheritanceRelationship.ImplementedMember)) ); var itemForFooInInterface = new TestInheritanceMemberItem( lineNumber: 4, memberName: "void IBar.Foo()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "void Bar.Foo()", locationTag: "target3", relationship: InheritanceRelationship.ImplementingMember)) ); var itemForFooInClass = new TestInheritanceMemberItem( lineNumber: 11, memberName: "void Bar.Foo()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "void IBar.Foo()", locationTag: "target4", relationship: InheritanceRelationship.ImplementedMember)) ); var itemForIBar = new TestInheritanceMemberItem( lineNumber: 2, memberName: "interface IBar", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "class Bar", locationTag: "target2", relationship: InheritanceRelationship.ImplementingType)) ); var itemForBar = new TestInheritanceMemberItem( lineNumber: 9, memberName: "class Bar", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "interface IBar", locationTag: "target1", relationship: InheritanceRelationship.ImplementedInterface)) ); var itemForIndexerInClass = new TestInheritanceMemberItem( lineNumber: 14, memberName: "int Bar.this[int] { get; set; }", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "int IBar.this[int] { get; set; }", locationTag: "target9", relationship: InheritanceRelationship.ImplementedMember)) ); var itemForIndexerInInterface = new TestInheritanceMemberItem( lineNumber: 7, memberName: "int IBar.this[int] { get; set; }", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "int Bar.this[int] { get; set; }", locationTag: "target10", relationship: InheritanceRelationship.ImplementingMember)) ); return VerifyInSingleDocumentAsync( markup, LanguageNames.CSharp, itemForEooInClass, itemForEooInInterface, itemForPooInInterface, itemForPooInClass, itemForFooInInterface, itemForFooInClass, itemForIBar, itemForBar, itemForIndexerInInterface, itemForIndexerInClass); } [Theory] [InlineData("abstract")] [InlineData("virtual")] public Task TestCSharpAbstractClassMembers(string modifier) { var markup = $@"using System; public abstract class {{|target2:Bar|}} {{ public {modifier} void {{|target4:Foo|}}(); public {modifier} int {{|target6:Poo|}} {{ get; set; }} public {modifier} event EventHandler {{|target8:Eoo|}}; }} public class {{|target1:Bar2|}} : Bar {{ public override void {{|target3:Foo|}}() {{ }} public override int {{|target5:Poo|}} {{ get; set; }} public override event EventHandler {{|target7:Eoo|}}; }} "; var itemForEooInClass = new TestInheritanceMemberItem( lineNumber: 12, memberName: "override event EventHandler Bar2.Eoo", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: $"{modifier} event EventHandler Bar.Eoo", locationTag: "target8", relationship: InheritanceRelationship.OverriddenMember))); var itemForEooInAbstractClass = new TestInheritanceMemberItem( lineNumber: 6, memberName: $"{modifier} event EventHandler Bar.Eoo", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "override event EventHandler Bar2.Eoo", locationTag: "target7", relationship: InheritanceRelationship.OverridingMember))); var itemForPooInClass = new TestInheritanceMemberItem( lineNumber: 11, memberName: "override int Bar2.Poo { get; set; }", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: $"{modifier} int Bar.Poo {{ get; set; }}", locationTag: "target6", relationship: InheritanceRelationship.OverriddenMember))); var itemForPooInAbstractClass = new TestInheritanceMemberItem( lineNumber: 5, memberName: $"{modifier} int Bar.Poo {{ get; set; }}", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "override int Bar2.Poo { get; set; }", locationTag: "target5", relationship: InheritanceRelationship.OverridingMember))); var itemForFooInAbstractClass = new TestInheritanceMemberItem( lineNumber: 4, memberName: $"{modifier} void Bar.Foo()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "override void Bar2.Foo()", locationTag: "target3", relationship: InheritanceRelationship.OverridingMember))); var itemForFooInClass = new TestInheritanceMemberItem( lineNumber: 10, memberName: "override void Bar2.Foo()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: $"{modifier} void Bar.Foo()", locationTag: "target4", relationship: InheritanceRelationship.OverriddenMember))); var itemForBar = new TestInheritanceMemberItem( lineNumber: 2, memberName: "class Bar", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "class Bar2", locationTag: "target1", relationship: InheritanceRelationship.DerivedType))); var itemForBar2 = new TestInheritanceMemberItem( lineNumber: 8, memberName: "class Bar2", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "class Bar", locationTag: "target2", relationship: InheritanceRelationship.BaseType))); return VerifyInSingleDocumentAsync( markup, LanguageNames.CSharp, itemForBar, itemForBar2, itemForFooInAbstractClass, itemForFooInClass, itemForPooInClass, itemForPooInAbstractClass, itemForEooInClass, itemForEooInAbstractClass); } [Theory] [CombinatorialData] public Task TestCSharpOverrideMemberCanFindImplementingInterface(bool testDuplicate) { var markup1 = @"using System; public interface {|target4:IBar|} { void {|target6:Foo|}(); } public class {|target1:Bar1|} : IBar { public virtual void {|target2:Foo|}() { } } public class {|target5:Bar2|} : Bar1 { public override void {|target3:Foo|}() { } }"; var markup2 = @"using System; public interface {|target4:IBar|} { void {|target6:Foo|}(); } public class {|target1:Bar1|} : IBar { public virtual void {|target2:Foo|}() { } } public class {|target5:Bar2|} : Bar1, IBar { public override void {|target3:Foo|}() { } }"; var itemForIBar = new TestInheritanceMemberItem( lineNumber: 2, memberName: "interface IBar", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "class Bar1", locationTag: "target1", relationship: InheritanceRelationship.ImplementingType), new TargetInfo( targetSymbolDisplayName: "class Bar2", locationTag: "target5", relationship: InheritanceRelationship.ImplementingType))); var itemForFooInIBar = new TestInheritanceMemberItem( lineNumber: 4, memberName: "void IBar.Foo()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "virtual void Bar1.Foo()", locationTag: "target2", relationship: InheritanceRelationship.ImplementingMember), new TargetInfo( targetSymbolDisplayName: "override void Bar2.Foo()", locationTag: "target3", relationship: InheritanceRelationship.ImplementingMember))); var itemForBar1 = new TestInheritanceMemberItem( lineNumber: 6, memberName: "class Bar1", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "interface IBar", locationTag: "target4", relationship: InheritanceRelationship.ImplementedInterface), new TargetInfo( targetSymbolDisplayName: "class Bar2", locationTag: "target5", relationship: InheritanceRelationship.DerivedType))); var itemForFooInBar1 = new TestInheritanceMemberItem( lineNumber: 8, memberName: "virtual void Bar1.Foo()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "void IBar.Foo()", locationTag: "target6", relationship: InheritanceRelationship.ImplementedMember), new TargetInfo( targetSymbolDisplayName: "override void Bar2.Foo()", locationTag: "target3", relationship: InheritanceRelationship.OverridingMember))); var itemForBar2 = new TestInheritanceMemberItem( lineNumber: 10, memberName: "class Bar2", targets: ImmutableArray.Create( new TargetInfo( targetSymbolDisplayName: "class Bar1", locationTag: "target1", relationship: InheritanceRelationship.BaseType), new TargetInfo( targetSymbolDisplayName: "interface IBar", locationTag: "target4", relationship: InheritanceRelationship.ImplementedInterface))); var itemForFooInBar2 = new TestInheritanceMemberItem( lineNumber: 12, memberName: "override void Bar2.Foo()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "void IBar.Foo()", locationTag: "target6", relationship: InheritanceRelationship.ImplementedMember), new TargetInfo( targetSymbolDisplayName: "virtual void Bar1.Foo()", locationTag: "target2", relationship: InheritanceRelationship.OverriddenMember))); return VerifyInSingleDocumentAsync( testDuplicate ? markup2 : markup1, LanguageNames.CSharp, itemForIBar, itemForFooInIBar, itemForBar1, itemForFooInBar1, itemForBar2, itemForFooInBar2); } [Fact] public Task TestCSharpFindGenericsBaseType() { var markup = @" public interface {|target2:IBar|}<T> { void {|target4:Foo|}(); } public class {|target1:Bar2|} : IBar<int>, IBar<string> { public void {|target3:Foo|}(); }"; var itemForIBar = new TestInheritanceMemberItem( lineNumber: 2, memberName: "interface IBar<T>", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "class Bar2", locationTag: "target1", relationship: InheritanceRelationship.ImplementingType))); var itemForFooInIBar = new TestInheritanceMemberItem( lineNumber: 4, memberName: "void IBar<T>.Foo()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "void Bar2.Foo()", locationTag: "target3", relationship: InheritanceRelationship.ImplementingMember))); // Only have one IBar<T> item var itemForBar2 = new TestInheritanceMemberItem( lineNumber: 7, memberName: "class Bar2", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "interface IBar<T>", locationTag: "target2", relationship: InheritanceRelationship.ImplementedInterface))); // Only have one IBar<T>.Foo item var itemForFooInBar2 = new TestInheritanceMemberItem( lineNumber: 9, memberName: "void Bar2.Foo()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "void IBar<T>.Foo()", locationTag: "target4", relationship: InheritanceRelationship.ImplementedMember))); return VerifyInSingleDocumentAsync( markup, LanguageNames.CSharp, itemForIBar, itemForFooInIBar, itemForBar2, itemForFooInBar2); } [Fact] public Task TestCSharpExplicitInterfaceImplementation() { var markup = @" interface {|target2:IBar|}<T> { void {|target3:Foo|}(T t); } abstract class {|target1:AbsBar|} : IBar<int> { void IBar<int>.{|target4:Foo|}(int t) { throw new System.NotImplementedException(); } }"; var itemForIBar = new TestInheritanceMemberItem( lineNumber: 2, memberName: "interface IBar<T>", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "class AbsBar", locationTag: "target1", relationship: InheritanceRelationship.ImplementingType))); var itemForFooInIBar = new TestInheritanceMemberItem( lineNumber: 4, memberName: "void IBar<T>.Foo(T)", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "void AbsBar.IBar<int>.Foo(int)", locationTag: "target4", relationship: InheritanceRelationship.ImplementingMember))); var itemForAbsBar = new TestInheritanceMemberItem( lineNumber: 7, memberName: "class AbsBar", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "interface IBar<T>", locationTag: "target2", relationship: InheritanceRelationship.ImplementedInterface))); var itemForFooInAbsBar = new TestInheritanceMemberItem( lineNumber: 9, memberName: "void AbsBar.IBar<int>.Foo(int)", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "void IBar<T>.Foo(T)", locationTag: "target3", relationship: InheritanceRelationship.ImplementedMember) )); return VerifyInSingleDocumentAsync( markup, LanguageNames.CSharp, itemForIBar, itemForFooInIBar, itemForAbsBar, itemForFooInAbsBar); } [Fact] public Task TestStaticAbstractMemberInterface() { var markup = @" interface {|target5:I1|}<T> where T : I1<T> { static abstract void {|target4:M1|}(); static abstract int {|target7:P1|} { get; set; } static abstract event EventHandler {|target9:e1|}; static abstract int operator {|target11:+|}(T i1); static abstract implicit operator {|target12:int|}(T i1); } public class {|target1:Class1|} : I1<Class1> { public static void {|target2:M1|}() {} public static int {|target6:P1|} { get => 1; set { } } public static event EventHandler {|target8:e1|}; public static int operator {|target10:+|}(Class1 i) => 1; public static implicit operator {|target13:int|}(Class1 i) => 0; }"; var itemForI1 = new TestInheritanceMemberItem( lineNumber: 2, memberName: "interface I1<T>", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "class Class1", locationTag: "target1", relationship: InheritanceRelationship.ImplementingType))); var itemForM1InI1 = new TestInheritanceMemberItem( lineNumber: 4, memberName: "void I1<T>.M1()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "static void Class1.M1()", locationTag: "target2", relationship: InheritanceRelationship.ImplementingMember))); var itemForAbsClass1 = new TestInheritanceMemberItem( lineNumber: 11, memberName: "class Class1", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "interface I1<T>", locationTag: "target5", relationship: InheritanceRelationship.ImplementedInterface))); var itemForM1InClass1 = new TestInheritanceMemberItem( lineNumber: 13, memberName: "static void Class1.M1()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "void I1<T>.M1()", locationTag: "target4", relationship: InheritanceRelationship.ImplementedMember))); var itemForP1InI1 = new TestInheritanceMemberItem( lineNumber: 5, memberName: "int I1<T>.P1 { get; set; }", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "static int Class1.P1 { get; set; }", locationTag: "target6", relationship: InheritanceRelationship.ImplementingMember))); var itemForP1InClass1 = new TestInheritanceMemberItem( lineNumber: 14, memberName: "static int Class1.P1 { get; set; }", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "int I1<T>.P1 { get; set; }", locationTag: "target7", relationship: InheritanceRelationship.ImplementedMember))); var itemForE1InI1 = new TestInheritanceMemberItem( lineNumber: 6, memberName: "event EventHandler I1<T>.e1", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "static event EventHandler Class1.e1", locationTag: "target8", relationship: InheritanceRelationship.ImplementingMember))); var itemForE1InClass1 = new TestInheritanceMemberItem( lineNumber: 15, memberName: "static event EventHandler Class1.e1", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "event EventHandler I1<T>.e1", locationTag: "target9", relationship: InheritanceRelationship.ImplementedMember))); var itemForPlusOperatorInI1 = new TestInheritanceMemberItem( lineNumber: 7, memberName: "int I1<T>.operator +(T)", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "static int Class1.operator +(Class1)", locationTag: "target10", relationship: InheritanceRelationship.ImplementingMember))); var itemForPlusOperatorInClass1 = new TestInheritanceMemberItem( lineNumber: 16, memberName: "static int Class1.operator +(Class1)", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "int I1<T>.operator +(T)", locationTag: "target11", relationship: InheritanceRelationship.ImplementedMember))); var itemForIntOperatorInI1 = new TestInheritanceMemberItem( lineNumber: 8, memberName: "I1<T>.implicit operator int(T)", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "static Class1.implicit operator int(Class1)", locationTag: "target13", relationship: InheritanceRelationship.ImplementingMember))); var itemForIntOperatorInClass1 = new TestInheritanceMemberItem( lineNumber: 17, memberName: "static Class1.implicit operator int(Class1)", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "I1<T>.implicit operator int(T)", locationTag: "target12", relationship: InheritanceRelationship.ImplementedMember))); return VerifyInSingleDocumentAsync( markup, LanguageNames.CSharp, itemForI1, itemForAbsClass1, itemForM1InI1, itemForM1InClass1, itemForP1InI1, itemForP1InClass1, itemForE1InI1, itemForE1InClass1, itemForPlusOperatorInI1, itemForPlusOperatorInClass1, itemForIntOperatorInI1, itemForIntOperatorInClass1); } #endregion #region TestsForVisualBasic [Fact] public Task TestVisualBasicWithErrorBaseType() { var markup = @" Namespace MyNamespace Public Class Bar Implements SomethingNotExist End Class End Namespace"; return VerifyNoItemForDocumentAsync(markup, LanguageNames.VisualBasic); } [Fact] public Task TestVisualBasicReferencingMetadata() { var markup = @" Namespace MyNamespace Public Class Bar Implements System.Collections.IEnumerable Public Function GetEnumerator() As System.Collections.IEnumerator Implements System.Collections.IEnumerable.GetEnumerator Throw New NotImplementedException() End Function End Class End Namespace"; var itemForBar = new TestInheritanceMemberItem( lineNumber: 3, memberName: "Class Bar", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Interface IEnumerable", relationship: InheritanceRelationship.ImplementedInterface, inMetadata: true))); var itemForGetEnumerator = new TestInheritanceMemberItem( lineNumber: 5, memberName: "Function Bar.GetEnumerator() As IEnumerator", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Function IEnumerable.GetEnumerator() As IEnumerator", relationship: InheritanceRelationship.ImplementedMember, inMetadata: true))); return VerifyInSingleDocumentAsync(markup, LanguageNames.VisualBasic, itemForBar, itemForGetEnumerator); } [Fact] public Task TestVisualBasicClassImplementingInterface() { var markup = @" Interface {|target2:IBar|} End Interface Class {|target1:Bar|} Implements IBar End Class"; var itemForIBar = new TestInheritanceMemberItem( lineNumber: 2, memberName: "Interface IBar", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Class Bar", locationTag: "target1", relationship: InheritanceRelationship.ImplementingType))); var itemForBar = new TestInheritanceMemberItem( lineNumber: 4, memberName: "Class Bar", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Interface IBar", locationTag: "target2", relationship: InheritanceRelationship.ImplementedInterface))); return VerifyInSingleDocumentAsync( markup, LanguageNames.VisualBasic, itemForIBar, itemForBar); } [Fact] public Task TestVisualBasicInterfaceImplementingInterface() { var markup = @" Interface {|target2:IBar2|} End Interface Interface {|target1:IBar|} Inherits IBar2 End Interface"; var itemForIBar2 = new TestInheritanceMemberItem( lineNumber: 2, memberName: "Interface IBar2", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Interface IBar", locationTag: "target1", relationship: InheritanceRelationship.ImplementingType))); var itemForIBar = new TestInheritanceMemberItem( lineNumber: 4, memberName: "Interface IBar", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Interface IBar2", locationTag: "target2", relationship: InheritanceRelationship.InheritedInterface))); return VerifyInSingleDocumentAsync(markup, LanguageNames.VisualBasic, itemForIBar2, itemForIBar); } [Fact] public Task TestVisualBasicClassInheritsClass() { var markup = @" Class {|target2:Bar2|} End Class Class {|target1:Bar|} Inherits Bar2 End Class"; var itemForBar2 = new TestInheritanceMemberItem( lineNumber: 2, memberName: "Class Bar2", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Class Bar", locationTag: "target1", relationship: InheritanceRelationship.DerivedType))); var itemForBar = new TestInheritanceMemberItem( lineNumber: 4, memberName: "Class Bar", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Class Bar2", locationTag: "target2", relationship: InheritanceRelationship.BaseType))); return VerifyInSingleDocumentAsync(markup, LanguageNames.VisualBasic, itemForBar2, itemForBar); } [Theory] [InlineData("Class")] [InlineData("Structure")] [InlineData("Enum")] [InlineData("Interface")] public Task TestVisualBasicTypeWithoutBaseType(string typeName) { var markup = $@" {typeName} Bar End {typeName}"; return VerifyNoItemForDocumentAsync(markup, LanguageNames.VisualBasic); } [Fact] public Task TestVisualBasicMetadataInterface() { var markup = @" Imports System.Collections Class Bar Implements IEnumerable End Class"; return VerifyInSingleDocumentAsync( markup, LanguageNames.VisualBasic, new TestInheritanceMemberItem( lineNumber: 3, memberName: "Class Bar", targets: ImmutableArray.Create( new TargetInfo( targetSymbolDisplayName: "Interface IEnumerable", relationship: InheritanceRelationship.ImplementedInterface, inMetadata: true)))); } [Fact] public Task TestVisualBasicEventStatement() { var markup = @" Interface {|target2:IBar|} Event {|target4:e|} As EventHandler End Interface Class {|target1:Bar|} Implements IBar Public Event {|target3:e|} As EventHandler Implements IBar.e End Class"; var itemForIBar = new TestInheritanceMemberItem( lineNumber: 2, memberName: "Interface IBar", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Class Bar", locationTag: "target1", relationship: InheritanceRelationship.ImplementingType))); var itemForBar = new TestInheritanceMemberItem( lineNumber: 5, memberName: "Class Bar", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Interface IBar", locationTag: "target2", relationship: InheritanceRelationship.ImplementedInterface))); var itemForEventInInterface = new TestInheritanceMemberItem( lineNumber: 3, memberName: "Event IBar.e As EventHandler", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Event Bar.e As EventHandler", locationTag: "target3", relationship: InheritanceRelationship.ImplementingMember))); var itemForEventInClass = new TestInheritanceMemberItem( lineNumber: 7, memberName: "Event Bar.e As EventHandler", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Event IBar.e As EventHandler", locationTag: "target4", relationship: InheritanceRelationship.ImplementedMember))); return VerifyInSingleDocumentAsync( markup, LanguageNames.VisualBasic, itemForIBar, itemForBar, itemForEventInInterface, itemForEventInClass); } [Fact] public Task TestVisualBasicEventBlock() { var markup = @" Interface {|target2:IBar|} Event {|target4:e|} As EventHandler End Interface Class {|target1:Bar|} Implements IBar Public Custom Event {|target3:e|} As EventHandler Implements IBar.e End Event End Class"; var itemForIBar = new TestInheritanceMemberItem( lineNumber: 2, memberName: "Interface IBar", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Class Bar", locationTag: "target1", relationship: InheritanceRelationship.ImplementingType))); var itemForBar = new TestInheritanceMemberItem( lineNumber: 5, memberName: "Class Bar", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Interface IBar", locationTag: "target2", relationship: InheritanceRelationship.ImplementedInterface))); var itemForEventInInterface = new TestInheritanceMemberItem( lineNumber: 3, memberName: "Event IBar.e As EventHandler", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Event Bar.e As EventHandler", locationTag: "target3", relationship: InheritanceRelationship.ImplementingMember))); var itemForEventInClass = new TestInheritanceMemberItem( lineNumber: 7, memberName: "Event Bar.e As EventHandler", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Event IBar.e As EventHandler", locationTag: "target4", relationship: InheritanceRelationship.ImplementedMember))); return VerifyInSingleDocumentAsync( markup, LanguageNames.VisualBasic, itemForIBar, itemForBar, itemForEventInInterface, itemForEventInClass); } [Fact] public Task TestVisualBasicInterfaceMembers() { var markup = @" Interface {|target2:IBar|} Property {|target4:Poo|} As Integer Function {|target6:Foo|}() As Integer End Interface Class {|target1:Bar|} Implements IBar Public Property {|target3:Poo|} As Integer Implements IBar.Poo Get Return 1 End Get Set(value As Integer) End Set End Property Public Function {|target5:Foo|}() As Integer Implements IBar.Foo Return 1 End Function End Class"; var itemForIBar = new TestInheritanceMemberItem( lineNumber: 2, memberName: "Interface IBar", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Class Bar", locationTag: "target1", relationship: InheritanceRelationship.ImplementingType))); var itemForBar = new TestInheritanceMemberItem( lineNumber: 7, memberName: "Class Bar", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Interface IBar", locationTag: "target2", relationship: InheritanceRelationship.ImplementedInterface))); var itemForPooInInterface = new TestInheritanceMemberItem( lineNumber: 3, memberName: "Property IBar.Poo As Integer", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Property Bar.Poo As Integer", locationTag: "target3", relationship: InheritanceRelationship.ImplementingMember))); var itemForPooInClass = new TestInheritanceMemberItem( lineNumber: 9, memberName: "Property Bar.Poo As Integer", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Property IBar.Poo As Integer", locationTag: "target4", relationship: InheritanceRelationship.ImplementedMember))); var itemForFooInInterface = new TestInheritanceMemberItem( lineNumber: 4, memberName: "Function IBar.Foo() As Integer", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Function Bar.Foo() As Integer", locationTag: "target5", relationship: InheritanceRelationship.ImplementingMember))); var itemForFooInClass = new TestInheritanceMemberItem( lineNumber: 16, memberName: "Function Bar.Foo() As Integer", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Function IBar.Foo() As Integer", locationTag: "target6", relationship: InheritanceRelationship.ImplementedMember))); return VerifyInSingleDocumentAsync( markup, LanguageNames.VisualBasic, itemForIBar, itemForBar, itemForPooInInterface, itemForPooInClass, itemForFooInInterface, itemForFooInClass); } [Fact] public Task TestVisualBasicMustInheritClassMember() { var markup = @" MustInherit Class {|target2:Bar1|} Public MustOverride Sub {|target4:Foo|}() End Class Class {|target1:Bar|} Inherits Bar1 Public Overrides Sub {|target3:Foo|}() End Sub End Class"; var itemForBar1 = new TestInheritanceMemberItem( lineNumber: 2, memberName: "Class Bar1", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: $"Class Bar", locationTag: "target1", relationship: InheritanceRelationship.DerivedType))); var itemForBar = new TestInheritanceMemberItem( lineNumber: 6, memberName: "Class Bar", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Class Bar1", locationTag: "target2", relationship: InheritanceRelationship.BaseType))); var itemForFooInBar1 = new TestInheritanceMemberItem( lineNumber: 3, memberName: "MustOverride Sub Bar1.Foo()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Overrides Sub Bar.Foo()", locationTag: "target3", relationship: InheritanceRelationship.OverridingMember))); var itemForFooInBar = new TestInheritanceMemberItem( lineNumber: 8, memberName: "Overrides Sub Bar.Foo()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "MustOverride Sub Bar1.Foo()", locationTag: "target4", relationship: InheritanceRelationship.OverriddenMember))); return VerifyInSingleDocumentAsync( markup, LanguageNames.VisualBasic, itemForBar1, itemForBar, itemForFooInBar1, itemForFooInBar); } [Theory] [CombinatorialData] public Task TestVisualBasicOverrideMemberCanFindImplementingInterface(bool testDuplicate) { var markup1 = @" Interface {|target4:IBar|} Sub {|target6:Foo|}() End Interface Class {|target1:Bar1|} Implements IBar Public Overridable Sub {|target2:Foo|}() Implements IBar.Foo End Sub End Class Class {|target5:Bar2|} Inherits Bar1 Public Overrides Sub {|target3:Foo|}() End Sub End Class"; var markup2 = @" Interface {|target4:IBar|} Sub {|target6:Foo|}() End Interface Class {|target1:Bar1|} Implements IBar Public Overridable Sub {|target2:Foo|}() Implements IBar.Foo End Sub End Class Class {|target5:Bar2|} Inherits Bar1 Public Overrides Sub {|target3:Foo|}() End Sub End Class"; var itemForIBar = new TestInheritanceMemberItem( lineNumber: 2, memberName: "Interface IBar", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Class Bar1", locationTag: "target1", relationship: InheritanceRelationship.ImplementingType), new TargetInfo( targetSymbolDisplayName: "Class Bar2", locationTag: "target5", relationship: InheritanceRelationship.ImplementingType))); var itemForFooInIBar = new TestInheritanceMemberItem( lineNumber: 3, memberName: "Sub IBar.Foo()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Overridable Sub Bar1.Foo()", locationTag: "target2", relationship: InheritanceRelationship.ImplementingMember), new TargetInfo( targetSymbolDisplayName: "Overrides Sub Bar2.Foo()", locationTag: "target3", relationship: InheritanceRelationship.ImplementingMember))); var itemForBar1 = new TestInheritanceMemberItem( lineNumber: 6, memberName: "Class Bar1", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Interface IBar", locationTag: "target4", relationship: InheritanceRelationship.ImplementedInterface), new TargetInfo( targetSymbolDisplayName: "Class Bar2", locationTag: "target5", relationship: InheritanceRelationship.DerivedType))); var itemForFooInBar1 = new TestInheritanceMemberItem( lineNumber: 8, memberName: "Overridable Sub Bar1.Foo()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Sub IBar.Foo()", locationTag: "target6", relationship: InheritanceRelationship.ImplementedMember), new TargetInfo( targetSymbolDisplayName: "Overrides Sub Bar2.Foo()", locationTag: "target3", relationship: InheritanceRelationship.OverridingMember))); var itemForBar2 = new TestInheritanceMemberItem( lineNumber: 12, memberName: "Class Bar2", targets: ImmutableArray.Create( new TargetInfo( targetSymbolDisplayName: "Class Bar1", locationTag: "target1", relationship: InheritanceRelationship.BaseType), new TargetInfo( targetSymbolDisplayName: "Interface IBar", locationTag: "target4", relationship: InheritanceRelationship.ImplementedInterface))); var itemForFooInBar2 = new TestInheritanceMemberItem( lineNumber: 14, memberName: "Overrides Sub Bar2.Foo()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Sub IBar.Foo()", locationTag: "target6", relationship: InheritanceRelationship.ImplementedMember), new TargetInfo( targetSymbolDisplayName: "Overridable Sub Bar1.Foo()", locationTag: "target2", relationship: InheritanceRelationship.OverriddenMember))); return VerifyInSingleDocumentAsync( testDuplicate ? markup2 : markup1, LanguageNames.VisualBasic, itemForIBar, itemForFooInIBar, itemForBar1, itemForFooInBar1, itemForBar2, itemForFooInBar2); } [Fact] public Task TestVisualBasicFindGenericsBaseType() { var markup = @" Public Interface {|target5:IBar|}(Of T) Sub {|target6:Foo|}() End Interface Public Class {|target1:Bar|} Implements IBar(Of Integer) Implements IBar(Of String) Public Sub {|target3:Foo|}() Implements IBar(Of Integer).Foo Throw New NotImplementedException() End Sub Private Sub {|target4:IBar_Foo|}() Implements IBar(Of String).Foo Throw New NotImplementedException() End Sub End Class"; var itemForIBar = new TestInheritanceMemberItem( lineNumber: 2, memberName: "Interface IBar(Of T)", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Class Bar", locationTag: "target1", relationship: InheritanceRelationship.ImplementingType))); var itemForFooInIBar = new TestInheritanceMemberItem( lineNumber: 3, memberName: "Sub IBar(Of T).Foo()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Sub Bar.Foo()", locationTag: "target3", relationship: InheritanceRelationship.ImplementingMember), new TargetInfo( targetSymbolDisplayName: "Sub Bar.IBar_Foo()", locationTag: "target4", relationship: InheritanceRelationship.ImplementingMember))); var itemForBar = new TestInheritanceMemberItem( lineNumber: 6, memberName: "Class Bar", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Interface IBar(Of T)", locationTag: "target5", relationship: InheritanceRelationship.ImplementedInterface))); var itemForFooInBar = new TestInheritanceMemberItem( lineNumber: 10, memberName: "Sub Bar.Foo()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Sub IBar(Of T).Foo()", locationTag: "target6", relationship: InheritanceRelationship.ImplementedMember))); var itemForIBar_FooInBar = new TestInheritanceMemberItem( lineNumber: 14, memberName: "Sub Bar.IBar_Foo()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Sub IBar(Of T).Foo()", locationTag: "target6", relationship: InheritanceRelationship.ImplementedMember))); return VerifyInSingleDocumentAsync( markup, LanguageNames.VisualBasic, itemForIBar, itemForFooInIBar, itemForBar, itemForFooInBar, itemForIBar_FooInBar); } #endregion [Fact] public Task TestCSharpProjectReferencingVisualBasicProject() { var markup1 = @" using MyNamespace; namespace BarNs { public class {|target2:Bar|} : IBar { public void {|target4:Foo|}() { } } }"; var markup2 = @" Namespace MyNamespace Public Interface {|target1:IBar|} Sub {|target3:Foo|}() End Interface End Namespace"; var itemForBar = new TestInheritanceMemberItem( lineNumber: 5, memberName: "class Bar", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Interface IBar", locationTag: "target1", relationship: InheritanceRelationship.ImplementedInterface))); var itemForFooInMarkup1 = new TestInheritanceMemberItem( lineNumber: 7, memberName: "void Bar.Foo()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Sub IBar.Foo()", locationTag: "target3", relationship: InheritanceRelationship.ImplementedMember))); var itemForIBar = new TestInheritanceMemberItem( lineNumber: 3, memberName: "Interface IBar", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "class Bar", locationTag: "target2", relationship: InheritanceRelationship.ImplementingType))); var itemForFooInMarkup2 = new TestInheritanceMemberItem( lineNumber: 4, memberName: "Sub IBar.Foo()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "void Bar.Foo()", locationTag: "target4", relationship: InheritanceRelationship.ImplementingMember))); return VerifyInDifferentProjectsAsync( (markup1, LanguageNames.CSharp), (markup2, LanguageNames.VisualBasic), new[] { itemForBar, itemForFooInMarkup1 }, new[] { itemForIBar, itemForFooInMarkup2 }); } [Fact] public Task TestVisualBasicProjectReferencingCSharpProject() { var markup1 = @" Imports BarNs Namespace MyNamespace Public Class {|target2:Bar44|} Implements IBar Public Sub {|target4:Foo|}() Implements IBar.Foo End Sub End Class End Namespace"; var markup2 = @" namespace BarNs { public interface {|target1:IBar|} { void {|target3:Foo|}(); } }"; var itemForBar44 = new TestInheritanceMemberItem( lineNumber: 4, memberName: "Class Bar44", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "interface IBar", locationTag: "target1", relationship: InheritanceRelationship.ImplementedInterface))); var itemForFooInMarkup1 = new TestInheritanceMemberItem( lineNumber: 7, memberName: "Sub Bar44.Foo()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "void IBar.Foo()", locationTag: "target3", relationship: InheritanceRelationship.ImplementedMember))); var itemForIBar = new TestInheritanceMemberItem( lineNumber: 4, memberName: "interface IBar", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Class Bar44", locationTag: "target2", relationship: InheritanceRelationship.ImplementingType))); var itemForFooInMarkup2 = new TestInheritanceMemberItem( lineNumber: 6, memberName: "void IBar.Foo()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Sub Bar44.Foo()", locationTag: "target4", relationship: InheritanceRelationship.ImplementingMember))); return VerifyInDifferentProjectsAsync( (markup1, LanguageNames.VisualBasic), (markup2, LanguageNames.CSharp), new[] { itemForBar44, itemForFooInMarkup1 }, new[] { itemForIBar, itemForFooInMarkup2 }); } } }
-1
dotnet/roslyn
56,416
Do not include function type conversions in user-defined conversions
Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
cston
"2021-09-15T18:16:38Z"
"2021-09-24T23:24:46Z"
bb99d0bc89bde01650d2a694d720d600dd952dcb
3913f352cf066fa485869d866e4753fa721cbe93
Do not include function type conversions in user-defined conversions. Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
./src/ExpressionEvaluator/Core/Source/ResultProvider/Expansion/DebuggerTypeProxyExpansion.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.VisualStudio.Debugger.Evaluation; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; using System.Collections.ObjectModel; using System.Diagnostics; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { /// <summary> /// Debugger type proxy expansion. /// </summary> /// <remarks> /// May include <see cref="System.Collections.IEnumerable"/> and /// <see cref="System.Collections.Generic.IEnumerable{T}"/> as special cases. /// (The proxy is not declared by an attribute, but is known to debugger.) /// </remarks> internal sealed class DebuggerTypeProxyExpansion : Expansion { internal static Expansion CreateExpansion( ResultProvider resultProvider, DkmInspectionContext inspectionContext, string name, TypeAndCustomInfo typeDeclaringMemberAndInfoOpt, TypeAndCustomInfo declaredTypeAndInfo, DkmClrValue value, bool childShouldParenthesize, string fullName, string childFullNamePrefix, ReadOnlyCollection<string> formatSpecifiers, DkmEvaluationResultFlags flags, string editableValue) { Debug.Assert((inspectionContext.EvaluationFlags & DkmEvaluationFlags.NoExpansion) == 0); // Note: The native EE uses the proxy type, even for // null instances, so statics on the proxy type are // displayed. That case is not supported currently. if (!value.IsNull) { var proxyType = value.Type.GetProxyType(); if (proxyType != null) { if ((inspectionContext.EvaluationFlags & DkmEvaluationFlags.ShowValueRaw) != 0) { var rawView = CreateRawView(resultProvider, inspectionContext, declaredTypeAndInfo, value); Debug.Assert(rawView != null); return rawView; } DkmClrValue proxyValue; try { proxyValue = value.InstantiateProxyType(inspectionContext, proxyType); } catch { proxyValue = null; } if (proxyValue != null) { return new DebuggerTypeProxyExpansion( inspectionContext, proxyValue, name, typeDeclaringMemberAndInfoOpt, declaredTypeAndInfo, value, childShouldParenthesize, fullName, childFullNamePrefix, formatSpecifiers, flags, editableValue, resultProvider); } } } return null; } private readonly EvalResult _proxyItem; private readonly string _name; private readonly TypeAndCustomInfo _typeDeclaringMemberAndInfoOpt; private readonly TypeAndCustomInfo _declaredTypeAndInfo; private readonly DkmClrValue _value; private readonly bool _childShouldParenthesize; private readonly string _fullName; private readonly string _childFullNamePrefix; private readonly ReadOnlyCollection<string> _formatSpecifiers; private readonly DkmEvaluationResultFlags _flags; private readonly string _editableValue; private DebuggerTypeProxyExpansion( DkmInspectionContext inspectionContext, DkmClrValue proxyValue, string name, TypeAndCustomInfo typeDeclaringMemberAndInfoOpt, TypeAndCustomInfo declaredTypeAndInfo, DkmClrValue value, bool childShouldParenthesize, string fullName, string childFullNamePrefix, ReadOnlyCollection<string> formatSpecifiers, DkmEvaluationResultFlags flags, string editableValue, ResultProvider resultProvider) { Debug.Assert(proxyValue != null); var proxyType = proxyValue.Type; var proxyTypeAndInfo = new TypeAndCustomInfo(proxyType); var proxyMembers = MemberExpansion.CreateExpansion( inspectionContext, proxyTypeAndInfo, proxyValue, ExpansionFlags.IncludeBaseMembers, TypeHelpers.IsPublic, resultProvider, isProxyType: true, supportsFavorites: false); if (proxyMembers != null) { string proxyMemberFullNamePrefix = null; if (childFullNamePrefix != null) { proxyMemberFullNamePrefix = resultProvider.FullNameProvider.GetClrObjectCreationExpression( inspectionContext, proxyTypeAndInfo.ClrType, proxyTypeAndInfo.Info, new[] { childFullNamePrefix }); } _proxyItem = new EvalResult( ExpansionKind.Default, name: string.Empty, typeDeclaringMemberAndInfo: default(TypeAndCustomInfo), declaredTypeAndInfo: proxyTypeAndInfo, useDebuggerDisplay: false, value: proxyValue, displayValue: null, expansion: proxyMembers, childShouldParenthesize: false, fullName: null, childFullNamePrefixOpt: proxyMemberFullNamePrefix, formatSpecifiers: Formatter.NoFormatSpecifiers, category: default(DkmEvaluationResultCategory), flags: default(DkmEvaluationResultFlags), editableValue: null, inspectionContext: inspectionContext); } _name = name; _typeDeclaringMemberAndInfoOpt = typeDeclaringMemberAndInfoOpt; _declaredTypeAndInfo = declaredTypeAndInfo; _value = value; _childShouldParenthesize = childShouldParenthesize; _fullName = fullName; _childFullNamePrefix = childFullNamePrefix; _formatSpecifiers = formatSpecifiers; _flags = flags; _editableValue = editableValue; } internal override void GetRows( ResultProvider resultProvider, ArrayBuilder<EvalResult> rows, DkmInspectionContext inspectionContext, EvalResultDataItem parent, DkmClrValue value, int startIndex, int count, bool visitAll, ref int index) { if (_proxyItem != null) { _proxyItem.Expansion.GetRows(resultProvider, rows, inspectionContext, _proxyItem.ToDataItem(), _proxyItem.Value, startIndex, count, visitAll, ref index); } if (InRange(startIndex, count, index)) { rows.Add(this.CreateRawViewRow(resultProvider, inspectionContext)); } index++; } private EvalResult CreateRawViewRow( ResultProvider resultProvider, DkmInspectionContext inspectionContext) { return new EvalResult( ExpansionKind.RawView, _name, _typeDeclaringMemberAndInfoOpt, _declaredTypeAndInfo, useDebuggerDisplay: false, value: _value, displayValue: null, expansion: CreateRawView(resultProvider, inspectionContext, _declaredTypeAndInfo, _value), childShouldParenthesize: _childShouldParenthesize, fullName: _fullName, childFullNamePrefixOpt: _childFullNamePrefix, formatSpecifiers: Formatter.AddFormatSpecifier(_formatSpecifiers, "raw"), category: DkmEvaluationResultCategory.Data, flags: _flags | DkmEvaluationResultFlags.ReadOnly, editableValue: _editableValue, inspectionContext: inspectionContext); } private static Expansion CreateRawView( ResultProvider resultProvider, DkmInspectionContext inspectionContext, TypeAndCustomInfo declaredTypeAndInfo, DkmClrValue value) { return resultProvider.GetTypeExpansion(inspectionContext, declaredTypeAndInfo, value, ExpansionFlags.IncludeBaseMembers, supportsFavorites: false); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.VisualStudio.Debugger.Evaluation; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; using System.Collections.ObjectModel; using System.Diagnostics; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { /// <summary> /// Debugger type proxy expansion. /// </summary> /// <remarks> /// May include <see cref="System.Collections.IEnumerable"/> and /// <see cref="System.Collections.Generic.IEnumerable{T}"/> as special cases. /// (The proxy is not declared by an attribute, but is known to debugger.) /// </remarks> internal sealed class DebuggerTypeProxyExpansion : Expansion { internal static Expansion CreateExpansion( ResultProvider resultProvider, DkmInspectionContext inspectionContext, string name, TypeAndCustomInfo typeDeclaringMemberAndInfoOpt, TypeAndCustomInfo declaredTypeAndInfo, DkmClrValue value, bool childShouldParenthesize, string fullName, string childFullNamePrefix, ReadOnlyCollection<string> formatSpecifiers, DkmEvaluationResultFlags flags, string editableValue) { Debug.Assert((inspectionContext.EvaluationFlags & DkmEvaluationFlags.NoExpansion) == 0); // Note: The native EE uses the proxy type, even for // null instances, so statics on the proxy type are // displayed. That case is not supported currently. if (!value.IsNull) { var proxyType = value.Type.GetProxyType(); if (proxyType != null) { if ((inspectionContext.EvaluationFlags & DkmEvaluationFlags.ShowValueRaw) != 0) { var rawView = CreateRawView(resultProvider, inspectionContext, declaredTypeAndInfo, value); Debug.Assert(rawView != null); return rawView; } DkmClrValue proxyValue; try { proxyValue = value.InstantiateProxyType(inspectionContext, proxyType); } catch { proxyValue = null; } if (proxyValue != null) { return new DebuggerTypeProxyExpansion( inspectionContext, proxyValue, name, typeDeclaringMemberAndInfoOpt, declaredTypeAndInfo, value, childShouldParenthesize, fullName, childFullNamePrefix, formatSpecifiers, flags, editableValue, resultProvider); } } } return null; } private readonly EvalResult _proxyItem; private readonly string _name; private readonly TypeAndCustomInfo _typeDeclaringMemberAndInfoOpt; private readonly TypeAndCustomInfo _declaredTypeAndInfo; private readonly DkmClrValue _value; private readonly bool _childShouldParenthesize; private readonly string _fullName; private readonly string _childFullNamePrefix; private readonly ReadOnlyCollection<string> _formatSpecifiers; private readonly DkmEvaluationResultFlags _flags; private readonly string _editableValue; private DebuggerTypeProxyExpansion( DkmInspectionContext inspectionContext, DkmClrValue proxyValue, string name, TypeAndCustomInfo typeDeclaringMemberAndInfoOpt, TypeAndCustomInfo declaredTypeAndInfo, DkmClrValue value, bool childShouldParenthesize, string fullName, string childFullNamePrefix, ReadOnlyCollection<string> formatSpecifiers, DkmEvaluationResultFlags flags, string editableValue, ResultProvider resultProvider) { Debug.Assert(proxyValue != null); var proxyType = proxyValue.Type; var proxyTypeAndInfo = new TypeAndCustomInfo(proxyType); var proxyMembers = MemberExpansion.CreateExpansion( inspectionContext, proxyTypeAndInfo, proxyValue, ExpansionFlags.IncludeBaseMembers, TypeHelpers.IsPublic, resultProvider, isProxyType: true, supportsFavorites: false); if (proxyMembers != null) { string proxyMemberFullNamePrefix = null; if (childFullNamePrefix != null) { proxyMemberFullNamePrefix = resultProvider.FullNameProvider.GetClrObjectCreationExpression( inspectionContext, proxyTypeAndInfo.ClrType, proxyTypeAndInfo.Info, new[] { childFullNamePrefix }); } _proxyItem = new EvalResult( ExpansionKind.Default, name: string.Empty, typeDeclaringMemberAndInfo: default(TypeAndCustomInfo), declaredTypeAndInfo: proxyTypeAndInfo, useDebuggerDisplay: false, value: proxyValue, displayValue: null, expansion: proxyMembers, childShouldParenthesize: false, fullName: null, childFullNamePrefixOpt: proxyMemberFullNamePrefix, formatSpecifiers: Formatter.NoFormatSpecifiers, category: default(DkmEvaluationResultCategory), flags: default(DkmEvaluationResultFlags), editableValue: null, inspectionContext: inspectionContext); } _name = name; _typeDeclaringMemberAndInfoOpt = typeDeclaringMemberAndInfoOpt; _declaredTypeAndInfo = declaredTypeAndInfo; _value = value; _childShouldParenthesize = childShouldParenthesize; _fullName = fullName; _childFullNamePrefix = childFullNamePrefix; _formatSpecifiers = formatSpecifiers; _flags = flags; _editableValue = editableValue; } internal override void GetRows( ResultProvider resultProvider, ArrayBuilder<EvalResult> rows, DkmInspectionContext inspectionContext, EvalResultDataItem parent, DkmClrValue value, int startIndex, int count, bool visitAll, ref int index) { if (_proxyItem != null) { _proxyItem.Expansion.GetRows(resultProvider, rows, inspectionContext, _proxyItem.ToDataItem(), _proxyItem.Value, startIndex, count, visitAll, ref index); } if (InRange(startIndex, count, index)) { rows.Add(this.CreateRawViewRow(resultProvider, inspectionContext)); } index++; } private EvalResult CreateRawViewRow( ResultProvider resultProvider, DkmInspectionContext inspectionContext) { return new EvalResult( ExpansionKind.RawView, _name, _typeDeclaringMemberAndInfoOpt, _declaredTypeAndInfo, useDebuggerDisplay: false, value: _value, displayValue: null, expansion: CreateRawView(resultProvider, inspectionContext, _declaredTypeAndInfo, _value), childShouldParenthesize: _childShouldParenthesize, fullName: _fullName, childFullNamePrefixOpt: _childFullNamePrefix, formatSpecifiers: Formatter.AddFormatSpecifier(_formatSpecifiers, "raw"), category: DkmEvaluationResultCategory.Data, flags: _flags | DkmEvaluationResultFlags.ReadOnly, editableValue: _editableValue, inspectionContext: inspectionContext); } private static Expansion CreateRawView( ResultProvider resultProvider, DkmInspectionContext inspectionContext, TypeAndCustomInfo declaredTypeAndInfo, DkmClrValue value) { return resultProvider.GetTypeExpansion(inspectionContext, declaredTypeAndInfo, value, ExpansionFlags.IncludeBaseMembers, supportsFavorites: false); } } }
-1
dotnet/roslyn
56,416
Do not include function type conversions in user-defined conversions
Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
cston
"2021-09-15T18:16:38Z"
"2021-09-24T23:24:46Z"
bb99d0bc89bde01650d2a694d720d600dd952dcb
3913f352cf066fa485869d866e4753fa721cbe93
Do not include function type conversions in user-defined conversions. Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
./src/EditorFeatures/Test/RenameTracking/RenameTrackingTestState.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.Implementation.RenameTracking; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Editor.UnitTests.Utilities; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Composition; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Microsoft.VisualStudio.Text.Operations; using Microsoft.VisualStudio.Text.Tagging; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.RenameTracking { internal sealed class RenameTrackingTestState : IDisposable { private readonly ITagger<RenameTrackingTag> _tagger; public readonly TestWorkspace Workspace; private readonly IWpfTextView _view; private readonly ITextUndoHistoryRegistry _historyRegistry; private string _notificationMessage = null; private readonly TestHostDocument _hostDocument; public TestHostDocument HostDocument { get { return _hostDocument; } } private readonly IEditorOperations _editorOperations; public IEditorOperations EditorOperations { get { return _editorOperations; } } private readonly MockRefactorNotifyService _mockRefactorNotifyService; public MockRefactorNotifyService RefactorNotifyService { get { return _mockRefactorNotifyService; } } private readonly RenameTrackingCodeRefactoringProvider _codeRefactoringProvider; private readonly RenameTrackingCancellationCommandHandler _commandHandler = new RenameTrackingCancellationCommandHandler(); public static RenameTrackingTestState Create( string markup, string languageName, bool onBeforeGlobalSymbolRenamedReturnValue = true, bool onAfterGlobalSymbolRenamedReturnValue = true) { var workspace = CreateTestWorkspace(markup, languageName); return new RenameTrackingTestState(workspace, languageName, onBeforeGlobalSymbolRenamedReturnValue, onAfterGlobalSymbolRenamedReturnValue); } public static RenameTrackingTestState CreateFromWorkspaceXml( string workspaceXml, string languageName, bool onBeforeGlobalSymbolRenamedReturnValue = true, bool onAfterGlobalSymbolRenamedReturnValue = true) { var workspace = CreateTestWorkspace(workspaceXml); return new RenameTrackingTestState(workspace, languageName, onBeforeGlobalSymbolRenamedReturnValue, onAfterGlobalSymbolRenamedReturnValue); } public RenameTrackingTestState( TestWorkspace workspace, string languageName, bool onBeforeGlobalSymbolRenamedReturnValue = true, bool onAfterGlobalSymbolRenamedReturnValue = true) { this.Workspace = workspace; _hostDocument = Workspace.Documents.First(); _view = _hostDocument.GetTextView(); _view.Caret.MoveTo(new SnapshotPoint(_view.TextSnapshot, _hostDocument.CursorPosition.Value)); _editorOperations = Workspace.GetService<IEditorOperationsFactoryService>().GetEditorOperations(_view); _historyRegistry = Workspace.ExportProvider.GetExport<ITextUndoHistoryRegistry>().Value; _mockRefactorNotifyService = new MockRefactorNotifyService { OnBeforeSymbolRenamedReturnValue = onBeforeGlobalSymbolRenamedReturnValue, OnAfterSymbolRenamedReturnValue = onAfterGlobalSymbolRenamedReturnValue }; // Mock the action taken by the workspace INotificationService var notificationService = (INotificationServiceCallback)Workspace.Services.GetRequiredService<INotificationService>(); var callback = new Action<string, string, NotificationSeverity>((message, title, severity) => _notificationMessage = message); notificationService.NotificationCallback = callback; var tracker = new RenameTrackingTaggerProvider( Workspace.ExportProvider.GetExportedValue<IThreadingContext>(), Workspace.ExportProvider.GetExport<IInlineRenameService>().Value, Workspace.ExportProvider.GetExport<IDiagnosticAnalyzerService>().Value, Workspace.ExportProvider.GetExportedValue<IAsynchronousOperationListenerProvider>()); _tagger = tracker.CreateTagger<RenameTrackingTag>(_hostDocument.GetTextBuffer()); if (languageName is LanguageNames.CSharp or LanguageNames.VisualBasic) { _codeRefactoringProvider = new RenameTrackingCodeRefactoringProvider( _historyRegistry, SpecializedCollections.SingletonEnumerable(_mockRefactorNotifyService)); } else { throw new ArgumentException("Invalid language name: " + languageName, nameof(languageName)); } } private static TestWorkspace CreateTestWorkspace(string code, string languageName) { return CreateTestWorkspace(string.Format(@" <Workspace> <Project Language=""{0}"" CommonReferences=""true""> <Document>{1}</Document> </Project> </Workspace>", languageName, code)); } private static TestWorkspace CreateTestWorkspace(string xml) { return TestWorkspace.Create(xml, composition: EditorTestCompositions.EditorFeaturesWpf); } public void SendEscape() => _commandHandler.ExecuteCommand(new EscapeKeyCommandArgs(_view, _view.TextBuffer), TestCommandExecutionContext.Create()); public void MoveCaret(int delta) { var position = _view.Caret.Position.BufferPosition.Position; _view.Caret.MoveTo(new SnapshotPoint(_view.TextSnapshot, position + delta)); } public void Undo(int count = 1) { var history = _historyRegistry.GetHistory(_view.TextBuffer); history.Undo(count); } public void Redo(int count = 1) { var history = _historyRegistry.GetHistory(_view.TextBuffer); history.Redo(count); } public async Task AssertNoTag() { await WaitForAsyncOperationsAsync(); var tags = _tagger.GetTags(_view.TextBuffer.CurrentSnapshot.GetSnapshotSpanCollection()); Assert.Equal(0, tags.Count()); } /// <param name="textSpan">If <see langword="null"/> the current caret position will be used.</param> public async Task<CodeAction> TryGetCodeActionAsync(TextSpan? textSpan = null) { var span = textSpan ?? new TextSpan(_view.Caret.Position.BufferPosition, 0); var document = this.Workspace.CurrentSolution.GetDocument(_hostDocument.Id); var actions = new List<CodeAction>(); var context = new CodeRefactoringContext( document, span, actions.Add, CancellationToken.None); await _codeRefactoringProvider.ComputeRefactoringsAsync(context); return actions.SingleOrDefault(); } public async Task AssertTag(string expectedFromName, string expectedToName, bool invokeAction = false) { await WaitForAsyncOperationsAsync(); var tags = _tagger.GetTags(_view.TextBuffer.CurrentSnapshot.GetSnapshotSpanCollection()); // There should only ever be one tag Assert.Equal(1, tags.Count()); var tag = tags.Single(); // There should only be one code action for the tag var codeAction = await TryGetCodeActionAsync(tag.Span.Span.ToTextSpan()); Assert.NotNull(codeAction); Assert.Equal(string.Format(EditorFeaturesResources.Rename_0_to_1, expectedFromName, expectedToName), codeAction.Title); if (invokeAction) { var operations = (await codeAction.GetOperationsAsync(CancellationToken.None)).ToArray(); Assert.Equal(1, operations.Length); operations[0].TryApply(this.Workspace, new ProgressTracker(), CancellationToken.None); } } public void AssertNoNotificationMessage() => Assert.Null(_notificationMessage); public void AssertNotificationMessage() => Assert.NotNull(_notificationMessage); private async Task WaitForAsyncOperationsAsync() { var provider = Workspace.ExportProvider.GetExportedValue<AsynchronousOperationListenerProvider>(); await provider.WaitAllDispatcherOperationAndTasksAsync( Workspace, FeatureAttribute.RenameTracking, FeatureAttribute.SolutionCrawler, FeatureAttribute.Workspace, FeatureAttribute.EventHookup); } public void Dispose() => Workspace.Dispose(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.Implementation.RenameTracking; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Editor.UnitTests.Utilities; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Composition; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Microsoft.VisualStudio.Text.Operations; using Microsoft.VisualStudio.Text.Tagging; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.RenameTracking { internal sealed class RenameTrackingTestState : IDisposable { private readonly ITagger<RenameTrackingTag> _tagger; public readonly TestWorkspace Workspace; private readonly IWpfTextView _view; private readonly ITextUndoHistoryRegistry _historyRegistry; private string _notificationMessage = null; private readonly TestHostDocument _hostDocument; public TestHostDocument HostDocument { get { return _hostDocument; } } private readonly IEditorOperations _editorOperations; public IEditorOperations EditorOperations { get { return _editorOperations; } } private readonly MockRefactorNotifyService _mockRefactorNotifyService; public MockRefactorNotifyService RefactorNotifyService { get { return _mockRefactorNotifyService; } } private readonly RenameTrackingCodeRefactoringProvider _codeRefactoringProvider; private readonly RenameTrackingCancellationCommandHandler _commandHandler = new RenameTrackingCancellationCommandHandler(); public static RenameTrackingTestState Create( string markup, string languageName, bool onBeforeGlobalSymbolRenamedReturnValue = true, bool onAfterGlobalSymbolRenamedReturnValue = true) { var workspace = CreateTestWorkspace(markup, languageName); return new RenameTrackingTestState(workspace, languageName, onBeforeGlobalSymbolRenamedReturnValue, onAfterGlobalSymbolRenamedReturnValue); } public static RenameTrackingTestState CreateFromWorkspaceXml( string workspaceXml, string languageName, bool onBeforeGlobalSymbolRenamedReturnValue = true, bool onAfterGlobalSymbolRenamedReturnValue = true) { var workspace = CreateTestWorkspace(workspaceXml); return new RenameTrackingTestState(workspace, languageName, onBeforeGlobalSymbolRenamedReturnValue, onAfterGlobalSymbolRenamedReturnValue); } public RenameTrackingTestState( TestWorkspace workspace, string languageName, bool onBeforeGlobalSymbolRenamedReturnValue = true, bool onAfterGlobalSymbolRenamedReturnValue = true) { this.Workspace = workspace; _hostDocument = Workspace.Documents.First(); _view = _hostDocument.GetTextView(); _view.Caret.MoveTo(new SnapshotPoint(_view.TextSnapshot, _hostDocument.CursorPosition.Value)); _editorOperations = Workspace.GetService<IEditorOperationsFactoryService>().GetEditorOperations(_view); _historyRegistry = Workspace.ExportProvider.GetExport<ITextUndoHistoryRegistry>().Value; _mockRefactorNotifyService = new MockRefactorNotifyService { OnBeforeSymbolRenamedReturnValue = onBeforeGlobalSymbolRenamedReturnValue, OnAfterSymbolRenamedReturnValue = onAfterGlobalSymbolRenamedReturnValue }; // Mock the action taken by the workspace INotificationService var notificationService = (INotificationServiceCallback)Workspace.Services.GetRequiredService<INotificationService>(); var callback = new Action<string, string, NotificationSeverity>((message, title, severity) => _notificationMessage = message); notificationService.NotificationCallback = callback; var tracker = new RenameTrackingTaggerProvider( Workspace.ExportProvider.GetExportedValue<IThreadingContext>(), Workspace.ExportProvider.GetExport<IInlineRenameService>().Value, Workspace.ExportProvider.GetExport<IDiagnosticAnalyzerService>().Value, Workspace.ExportProvider.GetExportedValue<IAsynchronousOperationListenerProvider>()); _tagger = tracker.CreateTagger<RenameTrackingTag>(_hostDocument.GetTextBuffer()); if (languageName is LanguageNames.CSharp or LanguageNames.VisualBasic) { _codeRefactoringProvider = new RenameTrackingCodeRefactoringProvider( _historyRegistry, SpecializedCollections.SingletonEnumerable(_mockRefactorNotifyService)); } else { throw new ArgumentException("Invalid language name: " + languageName, nameof(languageName)); } } private static TestWorkspace CreateTestWorkspace(string code, string languageName) { return CreateTestWorkspace(string.Format(@" <Workspace> <Project Language=""{0}"" CommonReferences=""true""> <Document>{1}</Document> </Project> </Workspace>", languageName, code)); } private static TestWorkspace CreateTestWorkspace(string xml) { return TestWorkspace.Create(xml, composition: EditorTestCompositions.EditorFeaturesWpf); } public void SendEscape() => _commandHandler.ExecuteCommand(new EscapeKeyCommandArgs(_view, _view.TextBuffer), TestCommandExecutionContext.Create()); public void MoveCaret(int delta) { var position = _view.Caret.Position.BufferPosition.Position; _view.Caret.MoveTo(new SnapshotPoint(_view.TextSnapshot, position + delta)); } public void Undo(int count = 1) { var history = _historyRegistry.GetHistory(_view.TextBuffer); history.Undo(count); } public void Redo(int count = 1) { var history = _historyRegistry.GetHistory(_view.TextBuffer); history.Redo(count); } public async Task AssertNoTag() { await WaitForAsyncOperationsAsync(); var tags = _tagger.GetTags(_view.TextBuffer.CurrentSnapshot.GetSnapshotSpanCollection()); Assert.Equal(0, tags.Count()); } /// <param name="textSpan">If <see langword="null"/> the current caret position will be used.</param> public async Task<CodeAction> TryGetCodeActionAsync(TextSpan? textSpan = null) { var span = textSpan ?? new TextSpan(_view.Caret.Position.BufferPosition, 0); var document = this.Workspace.CurrentSolution.GetDocument(_hostDocument.Id); var actions = new List<CodeAction>(); var context = new CodeRefactoringContext( document, span, actions.Add, CancellationToken.None); await _codeRefactoringProvider.ComputeRefactoringsAsync(context); return actions.SingleOrDefault(); } public async Task AssertTag(string expectedFromName, string expectedToName, bool invokeAction = false) { await WaitForAsyncOperationsAsync(); var tags = _tagger.GetTags(_view.TextBuffer.CurrentSnapshot.GetSnapshotSpanCollection()); // There should only ever be one tag Assert.Equal(1, tags.Count()); var tag = tags.Single(); // There should only be one code action for the tag var codeAction = await TryGetCodeActionAsync(tag.Span.Span.ToTextSpan()); Assert.NotNull(codeAction); Assert.Equal(string.Format(EditorFeaturesResources.Rename_0_to_1, expectedFromName, expectedToName), codeAction.Title); if (invokeAction) { var operations = (await codeAction.GetOperationsAsync(CancellationToken.None)).ToArray(); Assert.Equal(1, operations.Length); operations[0].TryApply(this.Workspace, new ProgressTracker(), CancellationToken.None); } } public void AssertNoNotificationMessage() => Assert.Null(_notificationMessage); public void AssertNotificationMessage() => Assert.NotNull(_notificationMessage); private async Task WaitForAsyncOperationsAsync() { var provider = Workspace.ExportProvider.GetExportedValue<AsynchronousOperationListenerProvider>(); await provider.WaitAllDispatcherOperationAndTasksAsync( Workspace, FeatureAttribute.RenameTracking, FeatureAttribute.SolutionCrawler, FeatureAttribute.Workspace, FeatureAttribute.EventHookup); } public void Dispose() => Workspace.Dispose(); } }
-1
dotnet/roslyn
56,416
Do not include function type conversions in user-defined conversions
Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
cston
"2021-09-15T18:16:38Z"
"2021-09-24T23:24:46Z"
bb99d0bc89bde01650d2a694d720d600dd952dcb
3913f352cf066fa485869d866e4753fa721cbe93
Do not include function type conversions in user-defined conversions. Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/LinkedListExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // 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; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static class LinkedListExtensions { public static void AddRangeAtHead<T>(this LinkedList<T> list, IEnumerable<T> values) { LinkedListNode<T>? currentNode = null; foreach (var value in values) { if (currentNode == null) { currentNode = list.AddFirst(value); } else { currentNode = list.AddAfter(currentNode, value); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static class LinkedListExtensions { public static void AddRangeAtHead<T>(this LinkedList<T> list, IEnumerable<T> values) { LinkedListNode<T>? currentNode = null; foreach (var value in values) { if (currentNode == null) { currentNode = list.AddFirst(value); } else { currentNode = list.AddAfter(currentNode, value); } } } } }
-1